View video tutorial

HTML onfocus Attribute

HTML

The HTML onfocus attribute is an event handler that triggers a script to execute when an element receives focus.

Definition and Usage


➔ Typically, the element gains focus when the user interacts with an element, such as clicking on an input element, tabbing to it, or setting focus programmatically.

➔ The onfocus attribute is the opposite of the onblur attribute, which is activated when an element loses focus.

Example
<input type="text" id="username" onfocus="myFunction(this)">

function myFunction(element) {
  element.style.backgroundColor = "yellow";
}
<!--This keyword within the onfocus attribute refers 
to the element that triggered the event. -->

Example
<input type="text" id="name" onfocus="myFunction(event)">

function myFunction(e) {
  e.target.style.backgroundColor = "skyblue";
}
<!--The event keyword within the onfocus attribute refers 
to the event that was triggered by the element.-->

Applies to

This attribute can be used on the following element.

Attribute Element
onfocus All visible elements

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML onfocus Attribute Example</title>
    <meta charset="utf-8" />
    <style>
        input[type="text"] {
            width: 230px;
            height: 30px;
            background-color: #efffff;
            font-size: 14pt;
            color: #000;
            border-radius: 5px;
            margin: 5px;
        }
        input[type="text"]:hover {
            background-color: #fff;
        }
    </style>
</head>
<body>
    <h2>HTML onfocus Attribute Example</h2>
    <p>Click on the textfield element to get focus and fire the event.</p>
    <input type="text" id="name" onfocus="myFunction(this)">
    <input type="text" id="name" onfocus="myFunction2(event)">
    <script>
        function myFunction(element) {
            element.style.backgroundColor = "yellow";
        }
        function myFunction2(e) {
            e.target.style.backgroundColor = "skyblue";
        }
    </script>
</body>
</html>

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