2 min read

VirtualKeyboard API

The VirtualKeyboard API provides control over the on-screen virtual keyboard (OSK) on devices like tablets and mobile phones. It allows developers to prevent the browser from automatically resizing the visual viewport when the keyboard appears, and instead handle the layout adjustments manually.

1. The Problem: Viewport Resizing

Traditionally, when a virtual keyboard appears on a mobile device, the browser resizes the visual viewport to fit the remaining space. This pushes content up, which is usually good, but can be jarring for complex layouts or fixed-position elements (like bottom navigation bars).

2. The Solution: overlaysContent

The core feature of this API is the overlaysContent property. When set to true, the browser stops resizing the viewport. The keyboard simply overlays the content.

if ('virtualKeyboard' in navigator) {
  navigator.virtualKeyboard.overlaysContent = true;
}

3. Handling Layout Changes

Since the viewport doesn't resize, your content might be hidden behind the keyboard. You need to adjust your layout manually.

CSS Environment Variables

The API provides CSS environment variables to calculate the keyboard's dimensions.

  • env(keyboard-inset-top)
  • env(keyboard-inset-right)
  • env(keyboard-inset-bottom): The height of the keyboard.
  • env(keyboard-inset-left)
  • env(keyboard-inset-width)
  • env(keyboard-inset-height)
.bottom-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  /* Add margin equal to keyboard height */
  margin-bottom: env(keyboard-inset-height, 0px);
  transition: margin-bottom 0.3s;
}

The geometrychange Event

You can also listen for changes in JavaScript.

if ('virtualKeyboard' in navigator) {
  navigator.virtualKeyboard.addEventListener('geometrychange', (event) => {
    const { x, y, width, height } = event.target.boundingRect;
    console.log('Keyboard height:', height);

    // Adjust layout logic if needed
  });
}

4. Showing and Hiding

You can programmatically show or hide the keyboard. This is useful for custom editable elements (like contenteditable) where the keyboard might not trigger automatically, or to dismiss it after an action.

const input = document.getElementById('my-input');

input.addEventListener('click', () => {
  if ('virtualKeyboard' in navigator) {
    navigator.virtualKeyboard.show();
  }
});

document.getElementById('close-btn').addEventListener('click', () => {
  if ('virtualKeyboard' in navigator) {
    navigator.virtualKeyboard.hide();
  }
});

5. Requirements

  • Secure Context: Requires HTTPS.
  • Browser Support: Primarily Chromium-based browsers on mobile/tablet devices (Chrome Android, Edge).

programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/dom-manipulation