Skip to content

Instantly share code, notes, and snippets.

@c-kick
Last active October 4, 2024 12:21
Show Gist options
  • Save c-kick/da08c01011cc9b7bf771883c2ec3c1a7 to your computer and use it in GitHub Desktop.
Save c-kick/da08c01011cc9b7bf771883c2ec3c1a7 to your computer and use it in GitHub Desktop.
adds class 'stuck' to elements that are stuck. Uses Bootstraps' `position-sticky` class as a selector.
const stickies = document.body.querySelectorAll('.position-sticky');
window.addEventListener('scroll', function(){
stickies.forEach(function(el){
let stuck = false;
const rect = el.getBoundingClientRect();
if (window.getComputedStyle(el).bottom == 'auto') {
stuck = rect.top === parseInt(window.getComputedStyle(el).top, 10);
} else if (window.getComputedStyle(el).top == 'auto') {
stuck = rect.height + rect.top < window.innerHeight;
}
el.classList.toggle('stuck',stuck);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment