Home > Web Front-end > JS Tutorial > How Can I Scroll to the Top of a Web Page Using JavaScript?

How Can I Scroll to the Top of a Web Page Using JavaScript?

Susan Sarandon
Release: 2024-11-29 01:40:11
Original
661 people have browsed it

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);
Copy after login

Parameters:

  • xCoord: The horizontal coordinate (in pixels) to scroll to. Set this to 0 to scroll to the left edge.
  • yCoord: The vertical coordinate (in pixels) to scroll to. Set this to 0 to scroll to the top.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template