Question

I'm using the the JavaScript code below to create a scroll effect from my nav to the anchor.

The problem I am having is I want the scrolling to stop 100px above the anchor.

What would I need to change in this code to achieve this result?

$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
      if (target.length == 0) target = $('html');
      $('html, body').animate({ scrollTop: target.offset().top }, 1000);
      return false;
  });
});

Thank you

Was it helpful?

Solution

Subtract 100 pixels from target.offset().top. like so:

$(document).ready(function() {
  $('a[href^="#"]').click(function() {
      var target = $(this.hash);
      if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
      if (target.length == 0) target = $('html');
      $('html, body').animate({ scrollTop: target.offset().top-100 }, 1000);
      return false;
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top