onfocusout
Event
Example
Execute JavaScript when an input field is about to lose focus:
<input type="text" onfocusout="myFunction()">
More examples are included at the bottom of this page.
Definition and Usage
The onfocusout
event is triggered when an element is about to lose focus.
Tip: The onfocusout
event is similar to the onblur event. The main difference is that the onblur
event does not support bubbling. Therefore, if you need to check if an element or its child elements have gained focus, you should use the onfocusout
event.
Tip: Although Firefox does not support the onfocusout
event, you can use the onfocus event (with the optional parameter useCapture in the addEventListener()
method) to check if an element or its child elements have lost focus.
Tip: The opposite event of onfocusout
is the onfocusin event.
Browser Support
Event | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
onfocusout | Yes | Yes | Yes | Yes | Yes |
Note: In Chrome, Safari, and Opera 15+ browsers, the onfocusin
event using HTML DOM syntax may not work properly. However, it works as an HTML element when using the addEventListener()
method.
Syntax
In HTML:
In JavaScript (may not work in Chrome, Safari, and Opera 15+):
In JavaScript, using addEventListener()
method:
Note: Internet Explorer 8 and earlier versions do not support the addEventListener() method.
Technical Details
Bubbles: | Yes |
---|---|
Cancelable: | No |
--- | --- |
Event Type: | FocusEvent |
--- | --- |
Supported HTML Tags: | All HTML elements except: <base> , <bdo> , <br> , <head> , <html> , <iframe> , <meta> , <param> , <script> , <style> , and <title> |
--- | --- |
More Examples
Example
Using "onfocusin" and "onfocusout" events:
<input type="text" onfocusin="focusFunction()" onfocusout="blurFunction()">
Example
Event delegation: Set the useCapture parameter of addEventListener()
to true (for focus and blur):
<form id="myForm"> <input type="text" id="myInput"></form>
<script>var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow"; }
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = ""; }
</script>
Example
Event delegation: Using the focusout
event (not supported in Firefox):
<form id="myForm"> <input type="text" id="myInput"></form>
<script>var x = document.getElementById("myForm");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);function
myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow"; }
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = ""; }
</script>