How to get keyboard height on a web app

Miguel Guardo picture Miguel Guardo · Jan 16, 2017 · Viewed 8.4k times · Source

This is for a web app, targeting any mobile browser but mainly Chrome and Safari for iOS10. The browser opens the built-in keyboard when the user clicks on any input, which is fine, but I am trying to resize/relocate the items more relevant to the user at that point in time.

Is there anyway to calculate the height of the keyboard so that I can adjust items accordingly? Generic solution would be better, as inputs may open different types of keyboard (text, numeric...) but hard coding options are also a valid response at this stage.

I have tested around window.screen, window.innerHeight and so on to no avail...

Thanks!

Answer

user9272019 picture user9272019 · Apr 21, 2018

Note: The credit of this answer fully goes to the user Alex k. However his solution has already been accepted by OP within comments section and I guess these should have to be in answer section as this is a very useful question.

To solve the problem, try CSS media queries like this:

var d = document.getElementById('d');

checkDimensions();

window.onresize = checkDimensions;

function checkDimensions(prevHeight) {
  d.innerHTML = 'Window dimensions: ' + window.innerWidth + ' x ' + window.innerHeight;
}
.media-query-test {
  display: none;
  color: red;
}

@media all and (max-height: 700px) {
  .media-query-test {
    display: block;
  }
}
<input type="number" />

<div id="d">
</div>

<div class="media-query-test">
  Height is less than 700px!
</div>

And here's the JSFiddle: https://jsfiddle.net/t3yn2yz1/6/