javascript - Scroll to an element with jQuery

ID : 280

viewed : 352

Tags : javascriptjqueryscrolljavascript

Top 5 Answer for javascript - Scroll to an element with jQuery

vote vote


Assuming you have a button with the id button, try this example:

$("#button").click(function() {     $([document.documentElement, document.body]).animate({         scrollTop: $("#elementtoScrollToID").offset().top     }, 2000); }); 

I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.

<html>     <script src=""></script>     <script>         $(document).ready(function (){             $("#click").click(function (){                 $('html, body').animate({                     scrollTop: $("#div1").offset().top                 }, 2000);             });         });     </script>     <div id="div1" style="height: 1000px; width 100px">         Test     </div>     <br/>     <div id="div2" style="height: 1000px; width 100px">         Test 2     </div>     <button id="click">Click me</button> </html>

vote vote


jQuery .scrollTo() Method

jQuery .scrollTo(): View - Demo, API, Source

I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?

Examples Usage:

$('body').scrollTo('#target'); // Scroll screen to target element  $('body').scrollTo(500); // Scroll screen 500 pixels down  $('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down 


scrollTarget: A element, string, or number which indicates desired scroll position.

offsetTop: A number that defines additional spacing above scroll target.

duration: A string or number determining how long the animation will run.

easing: A string indicating which easing function to use for the transition.

complete: A function to call once the animation is complete.

vote vote


If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:

So all you need to do is: $("selector").get(0).scrollIntoView();

.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.

vote vote


This is achievable without jQuery:

vote vote


Using this simple script

if($(window.location.hash).length > 0){         $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000); } 

Would make in sort that if a hash tag is found in the url, the scrollTo animate to the ID. If not hash tag found, then ignore the script.

Top 3 video Explaining javascript - Scroll to an element with jQuery