We can use jQuery to scroll to the top of the page by using the jQuery animate method along with the scrollTop property.
$("html, body").animate({ scrollTop: 0 }, "slow");
Let’s say I have the following HTML:
Top
To scroll to top of the page, we can use the jQuery animate method in the following JavaScript code:
$("html, body").animate({ scrollTop: 0 }, "slow");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("html, body").animate({ scrollTop: 0 }, "slow");
Note we can also do this in pure JavaScript using the scrollTo() method.
Scrolling to Top of the Page On Click Using jQuery
Let’s say we have the following HTML code and we want to scroll smoothly to the top of the page.
Scroll Top
We can utilize both the jQuery click() method and jQuery animate() method to scroll to the top of the page.
Below is the JavaScript code which will allow the user to scroll to the top:
$("#click-me").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
});
The final code and output for this example of how to scroll to the top of the page using jQuery and JavaScript is below.
Code Output:
Full Code:
Scroll Top
Hopefully this article has been useful for you to understand how to use jQuery to scroll to the top of the page.