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 it should automatically get focus when the page loads 😉
<input type="text" name="second" id="second" autofocus />
Code language: HTML, XML (xml)
NOTE: Several HTML5 attributes, like autofocus, can be written like this:
<input type="text" name="second" id="second" autofocus="" />
<input type="text" name="second" id="second" autofocus="autofocus" />
<input type="text" name="second" id="second" autofocus />
Code language: HTML, XML (xml)
Autofocus Supported Browers
Google Chrome, Safari, Firefox and Opera.
We can use a short JavaScript code to create the autofocus on old versions of Internet Explorer. See the full example below.
Demo
Full HTML5 Example
Please notice the script used after the Second Input.
< !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="https://ricard.dev/?p=401">Back to the post</a>
</body>
</head>
</html>
Code language: HTML, XML (xml)
I like your code.
Thank you!
It is also supported in Internet Explorer, starting version 10
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input
Yay 🙂
Sample Demo Code:
If we add autofocus attribute to Last name, the function doesn’t works properly….
Anyone can tell me the reason
Hi Yamuna,
You should try some of the variations:
autofocus=”” or autofocus=”autofocus”
Cheers
because of this thing, you cant call a js function “autofocus” anymore
argh.