Larry Steinle

November 11, 2013

Supercharged Html5 AutoFocus Fallback

Filed under: VS.Net,Web — Larry Steinle @ 8:32 pm
Tags: ,

The HTML5 specification introduces several helpful additions. One of my favorites is the autofocus attribute. This attribute ensures that the cursor is placed inside the first input, select or textarea tag containing the autofocus attribute.

Currently autofocus is supported in all major browsers. It is not supported in Internet Explorer 9 or older. Technically, I find it interesting that as web developers we only care about older versions of Internet Explorer. Backwards compatibility with other browsers is largely ignored. A testament to the popularity of IE and Microsoft’s continued support of older versions.

The online book, Dive Into HTML5, has an interesting article about autofocus in the section No9. A Form of Madness – Diving In. In this article they discuss a fallback option providing support for older browsers that can benefit from the autofocus attribute.

The following script supercharges the autofocus fallback strategy providing support for the input, select and textarea tags without having to know which tag contains the autofocus attribute.

function ApplyAutoFocusWhenNotSupported() {
    for (var i = 0, supportedTags = ["input", "select", "textarea"]; i < supportedTags.length; i++)
        for (var t = 0, tags = window.document.getElementsByTagName(supportedTags[i]) ; t < tags.length; t++) {
            var tag = tags[t];
            if (tag.attributes && tags.attributes && tags.attributes.getNamedItem && tags.attributes.getNamedItem("autofocus") === undefined) {
                tag.focus();
                return;
            }
        }
}
ApplyAutoFocusWhenNotSupported();

Happy coding!

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: