
JavaScript focusout event
The focusout
event in JavaScript is triggered when an element loses focus. It occurs when the user moves focus away from an element, typically by clicking outside the element or tabbing to another element.
To handle the focusout
event in JavaScript, you can use the addEventListener()
method to attach a callback function to the event. Here’s an example:
HTML:
<input type="text" id="myInput">
JavaScript:
var inputElement = document.getElementById("myInput");
inputElement.addEventListener("focusout", function(event) {
console.log("Element lost focus");
// Perform additional actions here
});
In this example, the HTML code contains an <input>
element with the ID "myInput"
.
The JavaScript code retrieves the input element using document.getElementById("myInput")
and assigns it to the inputElement
variable.
The addEventListener()
method is then used to attach a focusout
event listener to the input element. When the input element loses focus, the provided callback function is executed.
In the callback function, you can perform any desired actions or logic when the element loses focus. In this example, it simply logs a message to the console using console.log()
. You can replace this with your own code to perform additional actions or interact with the element or its value.
By running this code, when the user clicks outside the input element or tabs to another element, the console will display the “Element lost focus” message, indicating that the focusout
event has been triggered.