BB Design
BB Design

Reputation: 705

Detecting scroll on iPad with jQuery only works when scrolling stops

I am testing this website on an iPad: http://www.cherrystoneauctions.com/test

When you scroll the page down far enough that the navigation buttons with the blue marble background are above the top of your view area, I reposition those menus so they "stick" to the top of the screen:

$(window).on('scroll', function(){
    if ($('html').offset().top<-116){
        $('#fixnav').addClass('fixed');
    } else {
        $('#fixnav').removeClass('fixed');
    }
});

If you scroll back up, they "unstick" like normal.

This works pretty well on a computer screen, but with an iPad the "scroll" event is not triggered until the scrolling stops. So if you flick the screen with your finger, it will scroll, and once the scrolling stops, then it calculates the fixed/non-fixed navigation menu… which doesn't look good. I need it to basically calculate constantly, so it fixes/unfixes the menu immediately when the scroll goes past 116 pixels.

Is there a way I can have this trigger operate more smoothly on an iPad? Thanks!

Upvotes: 3

Views: 3751

Answers (2)

ken.dunnington
ken.dunnington

Reputation: 905

On Mobile Safari, scroll events are suspended while scrolling to help increase performance, so your scroll handler only gets fired once, after scrolling stops. You'll want to use a scrolling library such as iScroll to work around this limitation.

Upvotes: 1

Jasper
Jasper

Reputation: 75993

My fix for this was to use touch events rather than scroll events. The basic idea is:

  1. Detect when a finger hits the screen (touchstart) and save the x/y coordinates of this. I also save the time so I can attempt to detect what the user is doing.
  2. Detect when that finger moves and record where it moves to (touchmove). As the finger moves you can use this as your pseudo-scroll event handler. Where you take into account the current scrollTop() value as well as the amount of distance the user has moved their finger. Adding these together gives you your pseudo-scroll-position.
  3. Detect when that finger leaves the screen surface and do your cleanup, e.g. delete the data taken for this scroll so you can start fresh next time.

Hope that helps. There will be caveats along the way but you're more than welcome to come back and ask those questions on Stack Overflow.

Upvotes: 3

Related Questions