Tuesday, 28 January 2025

Enhance User Experience with the HTML Autofocus Attribute

The autofocus attribute in HTML is used to automatically focus on an input element when a web page loads. This means that when the page is opened, the input field with the autofocus attribute is immediately ready to accept user input, allowing for a more seamless and user-friendly experience.

autofocus.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 action="/submit-form" method="POST">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" autofocus><br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password"><br><br>

    <input type="submit" value="Submit">
  </form>
</body>
</html>

 

Above snippet generate below screen.

 


You can observe that the username field is in the focus. This feature is useful in scenarios where you want users to immediately start typing in a specific field without needing to manually click on it.

 

Can I set autofocus to more than one element?

No, you cannot set the autofocus attribute on more than one element at a time in a single HTML document. The autofocus attribute is designed to focus only one element automatically when the page loads. If multiple elements have the autofocus attribute, the browser will typically only focus on the first element with autofocus in the document's order.


Previous                                                    Next                                                    Home

No comments:

Post a Comment