Scroll to 100px above the anchor

I use the JavaScript code below to create a scroll effect from my navigator to anchor.

The problem I am facing is that I want the scroll to stop 100 pixels above the anchor.

What do 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; }); }); 

thanks

+4
source share
1 answer

Subtract 100 pixels from target.offset (). top. 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; }); }); 
+11
source

Source: https://habr.com/ru/post/1497436/


All Articles