To scroll to the top of the page using JavaScript, you can use the following methods:
Method 1: Using window.scrollTo
window.scrollTo(0, 0)
This method scrolls the window to the specified coordinates (0, 0), which is the top-left corner of the page.
Method 2: Using document.body.scrollTop or document.documentElement.scrollTop
document.body.scrollTop = 0
// or
document.documentElement.scrollTop = 0
This method sets the scrollTop property of the body or html element to 0, effectively scrolling the page to the top.
Method 3: Using window.scrollBy() or window.scroll
window.scrollBy(0, -window.scrollY)
// or
window.scroll(0, 0)
These methods scroll the window by the specified amount (-window.scrollY) or to the specified coordinates (0, 0).
You can also use these methods in combination with other JavaScript events, such as clicking a button or scrolling to a specific element.
Example Use Cases:
– Scroll to top on page load:
window.addEventListener(‘load’, () => {window.scrollTo(0, 0)