The focusout event in JavaScript refers to the event handler that triggers when an element is on the verge of losing its focus. In addition to this, we have explored the blur event, which also serves as an event handler in JavaScript. While both blur and focusout are categorized as focus events, they exhibit a key distinction. Specifically, the blur event does not propagate, while the focusout event does propagate or bubble. Therefore, when a user notices that an element or one of its child elements is set to lose focus, it is advisable to monitor the onfocus event associated with that particular element.
Thus if the user performs the following actions, the focusout event will be invoked:
- When the user clicks outside the active element, the focus is lost.
- Switching to another application or file.
- Use TAB key/access key to navigate away from the active element, and so the focus is lost.
- Calling the blur method on an active element.
- Calling the setActive method on a non-active element that can be active.
- Calling the focus method on a non-active element that can be active.
Note: The focusin event is just the opposite of the focusout event, where the event action is performed when the user creates a focus on the active element. For focusin, we use onFocusIn event handler.
Example of focusout event
Let’s examine and comprehend both the focusin and focusout events using the following example:
<html>
<head>
<script type="text/javascript">
function Focus_In (event) {
event.srcElement.style.color = "red";
}
function Focus_Out (event) {
event.srcElement.style.color = "blue";
}
</script>
</head>
<body>
<center> <h3>Click on the textbox and observe </h3><br></br>
<form onfocusin="Focus_In (event)" onfocusout="Focus_Out (event)">
<b> User name: <input type="text value="Username"/></b><br/>
<br>
<b> Password <input type="password" value="*******"/></b> </center>
</form>
</body>
</html>
Code Explanation
- The above code is the html and JavaScript based code.
- In the body section of the html, we have created a form having a user and a password field.
- In the script section of the JavaScript, we have created two functions where FocusIn is for focusin event and FocusOut is for focusout event.
- While creating the form, we have invoked both the FocusIn and FocusOut functions.
- Two actions will be performed-When the user clicks on any of the textbox, the color of the text changes to red which means that focus is in. So, the FocusIn function is called. Another action takes place when the user clicks anywhere on the page but not on the active part (i.e. on the text of the textbox or on the password in the textbox) which means the focus is lost and thus the color changes back to blue. So, the FocusOut function is invoked in this case.
- Also note that when the user executes the code on the web browser, the color of the text is seen black unless the user does not makes any action.
The output of the above code is shown below: