Skip to content

Instantly share code, notes, and snippets.

@dainemawer
Created March 14, 2024 06:00
Show Gist options
  • Save dainemawer/e233dc5b3ea82caa3a984cf34c6b339f to your computer and use it in GitHub Desktop.
Save dainemawer/e233dc5b3ea82caa3a984cf34c6b339f to your computer and use it in GitHub Desktop.
Determine Sticky State in JavaScript - Daine Mawer
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));
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