You can detect a browser scroll event on an arbitrary element with:
element.addEventListener('scroll', function (event) {
// do something
});
I would like to be able to differentiate between vertical scrolling and horizontal scrolling and execute actions for them independently.
I'm currently doing this by stashing the values of element.scrollTop, and element.scrollLeft, and then comparing them inside the event listener. E.g.
var scrollLeft, scrollTop;
element.addEventListener('scroll', function (event) {
if (scrollLeft !== element.scrollLeft) {
// horizontally scrolled
scrollLeft = element.scrollLeft;
}
if (scrollTop !== element.scrollTop) {
// vertically scrolled
scrollTop = element.scrollTop;
}
});
This works fine, however from https://gist.github.com/paulirish/5d52fb081b3570c81e3a I read that reading the scrollLeft or scrollTop values causes a reflow.
Is there a better way to do this without causing a browser reflow on scroll?
scrollLeft
andscrollTop
values, and see if they changed when you handle a scroll event, updating them at the end of the handling so they're ready for the next event handling? – Bright