Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery smooth scroll to an anchor?

Is there a way to scroll down to an anchor link using jQuery?

Like:

$(document).ready(function(){   $("#gotomyanchor").click(function(){       $.scrollSmoothTo($("#myanchor"));   }); }); 

?

like image 465
dynamic Avatar asked Nov 16 '10 19:11

dynamic


People also ask

How do I smooth scroll to anchor?

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 I scroll to anchor tag?

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 .


1 Answers

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/

like image 186
hanoo Avatar answered Sep 22 '22 19:09

hanoo