Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to 100px above the anchor

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

like image 486
Wiseguy Avatar asked Aug 16 '13 13:08

Wiseguy


People also ask

How do I scroll an HTML page to an anchor?

The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .

How do I create a smooth scrolling anchor link?

You can use window. scroll() with behavior: smooth and top set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.

How do you navigate to another page with a smooth scroll on a specific ID?

Modern Browsers detect the hash in the url and then automatically open that part. So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling. // direct browser to top right away if (window. location.

How do you prevent anchor links from scrolling behind a sticky header with one line in CSS?

You could add the scroll-padding-top CSS property to an HTML element with a value of 4rem . Now when you click the anchor link, the browser jumps to the anchor section but leaves padding of 4rem at the top, rather than scrolling the anchor point all the way to the top.


1 Answers

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;
  });
});
like image 148
Damiaan Dufaux Avatar answered Oct 12 '22 21:10

Damiaan Dufaux