View video tutorial

HTML autofocus Attribute

HTML

The autofocus attribute in HTML is a boolean attribute that, when present on a form control element, will automatically receive focus as the page loads, allowing the user to initiate interaction without having to click on it first.

Definition and Usage


➔ It does not require any value, just its presence on an element enables autofocus functionality.

➔ Although the autofocus attribute can be present on multiple elements, only the first element with the autofocus attribute in the DOM will actually receive focus.

➔ The primary purpose of autofocus is to improve the user experience by simplifying the initial interaction with a form or page, especially when a specific input is expected immediately.

Example
<input type="text" name="name" autofocus/>

Example
<input type="submit" value="Submit" autofocus/>

Applies to

This attribute can be used on the following element.

Attribute Element
autofocus <button>, <input>, <select>, <textarea>

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML autofocus Attribute Example</title>
    <meta charset="utf-8" />
    <style>
        input[type='text'],input[type='password'] {
            border: 1px solid rgb(19, 18, 18);
            border-radius: 5px;
            background-color: #d1e0ff;
            padding: 5px;
            margin-top: 10px;
            width: 200px;
            height: 23px;
        }
        input[type='submit'] {
            border: 1px solid rgb(19, 18, 18);
            border-radius: 5px;
            background-color: #d1e0ff;
            padding: 5px;
            margin-top: 10px;
            width: 120px;
            height: 42px;
        }
        input[type='submit']:hover,input[type='text']:hover,input[type='password']:hover {
            background-color: #c1d0ff;
        }
    </style>
</head>
<body>
    <h2>HTML autofocus Attribute Example</h2>
    <p>This is for example purposes only, it will not submit files to the server.</p>
    <form action="#" method="post">
        <table>
             <tr>
                <td>Name:</td>
                <td><input type="text" name="name" autocomplete="name" value="Demo" /></td>
             </tr>
             <tr>
                <td>Email:</td>
                <td><input type="text" name="email" autocomplete="email" autofocus/></td>
             </tr>
             <tr>
                <td>Password:</td>
                <td><input type="password" name="password" autocomplete="password"/></td>
             </tr>
             <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
             </tr>  
        </table>        
    </form>
</body>
</html>

Click on the "copy" button and try this example in your project.