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?
To find out which elements cause a horizontal scrollbar, you can use the devtools to delete elements one by one until the scrollbar disappears. When that happens, press ctrl/cmd Z to undo the delete, and drill down into the element to figure out which of the child elements cause the horizontal scrollbar.
Use the scrollTop and scrollLeft properties. If these are greater than 0, scrollbars are present. If these are 0, then first set them to 1, and test again to know if getting a result of 1.
Cmd+0 helped bring the zoom to 100% which got rid of the scrolling.
1) Set the scrolling attribute of the iframe to no (scrolling="no"). This will disable both horizontal and vertical scroll bars. 2) Set the width attribute of the iframe to 200% (width="200%"). This will enable only the horizontal scroll bar.
I think your code is right, because at the end of the day you need to read one of those properties to find out the scroll direction, but the key thing here to avoid performance problems is to throttle the event, because otherwise the scroll
event fires too often and that is the root cause for performance problems.
So your example code adapted to throttle the scroll
event would be like this:
var ticking = false; var lastScrollLeft = 0; $(window).scroll(function() { if (!ticking) { window.requestAnimationFrame(function() { var documentScrollLeft = $(document).scrollLeft(); if (lastScrollLeft != documentScrollLeft) { console.log('scroll x'); lastScrollLeft = documentScrollLeft; } ticking = false; }); ticking = true; } });
Source: https://developer.mozilla.org/en-US/docs/Web/Events/scroll#Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With