I'm adding a back to top button fixed to bottom of the browser window. When clicked, it scrolls to top in desktop and Android, but not iPhone. On the iPhone, the scrollTo event reveals the address bar and the bottom mobile button bar, but does not return the user to the top of the page.
EDIT: The address bar and button bar on the iPhone appears when a touch event occurs within 20-30px of the bottom of the screen. This is why this back to top button doesn't work. Moving it 40px up stops the address/button bars from appearing.
I've attempted to just place it raw:
$('#scroll-to-top-button').on('click', function() {
window.scrollTo(0,0);
});
And with a timer:
$('#scroll-to-top-button').on('click', function() {
window.setTimeout(function() {
window.scrollTo(0,0);
}, 500);
});
I tried using scrollTop, which had the same results: browser button bar and address bar appear, but no scroll.
I also tried initiating the scrollTo and at the same time setting a timeOut with another scrollTo. The timeout never fires.
I did also try scrolling html or body, or a combination of the two:
$('#scroll-to-top-button').on('click', function() {
$('html,body').animate({
scrollTop: 0,
}, 200);
});
Only html
$('#scroll-to-top-button').on('click', function() {
$('body').animate({
scrollTop: 0,
}, 200);
});
only body
$('#scroll-to-top-button').on('click', function() {
$('html').animate({
scrollTop: 0,
}, 200);
});
I've tried resetting the button to an anchor tag and trying to get it to link within the page. This doesn't work with just basic html anchor functionality:
<div id="main-body"> ... lots of content forcing scrollbars to appear ... </div>
<a id="scroll-to-top-button" class="btn btn-default" href="#main-body">Back to Top</a>
And tried preventing default and animating the link to the anchor:
$('#scroll-to-top-button').on('click', function(e) {
e.preventDefault();
$('html,body').animate({
scrollTop: 0,
}, 200);
});
Here's a link demonstrating the problem. In this link, the code is using one of my last examples down this question, where it's purely an anchor tag trying to link to top of page.
http://willanni.com/dev/iphone-scroll/
I thought maybe missing the viewport tag might be causing it, so I added the following: <meta name="viewport" content="width=device-width, initial-scale=1">
. However. When I add that in, it still does not make it work.
Besides forcing the address bar and button bar to always be visible in iPhone, is there a way to get this to scroll to top of window in iPhone? (Note: iPad doesn't have this issue, though it had a different weird issue that required the timeout to fix. Different story though)