-1

I want to create navigation with anchor URL' and smooth scroll. But on that page I use a sticky header with a height of 88px.

How can I create a smooth scroll, based on class product-anchor-links-action?

JSFiddle: https://jsfiddle.net/rx0txmek/2/

My current HTML:

<div class="product-page-nav">
    <div class="container">
    <ol class="product-anchor-links-list">
        <li class="product-anchor-links-item"><a href="#productbeschrijving" class="product-anchor-links-action">Nav 1</a></li>
        <li class="product-anchor-links-item"><a href="#specificaties" class="product-anchor-links-action">Nav 2</a></li>
        <li class="product-anchor-links-item"><a href="#reviews" class="product-anchor-links-action">Nav 3</a></li>
    </ol>
    </div>
</div>

jQuery:

    $(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
JGeer
  • 1,574
  • 22
  • 62
  • You aware you don't have any element with id `reviews`, right?!.... I really don't get your question because you have all you need in jsFiddle, just looks like you didn't put much effort to understand your code – A. Wolff Oct 19 '16 at 10:17
  • @A.Wolff Thanks for your reply. Yes I was aware of the, but I changed the fiddle, so that is complete. To only thing is that I can not get it right/working. The smooth scroll is not working and can not get it right, that it is based on the class. – JGeer Oct 19 '16 at 10:21
  • Your jsFiddle works as expected so maybe explain instead what are you expecting? `that it is based on the class` What do you mean? – A. Wolff Oct 19 '16 at 10:23
  • @A.Wolff Thanks! It currently works, but it does check the a href, instead of the class name `product-anchor-links-action`. So to should only work for elements with that class. So that other class will not influanced. – JGeer Oct 19 '16 at 10:50
  • `$('.product-anchor-links-action').click(...);`?! – A. Wolff Oct 19 '16 at 10:54

1 Answers1

2

Just subtract the height of the sticky header from the scrollTop value. When there is no sticky, the value will be 0 (you can just use the .height() value if the sticky is always present).

$('a').click(function(){

    var stickyHeight = $('.sticky').length ? $('.sticky').height() : 0

    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top - stickyHeight 
    }, 500);
    return false;
});  

If there is no $('.stickyHeader')

poisonborz
  • 68
  • 7