Home >Web Front-end >JS Tutorial >How Can I Scroll to the Top of a Web Page Using JavaScript?
Scrolling to the Top of a Web Page with JavaScript
Moving to the top of a web page with JavaScript is a common task, especially when instant scrolling is desired. This can be easily achieved using the built-in window.scrollTo() method, which allows you to specify the desired position on the page.
JavaScript Code:
To scroll to the top of the page instantly, use the following code:
window.scrollTo(0, 0);
Parameters:
By passing in 0 for both xCoord and yCoord, you can scroll to the top left corner of the page instantly.
Example Usage:
<!DOCTYPE html> <html> <body> <p>Scroll down this page and then click the button.</p> <button onclick="window.scrollTo(0, 0)">Scroll to Top</button> </body> </html>
When the button is clicked, the page will instantly jump to the top.
Note: If you want to achieve smooth scrolling with animation, consider using JavaScript plugins or frameworks.
The above is the detailed content of How Can I Scroll to the Top of a Web Page Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!