HTML onfocus Event Attribute
Description
The onfocus
HTML event attribute specifies a JavaScript function to be executed when an element receives focus. Focus is when an element is selected and can be interacted with, such as when a user clicks on an input field or navigates to a link using the keyboard.
The onfocus
attribute can be used on any HTML element, but it is most commonly used on form elements, such as input fields, select boxes, and buttons. This is because form elements are often the focus of user interaction.
Here is an example of how to use the onfocus
attribute on an input field:
<input type="text" onfocus="myFunction()">
The myFunction()
function will be executed when the user clicks on the input field.
Here is an example of how to use the onfocus
attribute on a link:
<a href="index.html" onfocus="this.style.color='red'">Home</a>
When the user navigates to the link using the keyboard, the link text will turn red.
The onfocus
attribute can be used to perform a variety of tasks, such as:
- Focusing the user's attention on an element
- Changing the appearance of an element
- Validating form data
- Submitting a form
- Performing an AJAX request
Syntax
<element onfocus="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE html>
<html>
<head>
<title>onfocus event</title>
</head>
<body>
<p>Click on the field, and then next to it. When you click on an element, due to the onfocus event attribute, the script is triggered when the element receives focus, and thanks to the onblur event attribute, the script is launched when the focus is lost.</p>
<input type="text" name="testInput" id="testInput" onblur="blurFunction()" onfocus="focusFunction()">
<script>
function blurFunction() {
document.getElementById("testInput").style.background="khaki";
}
function focusFunction() {
document.getElementById("testInput").style.background="red";
}
</script>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onfocus
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023