I would like to detect a user's scroll and make an element fixed to top by adding a class when it's reached by scolling and below. The class should be removed when the user is scrolling above the element. I can't use the css property position: sticky.
I'm currently using IntersectionObserver but it's adding the fixed class even when the element is not in view because of !entry.isIntersecting
.
Is there a way to get around that? Is there another or better way to add a fixed class only when scrolled below an element?
const watcher = document.querySelector('.watcher');
const evu = document.getElementById('box');
const createObserver = () => {
const options = {
root: null,
trackVisibility: true,
delay: 100,
threshold: [.9]
}
const handler = (entries) => {
entries.forEach((entry) => {
entry.target.nextElementSibling.classList.toggle('fixed', !entry.isIntersecting);
})
}
if ('IntersectionObserver' in window) {
const observer = new window.IntersectionObserver(handler, options);
observer.observe(watcher);
}
};