HTML5 Tutorial - Input Attr : Autofocus

Input Attr : Autofocus

Autofocus is an boolean attribute of form field that make browser set focus on it when a page is loaded. If you still don't understand what that is, please go to Google and you notice you just type your search string without first click on the big textbox.

This is because Google has set focus to that textbox automatically (I am not saying Google uses HTML5 "autofocus") and save you ONE mouse click.

below is the code to do it, piece of cake.

<label for="name">Your name goes here :</label><input id ="name" type="text" autofocus/> <br />
<label for="mothername">Your dog's name goes here :</label><input id ="mothername" type="text" />

"autofocus" is a boolean attribute, it is needless to set any value to it.

As usual, not every web browser supports "autofocus"

BrowsersAutofocus Support
IE 10
Firefox 4
Safari 4.0
Chrome 3.0
Opera 10

To implement a little bit more foolproof "autofocus", you will have to again use Javascript to check if a web browser supports "autofocus", if not, just set focus with Javascript.

Below is actually a demo as well as a test. If your web browser support Autofocus, you will notice the cursor is blinking in the first textbox, if your web browser does not support it, it will be set focus at the second input textbox.


<script>
function testAttribute(element, attribute) {
   var test = document.createElement(element);
   if (attribute in test) {
    return true;
  }
else
  return false;
}

window.onload = function() {
  if (!testAttribute('input', 'autofocus'))
  document.getElementById('Text2').focus();
//for browser has no autofocus support, set focus to Text2.
}
</script>
<label for="Text1">Support Autofocus :</label><input id ="Text1" type="text" autofocus/> <br />
<label for="Text2">No Autofocus Support :</label><input id ="Text2" type="text" />