![Return the scroll position of the current page](https://javascriptsource.com/wp-content/uploads/2022/03/Return-the-scroll-position-of-the-current-page-702x526.jpg)
Use Window.pageXOffset
and Window.pageYOffset
if they are defined, otherwise Element.scrollLeft
and Element.scrollTop
.
Omit the single argument, el
, to use the global Window
object.
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// EXAMPLE
getScrollPosition(); // {x: 0, y: 200}