How to prevent mobile keyboard from covering html input

This answer is a hack; but it's the best solution I have come up with.

Adding a padding to the bottom of the page that is large enough for the keyboard enables content to be displayed as desired when the keyboard is visible.

Using some javascript listeners and a CSS class, this padding can be added only when the keyboard is displayed.

body.keyboard {
    height: calc(100% + 500px); /* add padding for keyboard */
}

The following javascript will add and remove the CSS class when an input has focus, which is the closest I can get to figuring out when the keyboard is displayed.

// focus events don't bubble, must use capture phase
document.body.addEventListener("focus", event => {
    const target = event.target;
    switch (target.tagName) {
        case "INPUT":
        case "TEXTAREA":
        case "SELECT":
            document.body.classList.add("keyboard");
    }
}, true); 
document.body.addEventListener("blur", () => {
    document.body.classList.remove("keyboard");
}, true); 

It's also worth noting that iOS performs an annoying zoom if the input font size is less that 16px so this is also important.

input {
    font-size: 16px !important;
}

Please let me know if you have a better solution.


What about this: stackoverflow: Scroll textfield up when keyboard popsup?

Even if you're not using jquery you could still bind the focus event and scroll the page using the window.scrollTo(0, document.body.scrollHeight); function and just scroll to the bottom. Because interestingly, the space is created, but not scrolled to.

If you want to go fancy, you can check for the window size in order to determine if and how much you want to scroll.