Open In App

How to detect virtual keyboard using JavaScript ?

In this article, we are given an HTML document, the task is to detect a virtual keyboard if it pops up on the device’s screen. A virtual keyboard is a tool that helps in the input of characters without the use of the physical keyboard. It is widely used in touchscreen devices.

Approach: Unfortunately, currently there is no direct way to detect if a virtual keyboard appears on the screen using JavaScript. However, there are a few indirect ways using which we can detect when a virtual keyboard appears on the device’s screen. 



Example: This example shows the above-explained approach.




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0" />
    <title>Document</title>
  
    <style>
      /*media query to detect orientation change*/
      @media screen and (orientation: landscape) {
        h1 {
          color: green;
        }
      }
    </style>
  </head>
  <body>
    <h1 id="text">Change orientation/screen height</h1>
  </body>
</html>




<script>
    const text = document.querySelector("#text");
  
// resize event listener to detect change in screen height
    window.addEventListener("resize", (e) => {
        text.innerHTML = "Virtual keyboard detected!!!";
      });
</script>

Output: Click here to check the Output live



Detection when the screen height changes

Detection when the screen orientation changes


Article Tags :