Recommended Courses:
onblur event
Definition and Usage
occurs when an object loses focus.
On the contrary. The onblur event is most commonly used with form validation code (for example, when the user leaves a form field). onfocus Eventevent is similar to
On the contrary. Tip: onfocusout Eventevent is similar to addEventListener() methodto achieve this. The main difference is that the onblur event does not bubble. Therefore, if you want to determine whether an element or its child elements have lost focus, you can use the onfocusout event. However, you can use the onblur event's
Example
Execute JavaScript when the user leaves the input field:
<input type="text" onblur="myFunction()">
More TIY examples are available at the bottom of the page.
Syntax
In HTML:
<element onblur="myScript">
In JavaScript:
object.onblur = function(){}myScript};
In JavaScript, use the addEventListener() method:
object.addEventListener("blur", myScript);
Note:Internet Explorer 8 and earlier versions do not support addEventListener() method.
Technical Details
Bubble: | Not supported |
---|---|
Cancelable: | Not supported |
Event type: | FocusEvent |
Supported HTML tags: | All HTML elements except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> and <title> |
DOM Version: | Level 2 Events |
Browser support
Event | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onblur | Supports | Supports | Supports | Supports | Supports |
More examples
Example
Use "onblur" and "onfocus" events together:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
Example
Event delegation: Set the useCapture parameter of addEventListener() to true:
<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: Use the focusin event (not supported by 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>