Skip to content

Instantly share code, notes, and snippets.

@jasubal
Last active January 15, 2024 11:05
Show Gist options
  • Select an option

  • Save jasubal/00b2f21c3d175ba56c25047a3b459703 to your computer and use it in GitHub Desktop.

Select an option

Save jasubal/00b2f21c3d175ba56c25047a3b459703 to your computer and use it in GitHub Desktop.
JS Optimized Scroll detector and total of all Scrolled done
let lastScrollTop = 0;
const $html = document.documentElement;
$html.classList.add('near-top');
window.addEventListener('scroll', () => {
const currentScrollTop = window.scrollY || document.documentElement.scrollTop;
const windowHeight = window.innerHeight;
const docHeight = Math.max($html.scrollHeight, $html.offsetHeight, $html.clientHeight);
const scrolledPercentage = ((currentScrollTop + windowHeight) / docHeight) * 100;
const remainingScroll = 100 - scrolledPercentage;
// Determine scroll direction and update classes using ternary expressions
currentScrollTop > lastScrollTop ?
($html.classList.add('scrolling-down'), $html.classList.remove('scrolling-up')) :
($html.classList.add('scrolling-up'), $html.classList.remove('scrolling-down'));
// Add or remove class based on scroll position using a ternary expression
currentScrollTop <= 100 ?
$html.classList.add('near-top') :
$html.classList.remove('near-top');
lastScrollTop = currentScrollTop <= 0 ? 0 : currentScrollTop;
// Log or use the remainingScroll percentage as needed
console.log(`Remaining scroll: ${remainingScroll.toFixed(2)}%`);
});
@jasubal
Copy link
Author

jasubal commented Jan 15, 2024

In this refactored code:
1.
windowHeight is the inner height of the window (viewport).
2.
docHeight is the total height of the document. It's calculated using the maximum of scrollHeight, offsetHeight, and clientHeight of the document element to ensure compatibility and accuracy across different browsers and content types.
3.
scrolledPercentage calculates how much of the page (in percentage) has been scrolled including the current viewport.
remainingScroll is the percentage of the page that remains to be scrolled.
4.
The remainingScroll value is updated on every scroll event and represents the percentage of the page height that is still below the current viewport. You can use this value as needed, for instance, to display a progress bar, log information, or trigger certain actions when a specific threshold is reached.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment