How to Set the Scrollbar Position with JavaScript?

Sometimes, we want to set the scrollbar position with JavaScript.

In this article, we’ll look at how to set the scrollbar position with JavaScript.

Set the Scrollbar Position with JavaScript

To set the scrollbar position with JavaScript, we can set the scrollTop property of the scroll container element to the value of the offsetTop property of the element we want to scroll to.

For instance, if we have:

<div id='container' style='height: 100px; overflow-y: scroll'>
  <div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis augue a ante rutrum, non ornare erat maximus. Fusce sagittis nunc sed tellus sagittis, vitae volutpat odio faucibus. Nullam consequat ut mi a consequat. Praesent a porttitor magna. Donec placerat mollis sapien ac eleifend.
  </div>
  <div id='row'>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis augue a ante rutrum, non ornare erat maximus. Fusce sagittis nunc sed tellus sagittis, vitae volutpat odio faucibus. Nullam consequat ut mi a consequat. Praesent a porttitor magna. Donec placerat mollis sapien ac eleifend.
  </div>
</div>

Then we write:

const container = document.getElementById('container');
const rowToScrollTo = document.getElementById('row');

container.scrollTop = rowToScrollTo.offsetTop;

We get the scroll container with document.getElementById and assign it to container.

And we do the same with the element we want to scroll to and assign it to rowScrollTo.

Finally, we set rowScrollTo.offsetTop to container.scrollTop to do the scrolling to the div with ID row.

Conclusion

To set the scrollbar position with JavaScript, we can set the scrollTop property of the scroll container element to the value of the offsetTop property of the element we want to scroll to.