HTML global attributeGlobal attributes

autofocus

Sets focus on an element right after the page loads or after a dialog opens.

Applies to
Elements that can receive focus: form fields, buttons, links and elements with tabindex
On this page

Example

#
HTML
<form>
  <label for="q">What do you want to learn today?</label>
  <input type="search" id="q" name="q" placeholder="e.g. flexbox, loops, arrays" autofocus>
  <button>Search</button>
</form>
Preview

In the preview, autofocus is deliberately disabled so the example does not steal focus from the documentation page. On an ordinary page the cursor would blink in the search field right away.

Definition and usage

#

The boolean autofocus attribute marks the element that should receive focus without clicking. On an ordinary page this happens right after it loads, and in a <dialog> and in a pop-up with the popover attribute at the moment they open. The user can then type right away or press Enter.

It works where one field is the main goal of the visit: a search engine page, a login, a dialog with a question. At most one element on the page should have it. If several do, focus goes to the first of them.

Automatic focus has a price. The browser scrolls the page to the element, so a screen reader user may miss everything above it, and on a phone focus in a text field can immediately slide up the keyboard and cover half the screen. Browsers also ignore autofocus in frames embedded from another domain and when the user has already moved focus elsewhere.

Syntax

#
Syntax
<element autofocus>…</element>

More examples

#
A safe button in a question dialog
HTML
<dialog id="remove-dialog">
  <p>Remove the “Python from scratch” course from favorites?</p>
  <form method="dialog">
    <button value="remove">Remove</button>
    <button value="cancel" autofocus>Cancel</button>
  </form>
</dialog>

<button type="button" onclick="document.getElementById('remove-dialog').showModal()">
  Remove from favorites
</button>

After the dialog opens, focus lands on the “Cancel” button, so an accidental press of Enter will not remove anything.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Do not give autofocus to a field in the middle of a long page. The user lands halfway down the content and will not know what they skipped.
  • When focus should move after a user action, for example after clicking “Edit”, call element.focus() in a script.
  • In React you write the attribute as autoFocus. React then calls focus() itself when the element appears on the page.

Related entries

#

Spotted a mistake or missing an example? Write to us.