Categories
JavaScript Answers

How to Scroll to the Top of a Browser Page with JavaScript?

Spread the love

Sometimes, we may want to scroll to the top of a browser page with JavaScript.

In this article, we’ll look at how to scroll to the top of a browser page with JavaScript.

Use the window.scrollTo Method

We can use the window.scrollTo method with the x and y coordinates to scroll to as arguments respectively.

For instance, if we have the following HTML:

<div>

</div>
<button>
  scroll to top
</button>

Then we can write the following JavaScript to add child elements to the div and make the button scroll to the top of the page by writing:

const button = document.querySelector('button')
const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

button.addEventListener('click', () => {
  window.scrollTo(0, 0);
})

We have the for loop to add elements with document.createElement .

And then we set the textContent to some content.

Then we call appendChild to add the elements.

Next, we call button.addEventListener with 'click' to add a click listener.

We call scrollTo with 0 and 0 to scroll to the top of the page.

So when we click on ‘scroll to top’, we should go to the top of the page.

We can also change the scroll behavior with an object to change the scroll behavior.

For instance, we can write:

button.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    behavior: `smooth`
  })
})

top is set to 0 to scroll to the top.

behavior is set to 'smooth' to make the scrolling smooth.

Conclusion

We can scroll to the top of the page with the window.scrollTo method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *