HTML onblur Event Attribute
Description
The onblur
HTML event attribute fires when an HTML element loses focus. It is often used on input fields to validate the user's input when they leave the field. For example, you could use the onblur
event to check if a required field has been filled in, or to verify the format of an email address.
The onblur
event is also useful for other tasks, such as hiding or showing elements based on the user's focus. For example, you could use it to hide a tooltip when the user clicks off of the element that triggered it, or to show a suggestion list when the user focuses on a search input field.
To use the onblur
event, you simply add it to the HTML element that you want to respond to the event. The value of the attribute should be the name of a JavaScript function that will be called when the element loses focus. For example:
<input type="text" onblur="myFunction()">
The myFunction()
function will be called when the user clicks off of the input field. You can use this function to perform any task you want, such as validating the user's input or hiding or showing other elements.
Syntax
<element onblur="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE html>
<html>
<head>
<title>onblur 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 onblur
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023