Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

autofocus

Focuses the element right after the page loads or a dialog opens.

Syntax

<input name="q" autofocus>

Examples

The cursor goes straight to the search field:

<form>
  <input type="search" name="q" placeholder="Search drinks" autofocus>
  <button>Find</button>
</form>

Focus on a button inside a dialog:

<button onclick="ask.showModal()">Delete</button>
<dialog id="ask">
  <p>Delete the order?</p>
  <button onclick="ask.close()">Yes</button>
  <button onclick="ask.close()" autofocus>No</button>
</dialog>

Notes

Use it with care: autofocus scrolls the page to the field and opens the keyboard on phones. It fits pages where the field is the only purpose (search, sign-in). A page should have only one such element.

See also

  • tabindex — Controls whether an element can be reached with the Tab key.
  • <input> — An input field; its kind is set by the `type` attribute.
  • <dialog> — A dialog box; a modal one is opened with `showModal()` and blocks the rest of the page.

In the tutorial

  • Forms — How a form works in HTML — the form tag, the input field, the name attribute, the submit button, action and the GET and POST methods.

Thanks for reading!

Donate to the site — we work hard for you.