I am currently trying to do scroll snapping with vanilla javascript. I want to snap the scroll at specific pixels, I am aware of the various libraries and CSS scroll snap, but they all depend on all the elements being the children of specific tags. For me, the points are scattered throughout the code.
if (window.scrollY < window.innerHeight / 3)
window.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
else if (window.scrollY < reference.placeholderTop)
window.scrollTo({ top: reference.placeholderTop, left: 0, behavior: 'smooth' });
I can get the pixel value, the issue with this kind of implementation is that when scrollTo
is triggered it fires the scroll event, which causes the scrollTo to be triggered after a certain time. I have tried with debounce from lodash
, but it won't help. How can I do it without the scroll freezing in between? Or is there any library which does scroll snapping to certain pixels?