I need to know the current scroll position every ±100ms while the user is scrolling. That position determines which part of the page is "illuminated".
With $(window).on('scroll', function(){}); everything works just fine. I used _.debounce to debounce the event and check in every 100ms where the document is now.
However - on an iPad - 'scroll' isn't triggered until the scrolling has fully stopped, which is terrible in my scenario, so I'm trying to figure out a better solution.
At first, I wanted to use setInterval and check the position every 100ms that way, but I read that it's not as efficient on mobile devices, and it's going to run even if the tab isn't open. So I stumbled on requestAnimationFrame, and at the moment, it looks like I could do this:
saved_pos = -1;
rAF = window.requestAnimationFrame;
set_sticky_pos = function() {
if (saved_pos === window.scrollY) {
rAF(set_sticky_pos);
return false;
}
saved_pos = window.scrollY;
debounced_trigger_function(saved_pos);
rAF(set_sticky_pos);
};
My debounced_trigger_function would then check the current position, and according to it illuminate the content needed by adding a class on it's parent element.
By doing this - is there anything I should be aware of ? Is it a big no-no ?
Note: You may have noticed that I'm not doing any real "animation" which is what ( I think ) rAF was actually designed for, but it seems like the only way to counter the iPad on-scoll slowness. That's exactly why I decided to post the question on SO - is it okay to use rAF even if I'm not "animating" ?
Is it okay to use rAF as a workaround for live scroll position detection, and not for "animating" ?
Since iOS devices are using webkit browsers you can achieve smooth scrolling on them with one single line of CSS:
-webkit-overflow-scrolling: touch;
If that doesn't work for you than you can use rAF with a customized polyfill and/or fallback to scrolling if rAF is not available, but that is quite easy to verify:
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
// defualt scrolling logic or setInterval
window.setTimeout(callback, 1000 / 60);
};
})();
Also, if you don't want to mess with default scrolling on desktop browser you can use Modernizr to detect if the device running your code is touch enabled or not, and than (and only than) you can override the default scrolling behaviour. This would be as easy as
if(Modernizr.touch) {
// your custom scrolling logic here, rAF for 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