JS bootstrap smooth scroll offset

I need the smooth scroll to be offset by 100px. So far I have this:

$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});
      

Run codeHide result


It makes me move! But how can I add .offset (). Top> 100 to this? I'm having trouble figuring out if anyone can help.

+3


source to share


2 answers


It looks like you have a fixed navbar. Assuming your anchors are empty:

<a class="anchor" id="foo"></a>

      

Just offset anchors in css:



.anchor {
    top: -100px;
    position: relative;
    display: block;
}

      

Alternatively, you can compensate for the scrollTop by updating your javascript:

scrollTop: $($anchor.attr('href')).offset().top - 100

      

+1


source


ve1jdramas Hi. Check out the link here .

In this example, they use + or - .

Like this ... scrollTop: target.offset().top -100


or
scrollTop: target.offset().top +100



Try this and see if you can make this work for you.
Or use this complete code.

$(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 -100
            }, 1000);
            return false;
          }
        }
      });
    });

      

+1


source







All Articles