onfocusinEvent
Examples
Execute JavaScript when an input field is about to gain focus:
Try it Yourself »
More examples are provided at the bottom of this chapter.
Definition and Usage
The onfocusin event fires when an element is about to gain focus.
Tip:The onfocusin event is similar to theonfocusevent. The main difference is that the onfocus event does not support bubbling. Therefore, if you want to know whether an element or its child elements have gained focus, you need to use the onfocusin event.
Tip:Although Firefox does not support the onfocusin event, you can use theonfocus(optional parameter of the addEventListener() methoduseCapture) capture listener event to see whether an element or its child elements have gained focus.
Tip:The opposite event of the onfocusin event is theonfocusoutevent.
Browser Support
| Event | |||||
|---|---|---|---|---|---|
| onfocusin | Yes | Yes | Not supported | Yes | Yes |
Note:In Chrome, Safari, and Opera 15+ browsers, the onfocusin event using HTML DOM syntax may not work properly. However, as an HTML element, it works properly when using the addEventListener() method.
Syntax
In HTML:
In JavaScript (may not work properly in Chrome, Safari, and Opera 15+):
In JavaScript, using the addEventListener() method:
Note:Internet Explorer 8 and earlier IE versions do not support theaddEventListener()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
Use the "onfocusin" and "onfocusout" events together:
Try it Yourself »
Example
Event delegation: set addEventListener()'suseCaptureparameter to true (for gaining and losing focus):
<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>
Try it Yourself »
Example
Event delegation: use the focusin event (not supported in Firefox):
<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>
Try it Yourself »
Other Extensions
Event Object