Search code examples
jqueryscrollsmooth-scrollinganchor-scroll

Smooth Scroll to anchor edit page top


I am using a smooth scroll snippet. I have a fixed header, and would like the anchor sections to stop under my header. How would I edit this code to get them to stop roughly 100 pixels below the top of the page?

$(document).ready(function(){
  $('a[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) {
    var targetOffset = $target.offset(). top;
    $('html,body')
    .animate({scrollTop: targetOffset}, 1000);
   return false;
  }
}
});
});

I just need the sections to stop 100px below the page top. I am very new to jquery so please bare with my lack of knowledge. Thanks


Solution

  • You could simply add 100 to the targets offset from the top of the webpage as such:

        var targetOffset = $target.offset().top + 100;
        $('html,body')
        .animate({scrollTop: targetOffset}, 1000);