How to detect whether the scroll direction is up or down using Javascript

peterking1697923543 peterking1697923543
Blog
How to detect whether the scroll direction is up or down using Javascript

Code to compare the last scroll position before and after the user scrolls, allowing us to detect whether the scroll direction is up or down.


Here’s the revised JavaScript code:

// Initialize the constant iMove with null
let iMove = null;

// Set the threshold for scrolling (100 pixels)
const threshold = 100;

// Initialize the last scroll position
let lastScrollY = window.scrollY;

// Function to handle scroll events
function handleScroll(evt) {
  const currentScrollY = evt.target.scrollTop;;

  // Calculate the difference between current and last scroll position
  const scrollDifference = currentScrollY - lastScrollY;

  if (scrollDifference > threshold) {
    // User scrolled down
    iMove = 'down';
  } else if (scrollDifference < -threshold) {
    // User scrolled up
    iMove = 'up';
  } else {
    // Reset iMove to null
    iMove = null;
  }

  // Update last scroll position
  lastScrollY = currentScrollY;
}

// Attach the scroll event listener to your target div (replace 'your-div-id' with the actual ID)
document.getElementById('your-div-id').addEventListener('scroll', handleScroll);


In the above code, we keep track of the last scroll position (lastScrollY) and calculate the difference between the current scroll position and the last one. If the difference exceeds the threshold, we determine whether the user scrolled up or down. Otherwise, iMove remains null. Remember to replace 'your-div-id' with the actual ID of the div you want to track. Feel free to customize this code further as needed! 😊

Comments (0)

U
Press Ctrl+Enter to post

No comments yet

Be the first to share your thoughts!