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!
Leave a Reply