Last active
January 15, 2024 11:05
-
-
Save jasubal/00b2f21c3d175ba56c25047a3b459703 to your computer and use it in GitHub Desktop.
JS Optimized Scroll detector and total of all Scrolled done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)}%`); | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.