get scroll position of element in javascript

To get the scroll position of an element in JavaScript, you can use the element.scrollTop property. This property returns the number of pixels that the content of an element is scrolled from the top.

Here's an example code snippet that demonstrates how to get the scroll position of a div element:

<div id="myDiv" style="height: 100px; overflow: auto">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  <p>Donec interdum, orci quis vestibulum lacinia, lorem sapien elementum eros, at eleifend eros augue a lectus.</p>
  <p>Etiam bibendum urna nec arcu tincidunt, sed porttitor tellus mollis.</p>
  <p>Proin tincidunt odio vel posuere dignissim.</p>
  <p>Curabitur in augue sed velit hendrerit rhoncus.</p>
  <p>Suspendisse potenti. Mauris hendrerit sapien at ipsum pharetra maximus.</p>
  <p>Quisque euismod augue non rutrum fermentum.</p>
  <p>Nullam quam dui, posuere non dolor vel, condimentum ultricies justo.</p>
  <p>Nam sollicitudin, turpis ac interdum consectetur, sem sapien luctus elit, a elementum elit elit et mi.</p>
  <p>Fusce vel laoreet odio, eget feugiat velit.</p>
  <p>Morbi convallis scelerisque augue, a mattis nisi consequat eget.</p>
  <p>Nulla facilisi.</p>
</div>
909 chars
15 lines
index.tsx
const myDiv = document.getElementById('myDiv');

myDiv.addEventListener('scroll', function() {
  const { scrollTop } = this;
  console.log('Scroll top:', scrollTop);
});
170 chars
7 lines

In this code, we listen to the scroll event on the myDiv element, and log the scrollTop value to the console.

gistlibby LogSnag