October 10, 2011

Javascript: Hide the iOS soft keyboard

I was having some trouble getting my text input field to relieve itself of focus on the iPhone, and after a little searching, I came up with a couple options. It's pretty self-explanatory. The 2nd line will de-focus all input fields, and it relies on jQuery. I found that calling blur() on the single focused textfield didn't always work. Either one of these lines should work independently, but both of them together cannot be stopped!
var hideKeyboard = function() {
 document.activeElement.blur();
 $("input").blur();
};
UPDATE: As a modern replacement for the jquery statement above, here's a simple, modern alternative:
var hideKeyboard = function() {
 document.activeElement.blur();
 var inputs = document.querySelectorAll('input');
 for(var i=0; i < inputs.length; i++) {
  inputs[i].blur();
 }
};