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 it should automatically get focus when the page loads 😉

<input type="text" name="second" id="second" autofocus />

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 />

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.

Full HTML5 Example

Please notice the script used after the Second Input.

The code:

< !DOCTYPE html>
<html lang="en">
<meta charset=utf-8 />
<title>Autofocus Example | Developer's Blog</title>

<form action="" method="">
    <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>
           if (!("autofocus" in document.createElement("input"))) {

    <p><input type="submit" /></p>
<br /><br /><a href="">Back to the post</a>

5 Responses to “Autofocus in HTML5”

  1. davv November 3, 2011 at 12:30 am #

    because of this thing, you cant call a js function “autofocus” anymore


  2. Yamuna August 5, 2013 at 11:18 am #

    Sample Demo Code:

    <form action="demo_form.asp">
      First name: <input type="text" name="fname" autofocus><br>
      Last name: <input type="text" name="lname"><br>
      <input type="submit">

    If we add autofocus attribute to Last name, the function doesn’t works properly….
    Anyone can tell me the reason

    <form action="demo_form.asp">
      First name: <input type="text" name="fname"><br>
      Last name: <input type="text" name="lname" autofocus><br>
      <input type="submit">
    • Rick August 5, 2013 at 4:30 pm #

      Hi Yamuna,

      You should try some of the variations:

      autofocus=”” or autofocus=”autofocus”


  3. Alexander October 28, 2014 at 3:53 pm #

    It is also supported in Internet Explorer, starting version 10

Leave a Reply

Add <code> Some Code </code> by using this tags.