MyInternships.in

HTML Attributes

HTML <button> autofocus Attribute

The autofocus attribute on a <button> gives it keyboard focus automatically when the page loads. It is a boolean attribute often used in dialogs.


The <button> autofocus Attribute

autofocus is a boolean attribute that, when added to a <button>, causes that button to receive focus as soon as the page or dialog is displayed. This is common in modal dialogs and confirmation prompts where you want a default action to be one keypress away.

Syntax

ℹ️

Syntax: <button autofocus>Label</button>. It is boolean and takes no value. Only one autofocus element should exist per page.

The basic pattern
Example
<button autofocus>Confirm</button>

Example

Run the example. When the dialog appears, the Confirm button is focused, so pressing Enter activates it right away.

Focus the confirm button in a dialog
Example
<!DOCTYPE html>
<html>
  <body>
    <dialog open>
      <p>Submit this application?</p>
      <button>Cancel</button>
      <button autofocus onclick="alert('Submitted!')">Confirm</button>
    </dialog>
  </body>
</html>

Attribute Values

ValueDescription
autofocusPresent: the button is focused automatically when shown
(omitted)Absent: the button is not focused automatically
💡

In dialogs, autofocus works well on a safe default action. Avoid auto-focusing destructive buttons like Delete, since a stray Enter key could trigger them by accident.

Key Takeaways

  • autofocus is a boolean attribute usable on <button>.
  • It focuses the button as soon as the page or dialog shows.
  • It is ideal for the default action in a dialog.
  • Only one autofocus element should exist per page.
  • Never auto-focus destructive buttons like Delete.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships