Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect scroll event on Android browser

I'm trying to detect the scroll event in Android browser (my specific version is 2.1, but U want it to work also on older versions). This seems impossible!

I first tried this:

document.addEventListener('scroll', function(){ alert('test'); }, false);

But nothing is triggered (except when the page load).

I thought: well, let's be crazy and emulate it by : 1. Detecting touchend 2. Polling the window.pageYOffset so we know when the window stops scrolling 3. Manually trigger a user function I want on scroll.

Unfortunately, the touchend event doesn't look to be triggered either... in fact, when we don't scroll and only tap the screen (touchstart + touchend), it works. As soon as we scroll the page in between (touchstart + touchmove + touchend), it breaks everything.

Now my most basic example only contains this:

document.addEventListener('touchend', function(){ alert('test'); }, false);

But the alert doesn't show up when we scroll with the finger and release the touch...

Does anyone has a suggestion?

Thanks.

like image 537
Savageman Avatar asked Nov 06 '22 08:11

Savageman


1 Answers

You may want to crawl the source for JQuery Mobile, it supports android browsers and has scroll event listeners.

Or at least they say it does in the docs. :p

Here's the source

$.event.special.scrollstart = {
    enabled: true,

        setup: function() {
            var thisObject = this,
                $this = $( thisObject ),
                    scrolling,
                    timer;

            function trigger( event, state ) {
                scrolling = state;
                var originalType = event.type;
                event.type = scrolling ? "scrollstart" : "scrollstop";
                $.event.handle.call( thisObject, event );
                event.type = originalType;
            }

            // iPhone triggers scroll after a small delay; use touchmove instead
            $this.bind( scrollEvent, function( event ) {
                if ( !$.event.special.scrollstart.enabled ) {
                    return;
                }

                if ( !scrolling ) {
                    trigger( event, true );
                }

                clearTimeout( timer );
                timer = setTimeout(function() {
                    trigger( event, false );
                }, 50 );
            });
        }
};
like image 171
Squish Avatar answered Nov 09 '22 04:11

Squish