Open In App

HTML autofocus Attribute

Improve
Improve
Like Article
Like
Save
Share
Report

The autofocus attribute in HTML is used to specify that the element should get focused when the page loads. It is a boolean attribute.

Syntax

<elementName autofocus>

Supported Tags

Element Purpose
Button autofocus Attribute Automatically focuses the button when the page loads.
Input autofocus Attribute Automatically focuses the input field when the page loads.
Select autofocus Attribute Automatically focuses the select dropdown when the page loads.
Textarea autofocus Attribute Automatically focuses the textarea when the page loads.

HTML autofocus Attribute Examples

Example 1: This example uses the autofocus attribute to create the focus on the first name while loading the page for the first time.

HTML




<!DOCTYPE html>
<html>
    <head>
        <title>HTML autofocus Attribute</title>
    </head>
 
    <body>
        <h2>HTML autofocus Attribute</h2>
        <form>
            <label
                >First Name:
                <input
                    type="text"
                    autofocus
                    placeholder="Enter Name"
                />
            </label>
        </form>
    </body>
</html>


Output:

autofocusAttributes2

Example 2: This example we sets autofocus on a textarea element, focusing on it when the page loads. It displays text suggesting it’s a computer science portal for geeks.

HTML




<!DOCTYPE html>
<html>
    <head>
        <title>HTML autofocus Attribute</title>
    </head>
 
    <body>
        <h2>HTML autofocus Attribute</h2>
        <textarea rows="3" cols="30" autofocus>
        A computer science portal for geeks.
    </textarea
        >
    </body>
</html>


Output:

autofocusAttributes3

HTML autofocus Attribute example output

Supported Browsers:



Last Updated : 07 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads