How to check scroll depth using JavaScript

Tracking how far users scroll down a webpage can provide valuable insights into content engagement. By monitoring scroll depth milestones—such as 25%, 50%, 75%, and 100% — you can trigger specific actions or events when users reach these points.

Scroll Depth Tracking with Vanilla JavaScript

The following script listens for scroll events and calculates the user’s scroll depth as a percentage of the total page height. When the user reaches each milestone for the first time, a corresponding action is triggered.

// Flags to ensure each milestone is only triggered once
let hasReached25 = false;
let hasReached50 = false;
let hasReached75 = false;
let hasReached100 = false;

function handleScroll() {
  const scrollTop = window.scrollY;
  const viewportHeight = window.innerHeight;
  const totalHeight = document.documentElement.scrollHeight;

  const scrollPercent = ((scrollTop + viewportHeight) / totalHeight) * 100;

  if (scrollPercent >= 25 && !hasReached25) {
    hasReached25 = true;
    // Action for 25% scroll depth
    console.log('User reached 25% scroll depth');
  }

  if (scrollPercent >= 50 && !hasReached50) {
    hasReached50 = true;
    // Action for 50% scroll depth
    console.log('User reached 50% scroll depth');
  }

  if (scrollPercent >= 75 && !hasReached75) {
    hasReached75 = true;
    // Action for 75% scroll depth
    console.log('User reached 75% scroll depth');
  }

  if (scrollPercent >= 100 && !hasReached100) {
    hasReached100 = true;
    // Action for 100% scroll depth
    console.log('User reached 100% scroll depth');
  }
}

// Attach the scroll event listener
window.addEventListener('scroll', handleScroll);

Flags (hasReached25, etc.): These boolean variables ensure that each scroll depth milestone triggers its action only once per page load.

handleScroll Function: Calculates the current scroll position as a percentage of the total page height and checks against each milestone.

Event Listener: The handleScroll function is attached to the window’s scroll event, so it’s called every time the user scrolls.

This implementation uses window.scrollY and window.innerHeight to determine the current scroll position and viewport size, respectively. document.documentElement.scrollHeight provides the total height of the document, ensuring compatibility across different browsers.

on in JavaScript DOM | Last modified on

Related Posts