I have some JavaScript I'm using to add a class to my <body>
element when the user is scrolling:
var $body = $('body');
$(window).scroll(function() {
$body.addClass('scrolling');
var scroll = $(window).scrollTop();
if (scroll <= 1) {
$body.removeClass('scrolling');
}
});
This works well on desktop browsers, but on iOS (and possibly other mobile devices) the class is only added upon touch release rather than when the user first touches the screen to scroll.
How do I adjust this script to trigger this class upon touch, whilst still working as normal for standard desktop users?
Here's a Fiddle showing this script in action: http://jsfiddle.net/alecrust/AKCCH/
You can use ontouchstart, ontouchmove and ontouchend to handle touch events.
var $body = $('body');
if ("ontouchstart" in document.documentElement)
{
$(window).bind('touchmove',function(e){
e.preventDefault();
$body.addClass('scrollingTouch');
});
$(window).bind('touchend',function(e){
e.preventDefault();
var scroll = $(window).scrollTop();
if (scroll <= 1) {
$body.removeClass('scrollingTouch');
}
});
}
else
{
$(window).scroll(function() {
$body.addClass('scrolling');
var scroll = $(window).scrollTop();
if (scroll <= 1) {
$body.removeClass('scrolling');
}
});
}
Here is a working jsfiddle: http://jsfiddle.net/BLrtr/
There might be some complications so I suggest you read this to understand them. Also, you might want to check these 3rd party libraries for touch events handling.
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