Open In App

HTML autofocus Attribute

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The HTML autofocus attribute is a powerful tool that enhances user experience by automatically setting the focus to a specific element when a webpage loads. This attribute is boolean, meaning it can either be present or absent.

Syntax:

<elementName autofocus>

Supported Tags

ElementPurpose
Button autofocus AttributeAutomatically focuses the button when the page loads.
Input autofocus AttributeAutomatically focuses the input field when the page loads.
Select autofocus AttributeAutomatically focuses the select dropdown when the page loads.
Textarea autofocus AttributeAutomatically focuses the text area when the page loads.

Examples of HTML autofocus Attribute

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:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads