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
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 .
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.
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.
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.
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With