onfocus
The onfocus event is triggered when an element gains focus. It is commonly used with input fields.
onfocus event
The onfocus
event is triggered when an element receives focus, usually through keyboard navigation or mouse clicks. It is commonly used to improve user interaction with forms and other interactive elements, such as <input>
.
Syntax
In HTML
index.html
<element onfocus="myScript">
In JS
script.js
object.onfocus = function(){myScript};
addEventListener()
function is used. In JavaScript, the
script.js
object.addEventListener("focus", myScript);
Example
::event-onfocus
::
index.html
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The focus Event</h2>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function changes the background-color.</p>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</body>
</html>
In this example, an alert will appear when the input field receives focus.
Values
The
onfocus
attribute is the reverse of the onblur
attribute.Conclusion
The onfocus
event enhances user interaction by triggering actions when an element gains focus. It is particularly useful in forms and other interactive elements, such as <input>
.