How to get div tag scroll position using JavaScript?

Sometimes, we want to get div tag scroll position using JavaScript.

In this article, we’ll look at how to get div tag scroll position using JavaScript.

How to get div tag scroll position using JavaScript?

To get div tag scroll position using JavaScript, we can use the scrollTop property.

For instance, we write:

<div style='height: 100px; overflow-y: auto'>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
  <p>hello</p>
</div>

to add a scrollable div.

Then we write:

const div = document.querySelector('div')
div.addEventListener('scroll', () => {
  console.log(div.scrollTop)
})

to select the div with document.querySelector.

Then we call div.addEventListener with 'scroll' to add a scroll event listener.

And in the listener, we log the value of div.scrollTop.

Now when we scroll the div up and down, we should see the scroll position of the div in pixels.

Conclusion

To get div tag scroll position using JavaScript, we can use the scrollTop property.