Created
February 5, 2019 11:45
-
-
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
This file contains hidden or 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
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