How to Scroll to the Top of the Page Using JavaScript
Read this tutorial and find useful information about the simplest native JavaScript method and its parameters to make the page jump on the top instantly.
Scrolling to the top of the page instantly can be done with the native JavaScript method: <kbd class="highlighted">window.scrollTo(x-coord, y-coord)</kbd>. This method of the window interface scrolls to a particular set of coordinates in the document. It has two parameters: the x and y.
- x-coord - pixel along the horizontal axis.
- y-coord - pixel along the vertical axis.
window.scrollTo(x-coordinate, y-coordinate)Setting both parameters to 0 will scroll the page to the topmost and leftmost point.
function scrollToTop() {
window.scrollTo(0, 0);
}Example:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.scroll {
height: 1200px;
background-color: yellow;
}
</style>
</head>
<body>
<h1> Scroll </h1>
<p class="scroll">This is a large scrollable area.</p>
<button onclick="scrollToTop()">
Click to scroll to top
</button>
<script>
function scrollToTop() {
window.scrollTo(0, 0);
}
</script>
</body>
</html>Window Interface
The Window interface represents a window that includes a DOM document.
It is the host of a variety of functions, objects, namespaces, and constructors that are not associated with the user interface window. The Window Interface is a place to include these items needed to be globally available.
The window global variable representing the window in which the script is running is exposed to JavaScript code.