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 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 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); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment