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();
 }
};

4 comments:

  1. thanks, it's very useful for me.

    ReplyDelete
  2. yep, this helped. Thank you.
    I am developing a Phonegap app and have replaced all onclick events with custom ontouschstart-ontouchend logic, to increase speed. This however did not take care of hiding the keyboard once i hit a button, since. Yours is the solution.
    (describing to help more people find your answer on search ;) )

    ReplyDelete
  3. For those using Phonegap with either MooTools or jQuery:

    $('input-box-id').blur();

    Great article, thank you.

    ReplyDelete
  4. too bad this don't work for Android

    ReplyDelete