When switching focus between children of a <div>
, I'd like to fire a function. (The children are <span>
s, if that matters). I know I can handle this by binding the function to the blur
event of each of the children, but I'll potentially be creating (and destroying) lots of child elements, and would like to avoid binding the function to the children themselves.
For many events, like click or mouseover, I know that the event will bubble up the DOM and fire the same event on my parent div, where I can catch it and handle it. I'm not sure how blur and focus events would bubble, though. It seems like the parent still has focus, since one of its children has focus, but javascript is a strange and beautiful creature.
Can I rely on blur/focus events bubbling up when changing between children of an element, or is there a better way of handling changing focus between the children?
When switching focus between children of a <div>
, I'd like to fire a function. (The children are <span>
s, if that matters). I know I can handle this by binding the function to the blur
event of each of the children, but I'll potentially be creating (and destroying) lots of child elements, and would like to avoid binding the function to the children themselves.
For many events, like click or mouseover, I know that the event will bubble up the DOM and fire the same event on my parent div, where I can catch it and handle it. I'm not sure how blur and focus events would bubble, though. It seems like the parent still has focus, since one of its children has focus, but javascript is a strange and beautiful creature.
Can I rely on blur/focus events bubbling up when changing between children of an element, or is there a better way of handling changing focus between the children?
Share Improve this question asked Mar 3, 2014 at 20:14 ckerschckersch 7,6972 gold badges41 silver badges48 bronze badges2 Answers
Reset to default 6focus
and blur
do not have a bubbling phase - https://developer.mozilla/en-US/docs/Web/API/Element/focus_event
Instead, you can use focusin
that has bubbling.
Bubbling should work fine with blur and focus
var myElem = document.getElementById("foo");
myElem.addEventListener('blur', function(evt) {
var elem = evt.srcElement || evt.target;
console.log("blur: " + elem.name);
}, true);
myElem.addEventListener('focus', function(evt) {
var elem = evt.srcElement || evt.target;
console.log("focus: " + elem.name);
}, true);
IE uses onfocusin and onfocusout instead.
http://jsfiddle/p6bAL/