Here's an example.
But first remember, getBoundingClientRect() will return values relative to the viewport.
<!DOCTYPE html> <html> <head> <style> div, p { font-size: 18px; } body { height: 2000px; width: 1000px; } #theText { width: 300px; padding: 10px; border: solid 1px #ddd; position: absolute; bottom: 2%; left: 30%; } p { position: fixed; } #coord { top: 50px; } </style> </head> <body> <h2>Scroll this page up and down</h2> <div id='theText'> Hi, I am a DIV element. Scroll this page up and down to get my position or the X and Y coordinates. 🙂 </div> <!-- display the coordinates of the above DIV --> <p id="coord"></p> </body> <script> window.addEventListener('scroll', function (e) { document.getElementById('coord').innerHTML = 'X: ' + theText.getBoundingClientRect().left + ' Y: ' + theText.getBoundingClientRect().top; }); </script> </html>
How to use .map() function to extract only numbers from an array of values?
Happy coding. 🙂