Scroll to an element with jQuery

Solution 1:

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="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></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>

Solution 2:

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

Options:

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.

Solution 3:

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:

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

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.

Solution 4:

This is achievable without jQuery:

document.getElementById("element-id").scrollIntoView();

Solution 5:

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.