Autofocus is also one of the important enhancement in HTML5. In OLD days we used to achieve this with JavaScript code. But now this can be achieved with the HTML code only. We just need add one more attributes to the HTML element.
For example if you look at the Google Homepage; cursor is automatically focused on search field. User don’t have to get focus on that manually they just can start searching directly without placing the cursor on search field manually. Ultimately this increases the User Experience of your website.
So to achieve the autofocus we just need to palce one attribute to the HTML element. This attribute can be places on any HTML element but it is well suited for Text boxes and Text area. Just have a look at below HTML code for the same.
[cc lang=”html”]
[/cc]
Above I have mentioned; this will increase the User Experience also we know that HTML5 is not fully supported on all browsers. So what about the User Experience for the who are using older or other browser which does not support HTML5 fully? Well in this case JavaScript comes to the rescue.
Here I don’t mean to say that don’t use HTML5 attribute and use JS only. But with JS we can detect the support for the HTML5 attribute and can place the fallback for the same. So now how our form should look like is as below:
[cc lang=”html”]
[/cc]
Above code is core javascript code so it will execute once all content are loaded of the webpage. So you might face delay in execution of the above code if you have more images in your web page.
So to overcome this situation it is recommended to use jQuery’s [code]document.ready[/code] or MooTools’ [code]domready[/code] (reference) event. It will execute on once DOM is initialized in the web page. So let’s see how you can have the same code with jQuery and Mootools.
Autofocus Fallback with jQuery
[cc lang=”js”]
$(document).ready(function() {
if (!(“autofocus” in document.createElement(“input”))) {
$(“#search_box”).focus();
}
});
[/cc]
Make sure you have included the jQuery main file before this code.
Autofocus Fallback with MooTools
Make sure you have included the at least MooTools core file.
[cc lang=”js”]
window.addEvent(‘domready’, function(){
if (!(“autofocus” in document.createElement(“input”))) {
$(“search_box”).focus();
}
});
[/cc]
Hope this become helpful to you. It is good to have the fallback in place to give equal justice to older browsers too. Any thoughts?