Autofocus in HTML5
You know what? Playing with forms and HTML5 can be really funny.
From now on no more JavaScript to autofocus a form input.
One single Attribute
Just add autofocus and you’re done
<input type="text" name="second" id="second" autofocus />
Autofocus Supported Browers
Google Chrome, Safari and Opera.
We can use a short JavaScript code to create the autofocus on Firefox and Internet Explorer. See the full example below.
Full HTML5 Example
Please notice the script used after the Second Input.
The code:
< !DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>Autofocus Example | Developer's Blog</title>
<body>
<form action="" method="">
<fieldset>
<legend>Form Name</legend>
<p>First Input: <input placeholder="write your e-mail" type="text" name="first" id="first" /></p>
<p>Second Input: <input type="text" name="second" id="second" autofocus /></p>
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("second").focus();
}
</script>
</fieldset>
<p><input type="submit" /></p>
</form>
<br /><br /><a href="http://php.quicoto.com/?p=401">Back to the post</a>
</body>
</head>
</html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>Autofocus Example | Developer's Blog</title>
<body>
<form action="" method="">
<fieldset>
<legend>Form Name</legend>
<p>First Input: <input placeholder="write your e-mail" type="text" name="first" id="first" /></p>
<p>Second Input: <input type="text" name="second" id="second" autofocus /></p>
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("second").focus();
}
</script>
</fieldset>
<p><input type="submit" /></p>
</form>
<br /><br /><a href="http://php.quicoto.com/?p=401">Back to the post</a>
</body>
</head>
</html>
Related PostsIf you liked Autofocus in HTML5; the posts below might interest you too:
|




November 3, 2011
00:30
because of this thing, you cant call a js function “autofocus” anymore
argh.