Question

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?

Was it helpful?

Solution

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.net/p6bAL/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top