Autofocus a form field with HTML5 or jQuery

Updated . Posted . Visible to the public.

In Webkit you can use the HTML5-attribute autofocus:

= form.text_field :title, :autofocus => 'autofocus'

Here is a jQuery fallback for browsers that don't speak HTML5:

var Autofocus = {

  supported: function() {
    return 'autofocus' in document.createElement('input');
  },

  fake: function() {
    $('[autofocus]').focus();
  },

  extend: function() {
    Autofocus.supported() || Autofocus.fake();
  }

};

$(Autofocus.extend);
Profile picture of Martin Straub
Martin Straub
Last edit
Keywords
input, auto, focus
License
Source code in this card is licensed under the MIT License.
Posted by Martin Straub to makandra dev (2010-08-26 09:32)