Autofocus a form field with HTML5 or jQuery

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);
Over 13 years ago