Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

getScrollPosition

Returns the current scroll position of a given element or window.

TypeScript
Copied!
1/**
2 * Returns the current scroll position of a given element or window.
3 *
4 * @param target - The element or window to get the scroll position from.
5 * @returns An object with 'x' and 'y' scroll positions.
6 */
7export function getScrollPosition(
8  target: Element | Window = window
9): { x: number; y: number } {
10  if (typeof window === 'undefined') {
11    return { x: 0, y: 0 };
12  }
13
14  if (target === window) {
15    return {
16      x: window.scrollX ?? window.pageXOffset,
17      y: window.scrollY ?? window.pageYOffset,
18    };
19  }
20
21  return {
22    x: (target as Element).scrollLeft,
23    y: (target as Element).scrollTop,
24  };
25}
  • Supports Both Window and Element Targets

    Works seamlessly with both the global window object and individual DOM elements, enhancing flexibility.

  • Cross-Browser Compatibility

    Accounts for both scrollX/Y and legacy pageXOffset/YOffset to handle inconsistencies in browser implementations.

  • Safe Server-Side Rendering (SSR)

    Returns { x: 0, y: 0 } gracefully if window is undefined, avoiding crashes in SSR environments.

  • Simple and Consistent API

    Provides a clean return format ({ x, y }) regardless of the target, simplifying downstream logic.

Tests | Examples

TypeScript
Copied!
1test('returns scroll position of window', () => {
2  const result = getScrollPosition(window);
3  expect(result).toHaveProperty('x');
4  expect(result).toHaveProperty('y');
5});
6
7test('returns scroll position of a DOM element', () => {
8  const div = document.createElement('div');
9  div.style.overflow = 'scroll';
10  div.style.width = '100px';
11  div.style.height = '100px';
12  div.innerHTML = '<div style="width:1000px;height:1000px;"></div>';
13  document.body.appendChild(div);
14  div.scrollTop = 50;
15  div.scrollLeft = 25;
16
17  const pos = getScrollPosition(div);
18  expect(pos).toEqual({ x: 25, y: 50 });
19
20  document.body.removeChild(div);
21});
22
23test('returns {0, 0} in non-browser environments', () => {
24  const originalWindow = globalThis.window;
25  // @ts-ignore
26  delete globalThis.window;
27
28  expect(getScrollPosition()).toEqual({ x: 0, y: 0 });
29
30  globalThis.window = originalWindow;
31});

Common Use Cases

  • Custom Scroll Tracking

    Monitor scroll positions for sticky headers, infinite scroll triggers, or lazy loading logic.

  • Analytics & Interaction Logging

    Capture user scroll behavior for heatmaps or engagement analytics.

  • Smooth Scrolling Anchors

    Use position data to implement smooth scroll animations or restore scroll positions.

  • Visibility Checks

    Determine how far an element is scrolled to decide if it's in the viewport or should be animated.

Codebase: Utilities -> Browser & DOM -> getScrollPosition | Yevhen Klymentiev