Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mobile Safari: why is window.scrollTo(0, 0) not scrolling to (0, 0)?

I've built a small single-page web app using Bootstrap 3, Sammy.js and Knockout 3. I'm finding that when the page is scrolled down, I'm unable to get window.scrollTo(0, 0) to work on Mobile Safari when I also change location.hash - specifically on iOS 7 on an iPhone 5C (likely happens on other iPhone models though).

When I try something like this:

self.changeState = function() {
    self.state(State.NewState);
    location.hash = 'somevalue';
    window.scrollTo(0, 0);
};

The page will scroll almost all the way to the top - it will usually be scrolled to Y = 12 or 13. It will never scroll to 0 if I call window.scrollTo(0, 0); when the user is scrolled to the bottom of the page (and the content is sufficiently high to warrant a scroll to top).

I've tried various StackOverflow answers/suggestions (e.g. The same old issue, .scrollTop(0) not working in Chrome & Safari); the usual remedies (wrap in a setTimeout) do not change the behavior - it still scrolls to somewhere near the top of the page, but not quite to the top.

Header style:

<div class="navbar navbar-default navbar-inverse navbar-static-top">

Viewport settings:

<meta name="viewport" 
      content="width=device-width, 
               height=device-height, 
               initial-scale=1.0, 
               maximum-scale=1.0, 
               target-densityDpi=device-dpi" />

Scroll attempts:

self.changeState = function() {
    self.state(State.NewState);
    location.hash = 'somevalue';
    window.scrollTo(0, 0);
};

and:

self.changeState = function() {
    self.state(State.NewState);
    location.hash = 'somevalue';
    window.setTimeout(function() {
        window.scrollTo(0, 0);
    }, 0);
};

I've dug into this with the Safari Web Inspector, and nothing seems out of place as far as the structure of the page. I'm just not sure what to look for here - any ideas?

Edit:

So far, I have not been able to reproduce this outside of my app's code. I'm trying to get this to break in a JSFiddle - in this one, it works correctly (e.g., it scrolls to 0,0 as it should): http://jsfiddle.net/rringham/n9evU/24/show.

like image 498
Rob Avatar asked Jul 07 '14 17:07

Rob


2 Answers

I managed to recreate this issue by using height: 100vh or min-height: 100vh on elements. I changed my CSS to use 100% instead (which is a bit of a pain) and the problem disappeared.

like image 67
sean_j_roberts Avatar answered Sep 28 '22 22:09

sean_j_roberts


Try setting scrollTo(-n, 0); "n" being any number lower than 0

like image 21
Pablo Navarro Avatar answered Sep 28 '22 20:09

Pablo Navarro