I'm aiming to toggle a class on an element based on scroll direction using Intersection Observer. Specifically, when scrolling down and the target element is just barely visible at the bottom of the viewport, I want to add a class; and when scrolling up, I want to remove it.
I currently have the following implementation, but the class isn't toggled reliably at the precise moment when the element is barely visible:
const options = {
root: null,
// rootMargin: '50px',
threshold: 0.1
}
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
// up
if (entry.boundingClientRect.top < 0) {
document.querySelector('button').classList.remove('hidden');
} else {
// down
document.querySelector('button').classList.add('hidden')
}
}
},
options
);
const arr = document.querySelectorAll('h2')
arr.forEach(i => {
observer.observe(i)
})
h2 {
margin-top: 700px;
margin-bottom: 700px;
}
button {
position: fixed;
top: 0;
left: 0;
}
button.hidden {
background: red !important;
}
<h2>
ELEMENT
</h2>
<button>
FIXED BUTTON
</button>
How can I adjust my Intersection Observer settings or logic so that the class is toggled exactly when the element becomes barely visible at the bottom of the screen?