What is autofocus attribute in HTML: Simple Explanation and Example
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.
<!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>
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
autofocusper page. - It works on
input,textarea, andselectelements. - 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
autofocus attribute sets keyboard focus on an input element when the page loads.autofocus to avoid confusion.