Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll Webpage input Field to Top prevent hide by Soft Keyboard

I have a webpage used on Mobile devices when clicking in input fields the Android Soft keyboard is hiding the input fields when I click in the input field I want the field to scroll up to become visible above the keyboard.

I've search various articles many refer to an Android manifest file but this is a webpage not an app. I've also tried various javascript options including the one below but many browsers don't seem to like the .focus event. It works on chrome but not on many other.

jQuery(function ($) {
        $("#Litres").focus(function () {
            document.body.scrollTop = $(this).offset().top;
        });
    });

Does anyone have a simple solution to achieve the desired effect for a webpage.?

like image 221
user552769 Avatar asked Jan 08 '16 13:01

user552769


1 Answers

while this solution doesn't automatically scroll your field into view, I have found it solves the problem of the page not being scrollable when the soft keyboard is active.

The answer thread is here: https://stackoverflow.com/a/25725611/5580153

I found adding the following CSS in my max-width: 768px media query made the native mobile browser respond to scrolling while the keyboard was active:

html { 
   overflow: auto; 
} 
body { 
   height:auto; 
   overflow: auto; 
} 
.scrollable { 
   position:inherit; 
}

I hope this helps you, or someone else like me that was struggling to find a solution.

Cheers!

Edit: This can also be achieved with a bit of jQuery if you're running something like a flexbox layout that breaks if you force the heights to auto. The following script will look for a user-agent that includes Mobi (*so this will target both iOS and Android devices, you can be more specific with targeting the user-agent if you wish) and adds the styles that are required.

if (/Mobi/i.test(navigator.userAgent)) {
    $('html').css({"overflow":"auto"});
    $('body').css({"height":"auto"});
    $('body').css({"overflow":"auto"});
    $('.scrollable').css({"position":"inherit"});
}

There's probably more elegant ways to achieve it, I'm sure someone can fill me in.

like image 196
Aaron Lavers Avatar answered Oct 18 '22 04:10

Aaron Lavers