Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find (in javascript) the current "scroll" offset in mobile safari / iphone

I'd like to know the x/y offset of the how far the user has "scrolled" within the viewport in mobile safari on the iphone.

Put another way, if I (through javascript) reloaded the current page, I'd like to find the values I'd need to pass into window.scrollTo(...) in order to reposition the document/viewport as it is currently.

window.pageXOffset always reports 0

jquery's $('body').scrollTop() always reports 0

events have a pageX, but this won't account for the scrolling of the page that happens after you release your finger if your gesture was to "flick" the page up/down. Namely, it'll give me a point when the finger leaves the screen, but that doesn't always match where the page will be after it's finished scrolling.

Any pointers?

like image 545
mintywalker Avatar asked Mar 24 '10 10:03

mintywalker


3 Answers

window.pageYOffset should give you the current scroll offset. There's window.pageXOffset if you need it too.

like image 100
pendor Avatar answered Nov 15 '22 07:11

pendor


I had the same problem... this did the trick:

var scrollX = window.pageXOffset; var scrollY = window.pageYOffset;

Got it from this question: Get current position of the viewport in Mobile (iPhone) Safari

like image 3
Andrea Avatar answered Nov 15 '22 08:11

Andrea


This will indeed work:

var scrollX = window.pageXOffset; 
var scrollY = window.pageYOffset;

If you are viewing content in an iFrame (which is common in WebViews for instance), then you will need to add parent:

var scrollX = parent.window.pageXOffset;

Also note that these values are not writeable. So to change the scroll position, you will need to use window.scrollTo method:

var scrollX = window.pageXOffset; 
var scrollY = window.pageYOffset;
window.scrollTo(scrollX -100, scrollY -100);
like image 3
BishopZ Avatar answered Nov 15 '22 07:11

BishopZ