How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.
To scroll to the top of the page instantly using JavaScript, you can use the window.scrollTo() method or the window.scroll() method with the x and y coordinates set to 0. Here's an example:
html
<!DOCTYPE html>
<html>
<head>
    <title>Scroll to Top</title>
</head>
<body>
    <button onclick="scrollToTop()">Scroll to Top</button>
    <script>
        function scrollToTop() {
            // Scroll to the top of the page
            window.scrollTo(0, 0);
        }
    </script>
</body>
</html>
In this example:
We have an HTML button with an
onclickattribute that calls thescrollToTop()JavaScript function when clicked.Inside the
scrollToTop()function, we use thewindow.scrollTo(0, 0)method to scroll to the top of the page. The0values for bothxandycoordinates specify that we want to scroll to the top of the page.
When you click the "Scroll to Top" button, the page will instantly jump to the top.
You can also achieve the same result using the window.scroll() method:
javascript
function scrollToTop() {
    // Scroll to the top of the page
    window.scroll(0, 0);
}
Both methods will immediately jump the scrollbar to the top of the page without any smooth scrolling animation.
Comments
Post a Comment