Skip to content

Instantly share code, notes, and snippets.

@umkasanki
Created February 5, 2019 11:45
Show Gist options
  • Save umkasanki/74c73872314beb83810ad56a1b74bb4f to your computer and use it in GitHub Desktop.
Save umkasanki/74c73872314beb83810ad56a1b74bb4f to your computer and use it in GitHub Desktop.
Sticky panel with Intersection Observer and position fixed. Add class if parent is offscreen
const sticky = function (panelsClass, elementsClass) {
const panels = document.querySelectorAll('.' + panelsClass);
const config = {
rootMargin: '150px 20px 75px 30px',
threshold: [0, 0.25, 0.75, 1]
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
let element = entry.target.querySelector('.' + elementsClass);
let nextSibling = entry.target.nextSibling.nextElementSibling;
let elHeight = element.clientHeight;
console.log(nextSibling);
if (entry.intersectionRatio > 0) {
element.classList.remove('is-sticky');
nextSibling.style.marginTop = '0';
} else {
element.classList.add('is-sticky');
nextSibling.style.marginTop = elHeight + 'px'; // prevent jumping
}
});
});
panels.forEach(panel => {
observer.observe(panel);
}, config);
};
export default sticky
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment