Is there a way to scroll down to an anchor link using jQuery?
Like:
$(document).ready(function(){ $("#gotomyanchor").click(function(){ $.scrollSmoothTo($("#myanchor")); }); });
?
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.
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 .
Here is how I do it:
var hashTagActive = ""; $(".scroll").on("click touchstart" , function (event) { if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll. event.preventDefault(); //calculate destination place var dest = 0; if ($(this.hash).offset().top > $(document).height() - $(window).height()) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().top; } //go to destination $('html,body').animate({ scrollTop: dest }, 2000, 'swing'); hashTagActive = this.hash; } });
Then you just need to create your anchor like this:
<a class="scroll" href="#destination1">Destination 1</a>
You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/
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