Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the scrollTop Property

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

Let's try out the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<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-3.5.1.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, like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Insert an Item into an Array at a Specific ... >>
<< How to Check If the Mouse is Over an Element in jQ...