Created
March 14, 2024 06:00
-
-
Save dainemawer/e233dc5b3ea82caa3a984cf34c6b339f to your computer and use it in GitHub Desktop.
Determine Sticky State in JavaScript - Daine Mawer
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 stickyElementStyle = null; | |
| let stickyElementTop = 0; | |
| function determineStickyState(element) { | |
| if (!stickyElementStyle) { | |
| stickyElementStyle = window.getComputedStyle(element); | |
| stickyElementTop = parseInt(stickyElementStyle.top, 10); | |
| } | |
| const currentTop = element.getBoundingClientRect().top; | |
| element.classList.toggle('is-sticky', currentTop <= stickyElementTop); | |
| } | |
| window.addEventListener('scroll', throttle(determineStickyState, 200)); |
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
| export function throttle(func, limit) { | |
| let inThrottle; | |
| return function() { | |
| const args = arguments; | |
| const context = this; | |
| if (!inThrottle) { | |
| func.apply(context, args); | |
| inThrottle = true; | |
| setTimeout(() => inThrottle = false, limit); | |
| } | |
| }; | |
| } |
I'm at a bit of loss on how to use this. Where do I specify my sticky styles I want to "observe". If I place on a page as-is it generates Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element' at the window.getComputedStyle(element) line because element is the window.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. Maybe you can get the value of
stickyElementTopprior to defining the function so that the function does not have to checkif (!stickyElementStyle)repeatedly.