Jason Vertucio

You know me! ™

Mobile Web Apps, making the keyboard disappear

So, just for fun, I decided to make a little mobile web app to change from Fahrenheit to Celsius (of vice versa in case you needed that instead). But there were two problems with it.

(a) if I hit BACKSPACE, it wouldn’t update the converted temperature
(b) couldn’t get the keyboard to disappear
(c) oops, also had a problem with disappearing zeroes at the end of the number.

Well, (c) was easy. My RegEx was wrong. (a) was also pretty easy, once I found out about the new html5 input event (keypress was not reading BACKSPACES on my iPhone). But (b). Oh, that nasty (b)!

Stack Overflow had this same question, and a user linked to this blog and the long and short of it is

  1. var hideKeyboard = function(ev) {
  2.   // Don't actually hide the keyboard if we are on the INPUT
  3.   if ( ev.target.tagName === 'INPUT' ) return;
  5.   document.activeElement.blur();
  6. }

Now this would be fine and dandy except where do you call the function?! I quickly determined that in my app, which is just a single-page thing, I could safely put the listener on the window itself.

  1. window.addEventListener('touchstart',hideKeyboard);

This code will only remove the keyboard when the active element is an INPUT. For some reason it doesn’t work on textareas. But the solution is to blur all inputs at the same time. I’m not doing it because my amp is simple enough to skip that step.

This bit of code was an immense help to me, and I hope it ends up being an immense help to you, as well!