Call a function when an input field is about to lose focus:
<input type="text" onfocusout="myFunction()">
Try it Yourself »
More "Try it Yourself" examples below.
The onfocusout
event occurs when an element loses focus.
The onfocusout
event is often used on input fields.
The onfocosout
event is often used with form validation (when the user leaves a form field).
Event | Occurs When |
---|---|
focus | An element gets focus |
blur | An element loses focus |
focusin | An element gets focus |
focusout | An element loses focus |
In JavaScript, using the addEventListener() method:
object.addEventListener("focusout",
myScript);
Try it Yourself »
Bubbles: | Yes |
---|---|
Cancelable: | No |
Event type: | FocusEvent |
HTML tags: | ALL HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> |
DOM Version: | Level 2 Events |
onfocusout
is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
Using onfocus and onblur:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
Try it Yourself »
Clear input field on focus:
<input type="text" onfocus="this.value=''" value="Blabla">
Try it Yourself »
Event delegation: using focus and blur events:
Set useCapture parameter of addEventListener() to true:
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
let 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>
Try it Yourself »
Event delegation: using focusin and focusout events:
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
let 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>
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!