Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to body on touch start rather than .scroll()

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/

like image 206
AlecRust Avatar asked Nov 12 '22 19:11

AlecRust


1 Answers

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.

like image 107
SM79 Avatar answered Nov 15 '22 09:11

SM79