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

getScrollHeight

Returns the total scrollable height of an element or the document.

TypeScript
Copied!
1/**
2 * Returns the total scrollable height of an element or the document.
3 *
4 * @param element - The target element or document.
5 * @returns The total scrollable height in pixels.
6 */
7export function getScrollHeight(element: HTMLElement | Document = document): number {
8  if (element === document) {
9    const body = document.body;
10    const html = document.documentElement;
11    return Math.max(
12      body.scrollHeight,
13      html.scrollHeight,
14      body.offsetHeight,
15      html.offsetHeight,
16      body.clientHeight,
17      html.clientHeight
18    );
19  }
20
21  return element.scrollHeight;
22}
  • Handles Both Document and Elements

    Supports computing scroll height for standard DOM elements as well as the full document, increasing its versatility.

  • Cross-Browser Compatibility

    Uses Math.max() with multiple properties (scrollHeight, offsetHeight, clientHeight) to ensure accuracy across different rendering engines.

  • Graceful Default

    Defaults to the full document if no element is provided, making it convenient for common use cases without additional setup.

  • Single Source of Truth

    Consolidates multiple browser quirks into one reliable utility, avoiding scattered and inconsistent scroll height logic.

Tests | Examples

TypeScript
Copied!
1test('getScrollHeight returns scrollHeight for element', () => {
2  const div = document.createElement('div');
3  div.style.height = '1000px';
4  document.body.appendChild(div);
5
6  expect(getScrollHeight(div)).toBe(div.scrollHeight);
7
8  document.body.removeChild(div);
9});
10
11test('getScrollHeight returns scrollHeight for document', () => {
12  const height = getScrollHeight(document);
13  expect(typeof height).toBe('number');
14  expect(height).toBeGreaterThan(0);
15});

Common Use Cases

  • Infinite Scrolling

    Detect when the user nears the bottom of the page or container to load additional content.

  • Custom Scrollbars

    Calculate total scroll height to style or position custom scrollbar components accurately.

  • Scroll-Based Animations

    Use scroll height to determine trigger points for animations or transitions.

  • Dynamic Layout Adjustments

    Recalculate layout or container dimensions when content dynamically changes in height.

  • Visibility Tracking

    Combine with scroll position to determine how much of a page or element has been viewed.

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