What is the autofocus attribute in HTML?

Overview

To enter the data on web pages, you must have felt that it is an extra step to click on the input field to enter the data. To overcome this issue, we have an HTML attribute called autofocus.

When the autofocus attribute is applied on the input element, the cursor will focus on that input field when the web page is loaded. This enables us to enter the data without clicking on the input field manually.

Syntax

<input autofocus />

Code example

We provide an autofocus attribute on the input element that accepts a username as the input data.

<html>
<head>
</head>
<body>
<div id="content">
<form>
<label for="username">Username:</label>
<!-- provide autofocus attribute -->
<input id="username" type="text" autofocus >
</form>
</div>
</body>
</html>

Note: If the output doesn’t work as expected, please try it on your local setup.

Free Resources