Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "snap scroll" and trigger the event when snapped?

Tags:

javascript

css

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?

like image 437
karolis2017 Avatar asked Oct 28 '25 14:10

karolis2017


1 Answers

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.

like image 136
CodeF0x Avatar answered Oct 31 '25 05:10

CodeF0x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!