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
// Get the element you want to get the scroll offset from const element = document.getElementById('yourElementId'); // Get the current horizontal scroll offset (X) const scrollOffsetX = element.scrollLeft; // Get the current vertical scroll offset (Y) const scrollOffsetY = element.scrollTop; // Store the scroll offsets in an object const scrollOffsets = { x: scrollOffsetX, y: scrollOffsetY }; // Later: restore the scroll position element.scroll(scrollOffsets.x, scrollOffsets.y);Programming Language: Javascript