I had a similar problem to @ds111 s. My website was pushed up by the keyboard but didn't move down when the keyboard closed.
First I tried @ds111 solution but I had two input
fields. Of course, first the keyboard goes away, then the blur happens (or something like that). So the second input
was under the keyboard, when the focus switched directly from one input to the other.
Furthermore, the "jump up" wasn't good enough for me as the whole page only has the size of the ipad. So I made the scroll smooth.
Finally, I had to attach the event listener to all inputs, even those, that were currently hidden, hence the live
.
All together I can explain the following javascript snippet as:
Attach the following blur event listener to the current and all future input
and textarea
(=live
): Wait a grace period (= window.setTimeout(..., 10)
) and smoothly scroll to top (= animate({scrollTop: 0}, ...)
) but only if "no keyboard is shown" (= if($('input:focus, textarea:focus').length == 0)
).
$('input, textarea').live('blur', function(event) {
window.setTimeout(function() {
if($('input:focus, textarea:focus').length == 0) {
$("html, body").animate({ scrollTop: 0 }, 400);
}
}, 10)
})
Be aware, that the grace period (= 10
) may be too short or the keyboard may still be shown although no input
or textarea
is focused. Of course, if you want the scrolling faster or slower, you may adjust the duration (= 400
)