Skip to content

Instantly share code, notes, and snippets.

@dainemawer
Created March 14, 2024 06:00
Show Gist options
  • Select an option

  • Save dainemawer/e233dc5b3ea82caa3a984cf34c6b339f to your computer and use it in GitHub Desktop.

Select an option

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);
}
};
}
@ianthedev
Copy link

Nice. Maybe you can get the value of stickyElementTop prior to defining the function so that the function does not have to check if (!stickyElementStyle) repeatedly.

@duncansmart
Copy link

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