How to focus element while loading the page in HTML ?
HyperText Markup Language(HTML) is the basic building block of web pages that defines a structure. This markup language is used by browsers to manipulate data like text, images, and other content so that they can be displayed in the required format. HyperText refers to the links that connect web pages and markup defines the text document within the tags.
How to focus the element while loading the page in HTML?
We want that an element should be in focus whenever we load the page. We can do this in 2 ways:
- Using autofocus attribute of the element.
- Using Window: load event.
Let’s explore both ways with examples.
1. Using autofocus attribute The autofocus attribute is a boolean attribute i.e it can only be true or false. When this attribute is present inside an element, it specifies that the element inside which it is present should automatically get focus whenever the page loads.
The autofocus attribute can be only used within the below mentioned elements –
Example: In this example, whenever the page loads the input element gets focus and we can see it as the background color of input changes to #8ecae6.
2. Using Window: load Event: The load event of window object is fired when the complete page has loaded including stylesheets and images. Now when the page has been loaded , we can use HTMLElement.focus() method to provide focus to our element(if can be focused). The focused element is the one that receive keyboard and similar events by default.
The focus() method can have an optional parameter that is an object providing options to control aspects of the focusing process.