autofocus

The autofocus attribute in HTML automatically selects a specified input element when the page is loaded.

autofocus attribute

The autofocus attribute in HTML automatically focuses on a specific form element when the page loads, making it the active focus and allowing users to start typing or interacting with it immediately. This can improve the user experience on forms where immediate action is expected.

Syntax

index.html
<tagname autofocus />

Example

Enter your name:

index.html
<p>Enter your name:</p>
<input type="text" autofocus="autofocus">

Key Points

  • Only one element per document or dialog can have autofocus. If multiple elements have it, only the first receives focus.
  • The attribute can be applied to any element, not just form controls, including contenteditable areas.

Applicable to

The autofocus attribute can be used with the following elements:

ElementsAttribute
<button>autofocus
<input>autofocus
<select>autofocus
<textarea>autofocus

Accessibility Concerns

Automatically focusing on an element may create challenges for screen reader users and individuals with cognitive impairments. It can cause unexpected page scrolling or activate virtual keyboards, leading to confusion.

It's important to use the autofocus attribute thoughtfully, keeping accessibility in mind.

Conclusion

The autofocus attribute improves user experience by automatically focusing on a specific element when the page loads. However, it should be used sparingly, as it can create accessibility challenges, especially for screen reader users. Always consider the potential impact on all users when implementing this feature.