Open In App

HTML autofocus Attribute

Last Updated : 24 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

Syntax

<input type="text" autofocus> 

Note: This attribute is boolean, meaning it can either be present or absent.

Supported Tags

ElementPurpose
ButtonAutomatically focuses the button when the page loads.
InputAutomatically focuses the input field when the page loads.
SelectAutomatically focuses the select dropdown when the page loads.
TextareaAutomatically focuses the text area when the page loads.

Tip: It is important to note that only one element per document can effectively have the autofocus attribute. If multiple elements include autofocus, the first one in the DOM (Document Object Model) will receive focus

HTML autofocus Attribute Examples

Example 1: Focusing on the First Name “Input text Field” on Page Load

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: Autofocus on a Textarea Field

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

HTML autofocus Attribute – FAQs

Can I use autofocus on multiple elements in the same HTML form?

No, only the first autofocus attribute found in the DOM will take effect. If multiple elements have autofocus, only the first one will be focused.

Does autofocus work on all HTML elements?

The autofocus attribute works with various form elements, including <input>, <textarea>, <select>, and <button>.

How can I remove focus from an element that has autofocus?

You can use JavaScript to remove focus from an element by calling the blur() method, such as document.getElementById(‘myElement’).blur();.

Does autofocus work with dynamically created elements?

The autofocus attribute will not work automatically on dynamically created elements. You’ll need to use JavaScript to focus the element after it’s added to the DOM.

How does autofocus affect mobile browsers?

On mobile devices, the autofocus attribute can cause the on-screen keyboard to appear immediately upon page load, which might not be a desirable user experience.


Next Article

Similar Reads

three90RightbarBannerImg
  翻译: