Sunday, January 19, 2025
HomeQ&AHow do I Scroll to the top of the page using JavaScript?

How do I Scroll to the top of the page using JavaScript?

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

See also  What gifts can Jehovah Witness accept and for what?

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).

See also  How tall is 67 inches?

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)

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x