How to Scroll to the Top of the Page Using jQuery/JavaScript ?

How to Scroll to the Top of the Page Using jQuery/JavaScript ?

Asked on November 2, 2018 in jQuery.
Add Comment


  • 2 Answer(s)

    The scrollTop Property

    The jQuery animate() method in combination with the scrollTop property to scroll to the top of the page smoothly with an animation.

    <head>
    <title>jQuery scrollTop Animation</title>
    <style>
        .scroll-top
        {
            position: fixed;
            bottom: 10px;
            right: 10px;
            z-index: 99;
    }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script>
    $(document).ready(function(){
        $(".scroll-top").click(function() {
            $("html, body").animate({
                 scrollTop: 0
              }, "slow");
          return false;
        });
    });
    </script>
    </head>
    <body>
            <button type="button" class="scroll-top">Go to Top</button>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
    </body>
    </html>
    

    However, if you simply want to scroll to the top of the page without any animation or jQuery you can use the native JavaScript window.scrollTo(x-coord, y-coord) method.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>JavaScript Scroll to Top</title>
    <style>
    .    scroll-top
    {
        position: fixed;
        bottom: 10px;
        right: 10px;
        z-index: 99;
    }
    </style>
    <script>
        function goToTop()
    {
        window.scrollTo(0, 0);
    }
    </script>
    </head>
    <body>
        <button type="button" class="scroll-top" onclick="goToTop();">Go to Top</button>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
    </body>
    </html>
    

    The same thing using the bookmark anchor, like <a href=”#top”>Go to Top</a>.

    However, it will add the string #top in the URL of the page.

     

    Answered on November 2, 2018.
    Add Comment

    $(“a[href=’#top’]”).click(function() {
    $
    (“html, body”).animate({ scrollTop: 0 }, “slow”);
    return false;
    });

    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.