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?
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?
Share Improve this question edited Aug 2, 2019 at 12:56 Kareem Dabbeet 3,9943 gold badges18 silver badges35 bronze badges asked Aug 2, 2019 at 12:26 karolis2017karolis2017 2,41510 gold badges27 silver badges54 bronze badges 1- 3 Im not sure if there is event being triggered but you can probably use Intersection Observer naitve Api:developer.mozilla/en-US/docs/Web/API/… – curious lad Commented Aug 2, 2019 at 12:35
2 Answers
Reset to default 7As 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.
The CSS Scroll Snap Module Level 2 specification defines two events snapChanging
and snapChanged
. The first one is obviously triggered when scrolling away from a snap position and the latter when the scroll position got snapped. The latter obviously covers your use case.
Though, as of the time of posting this answer, the specification is an early draft and no browser supports those events. So, as long as they are not available, you'll have to use some polyfill.