I tried using scroll-snap CSS property which works well in terms of the representation.
but I need to trigger an event when scrolled/snapped. how can I do that?
As Mladen suggested, using the Intersection Observer Api seems to (kinda) work.
(Seems buggy on latest Firefox -- when scrolling up, observer goes crazy and logs only first section -- works fine on latest Chrome)
const observer = new IntersectionObserver(entries => {
entries.forEach(elem => {
if (elem.isIntersecting) {
const text = elem.target.querySelector('h2').innerText;
console.log('Ping! Visible: ', text);
}
});
});
document.querySelectorAll('section').forEach(elem => observer.observe(elem));
.scroller {
height: 300px;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.scroller section {
height: 300px;
background: gray;
border: 1px solid black;
scroll-snap-align: start;
}
<article class="scroller">
<section>
<h2>Section one</h2>
</section>
<section>
<h2>Section two</h2>
</section>
<section>
<h2>Section three</h2>
</section>
</article>
I don't know if there's another way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With