Preventing an <input> element from scrolling the screen on iPhone?

46,814

Solution 1

I just found the solution to this problem in this post Stop page scrolling from focus

Just add onFocus="window.scrollTo(0, 0);" to your input field and you're done! (Tried it with <textarea> and <input type="text" /> on the iPad, but I'm pretty sure it'll work on the iPhone too.)

I was afraid the scrolling would be visible as a flicker or something, but fortunately that is not the case!

Solution 2

here is how I solved this on the iPhone (mobile Safari) (I used jQuery)

1) create a global variable that holds the current scroll position, and which is updated every time the user scrolls the viewport

var currentScrollPosition = 0;
$(document).scroll(function(){
    currentScrollPosition = $(this).scrollTop();
});

2) bind the focus event to the input field in question. when focused, have the document scroll to the current position

$(".input_selector").focus(function(){
    $(document).scrollTop(currentScrollPosition);
});

Ta Da! No annoying "scroll on focus"

One thing to keep in mind...make sure that the input field is ABOVE the keypad, else you will hide the field. That can be easily mitigated by adding an if-clause.

Solution 3

I would recommend using the jQuery.animate() method linked to above, not just the window.scrollTo(0,0), since iOS animates the page offset properties when an input element is focused. Calling window.scrollTo() just once may not work with the timing of this native animation.

For more background, iOS is animating the pageXOffset and pageYOffset properties of window. You can make a conditional check on these properties to respond if the window has shifted:

if(window.pageXOffset != 0 || window.pageYOffset != 0) {
  // handle window offset here
}

So, to expand on the aforementioned link, this would be a more complete example:

$('input,select').bind('focus',function(e) { 
  $('html, body').animate({scrollTop:0,scrollLeft:0}, 'slow'); 
});
Share:
46,814
Stefan Kendall
Author by

Stefan Kendall

Updated on January 31, 2020

Comments

  • Stefan Kendall
    Stefan Kendall over 4 years

    I have several <input type="number"> elements on my webpage. I'm using jQTouch, and I'm trying to stay fullscreen at all times; that is, horizontal scrolling is bad. Whenever I click an <input> element, the page scrolls right, showing a black border on the right of the screen and de-centering everything. The inputs are offset from the left of the screen, and they begin somewhere toward the middle of the page.

    How can I prevent this scrolling on focus?