One of the great things about HTML5 is the improvements that the spec makes on forms. No longer does everything have to be a text input. HTML5 gives us input types for telephone (tel), URL’s (url), search (search) and more! Along with all these new input types are new attributes. One of those attributes is the autofocus attribute. The autofocus attribute tells the browser which input to focus on when the page is loaded. For older browsers that do not recognize HTML5, you can use Modernizer along with jQuery to mimic the autofocus funtionality with minimal code.

$(function() {
    if(!Modernizr.input.autofocus) {
        $('input[autofocus]').focus();
    }
});

When this function runs, Modernizer checks to see if the browser supports the autofocus attribute. If it does not, we use jQuery to find inputs with the autofocus attribute and then put that input in focus when the page loads.

Posted by: John Dugan

Comments