Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent scrolling on keyboard display iOS 6

I am running into a strange issue. I am currently producing a mobile web app using HTML5 and CSS3 for iOS 6 only.

However, when an input element receives focus and the soft keyboard is displayed, the window is scrolled so that the input is not obscured by the keyboard (even though it won't be in any instance).

I have read on SO and via Google that one can add the following to prevent this behaviour (when viewing this inside a UIWebView):

input.onfocus = function () {
    window.scrollTo(0, 0);
    document.body.scrollTop = 0;
}

However, it seems that in iOS 6, even though the window is initially scrolled to 0,0, it is then once again scrolled to centre the focused element. Has anyone else come across this and do they know of a fix for iOS 6?

like image 909
BenM Avatar asked Nov 23 '12 12:11

BenM


People also ask

How do I turn off scrolling In IOS?

The most straightforward way for disabling scrolling on websites is to add overflow: hidden on the <body> tag. Depending on the situation, this might do the job well enough.

How do I stop my body scrolling?

Approach: A simple solution to this problem is to set the value of the “overflow” property of the body element to “hidden” whenever the modal is opened, which disables the scroll on the selected element.

How do I get my iPhone keyboard to scroll down?

By tapping and holding the spacebar on an iPhone's keyboard, users can turn it into a touchpad that can be used to scroll through texts, like an actual touchpad found on laptops.


2 Answers

I hit this issue too. The following works on iOS 6:

<input onfocus="this.style.webkitTransform = 'translate3d(0px,-10000px,0)'; webkitRequestAnimationFrame(function() { this.style.webkitTransform = ''; }.bind(this))"/>

Basically, since Safari decides whether or not to scroll the page based on the textbox's vertical position, you can trick it by momentarily moving the element above the top of the screen then back again after the focus event has completed.

The drawback is that the element vanishes for a fraction of a second. If you want to work around that, you could dynamically insert a clone of the original element at the original location and then remove it in the webkitRequestAnimationFrame callback.

like image 176
Steve Sanderson Avatar answered Oct 13 '22 17:10

Steve Sanderson


Could it be a timing issue?

Try wrapping it up in a timeout to ensure that it's firing after the native events are firing.

input.onfocus = function () {
    setTimeout(function() {
        window.scrollTo(0, 0);
        document.body.scrollTop = 0;
    }, 50)
}
like image 21
Will Tomlins Avatar answered Oct 13 '22 19:10

Will Tomlins