Search code examples
javascriptcssscroll-snap

How to get window.scrollTop, ScrollY or any other distance value when using css scroll snap


I am using css scroll snap to scroll through that are 100vh in height. The scroll snap works beautifully.

That said I need to determine how far the site visitor has scrolled for a few different reasons.

I have tried:

let wrapper = document.getElementById('landing-page-wrapper');
console.log(wrapper.offsetTop);
console.log(window.scrollY);

I have also tried window.scrollTop, wrapper.scrollTop and more.

Here is a Codepen of what I am seeing

How can I know the distance scrolled while using 100vh sections and css scroll-snap

TIA


Solution

  • Based on your shared code, the reason why window.onscroll does not work as expected is because neither window nor document.body are overflowing vertically. Only the element that is overflowing will fire the scroll event, and in this case it is actually the element that matches the .box-wrapper selector.

    Therefore if you listen to the scroll event on that element, then you should be able to retrieve its vertical scroll position using event.currentTarget.scrollTop:

    document.querySelector(".box-wrapper").addEventListener("scroll", (e) => {
      console.log(e.currentTarget.scrollTop);
    });
    

    See proof-of-concept example: