Detect mobile keyboard showing up using JavaScript

Today I needed to make sure some form fields were always visible when the mobile keyboard was shown. I found a solution that works on all devices and browsers. In this article I'll show you how to detect when the mobile keyboard is shown using JavaScript.

I checked various sources to see what would be a solution for all devices and browsers. The solution I found is to listen to the resize and scroll events and check if the height of the window has changed.

I used the visualViewport object to get the height of the window. The visualViewport object is a read-only property of the window object that returns a reference to the visual viewport of the window. The visual viewport is the part of the window that is currently visible to the user.

 function viewportHandler() {
    const viewport = event.target;
    window.scrollTo(0, document.body.scrollHeight);
}

window.visualViewport.addEventListener('scroll', viewportHandler);
window.visualViewport.addEventListener('resize', viewportHandler);

This code will scroll to the bottom of the page when the keyboard is shown. You can adjust the code to your needs.