48

The age old problem: Getting the scroll event to fire while a user is scrolling on an element while on a mobile site or app(web view).

All I'm looking for is access to the correct scrollTop() value while a user is scrolling my page on a mobile device instead of getting it when the user stops.

I'm sure there is a workaround somewhere, if I'm correct this limitation is set by iOS and there has been discussion over it for the past few years.

I've tried implementing native scroll emulators but none of them seem to be working how I want and to be honest it seems like overkill if all I really want is a persistent scrollTop() while a user is scrolling.

I'm currently thinking about maybe starting a counter on touchStart and stopping it on touchStop but something tells me I'm wasting my time.

Any help guys?

Franky Chanyau
  • 1,010
  • 1
  • 15
  • 24

3 Answers3

98

With jQuery:

$('body').bind('touchmove', function(e) { 
    console.log($(this).scrollTop()); // Replace this with your code.
});

This should give you a consistent stream of the scrollTop value when the user scrolls, but be careful as it's going to fire even while the user is just holding his finger on the screen.

Note that if you're using jQuery >= 1.7 the preferred binding method is .on() instead of the .bind() method I've used in my example. In that case my example would be

$('body').on({
    'touchmove': function(e) { 
        console.log($(this).scrollTop()); // Replace this with your code.
    }
});

Source: https://github.com/dantipa/pull-to-refresh-js/blob/master/jquery.plugin.pullToRefresh.js

Thanos Siopoudis
  • 1,121
  • 7
  • 11
  • This looks promising, I'll test it out on my app then accept the answer if it works. It should, in fact technically you have answered the question and the demo works. Ok, Ill accept it now. – Franky Chanyau Sep 18 '13 at 01:14
  • 3
    Not sure what I'm doing wrong but this solution works even less good for me then the scroll event... – amosmos Mar 11 '14 at 10:59
  • this seems to work when using chrome device toolbar (and scrolling by clicking the mouse and dragging) but not actually working on mobile devices. – Ari Seyhun Aug 03 '17 at 17:03
4

maybe you could take a look at how iScroll does it in their _move-method which is bound to the touchmove event: https://github.com/cubiq/iscroll/blob/master/src/core.js#L152

It's a bit complicated but i'm sure you'll figure it out. You could also just use iScroll to begin with and bind to their scrollmove event (I'm not sure how it's called on iScroll 5 but it was onScrollMove in iScroll 4). that.y will then give you the correct value.

urz0r
  • 462
  • 3
  • 8
1

I had to go the iScroll route to do this. I wrote up my implementation here: https://stackoverflow.com/a/23140322/229315

Community
  • 1
  • 1
Melinda Weathers
  • 2,649
  • 25
  • 31