7 February 2024

This code snippet demonstrates how to retrieve the horizontal (x) and vertical (y) scroll coordinates of an element using the scrollLeft and scrollTop properties, respectively. One common use case for this functionality is to preserve the scroll position of an element and later restore it to provide a seamless user experience when navigating through content.

Source code viewer
  1. // Get the element you want to get the scroll offset from
  2. const element = document.getElementById('yourElementId');
  3.  
  4. // Get the current horizontal scroll offset (X)
  5. const scrollOffsetX = element.scrollLeft;
  6.  
  7. // Get the current vertical scroll offset (Y)
  8. const scrollOffsetY = element.scrollTop;
  9.  
  10. // Store the scroll offsets in an object
  11. const scrollOffsets = {
  12. x: scrollOffsetX,
  13. y: scrollOffsetY
  14. };
  15.  
  16. // Later: restore the scroll position
  17. element.scroll(scrollOffsets.x, scrollOffsets.y);
Programming Language: Javascript