Categories
JavaScript Answers

How to Scroll Back to the Top of a Scrollable Div with JavaScript?

Spread the love

Sometimes, we want to scroll back to the top of a scrollable div with JavaScript.

In this article, we’ll look at how to scroll back to the top of a scrollable div with JavaScript.

Use the scroll Method

We can use the scroll method of an element to scroll a scrollable div back to the top.

For instance, if we have the following HTML:

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

</div>

And the following CSS:

div {
  height: 300px;
  overflow-y: scroll;
}

Then we can add some content to the div and make the div scroll to the top when we click the button by writing:

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

const btn = document.querySelector('button')
btn.addEventListener('click', () => {
  div.scroll({
    top: 0,
    behavior: 'smooth'
  });
});

We get the div with document.querySelector .

Then we add a for loop to add some content to the div with document.createElement to create a p element.

And we call div.appendChild to append the p elements to the div.

Next, we get the button with document.querySelector .

And then we call addEventListener on the button to add a click listener.

In the click listener, we call div.scroll with an object with top set to 0 to scroll to the top.

And behavior is set to 'smooth' to add smooth scrolling.

Now when we click on the scroll to top button, the scrollable div should go back to the top with smooth scrolling motion during scrolling.

Conclusion

We can use the scroll method to scroll a div to the top.

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 *