0
0
HtmlConceptBeginner · 3 min read

What is autofocus attribute in HTML: Simple Explanation and Example

The autofocus attribute in HTML automatically sets keyboard focus on an input element when the page loads. This means the user can start typing immediately without clicking the field first.
⚙️

How It Works

The autofocus attribute tells the browser to place the cursor inside a specific input field as soon as the webpage appears. Imagine walking into a room and immediately sitting down at a desk without searching for a chair — that's what autofocus does for a form field.

This helps users start typing right away, saving them a click or tap. Only one element on the page can have autofocus, and the browser will ignore it if the page is opened in a background tab or if the user has accessibility settings that prevent automatic focus changes.

💻

Example

This example shows a simple form with a text box that gets focused automatically when the page loads.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Autofocus Example</title>
</head>
<body>
  <form>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" autofocus>
    <br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
  </form>
</body>
</html>
Output
A webpage with a form showing two fields: 'Name' and 'Email'. The cursor is blinking inside the 'Name' input box ready for typing as soon as the page loads.
🎯

When to Use

Use autofocus when you want to guide users to start typing in a specific field immediately, such as a search box or login form. It improves user experience by reducing extra clicks.

For example, on a login page, autofocus on the username or email field helps users start typing their credentials right away. On a search page, autofocus on the search input lets users begin typing their query instantly.

However, avoid using it on pages where multiple inputs compete for attention or where automatic focus might confuse users, such as complex forms or pages with many interactive elements.

Key Points

  • Only one element can have autofocus per page.
  • It works on input, textarea, and select elements.
  • Improves usability by focusing the cursor automatically.
  • Does not work if the page is loaded in a background tab.
  • Use thoughtfully to avoid confusing users.

Key Takeaways

The autofocus attribute sets keyboard focus on an input element when the page loads.
Use it to help users start typing immediately, like in search or login forms.
Only one element per page should have autofocus to avoid confusion.
It works on text inputs, textareas, and select dropdowns.
Avoid using autofocus on complex pages where automatic focus might disrupt user flow.