views:

558

answers:

2

Possible Duplicates:
How to determine which html page element has focus?
How do I find out which Javascript element has focus?

Is there a way to determine which element within the document currently has focus? Ideally without having to walk through ever element.

+4  A: 

Duplicate:

Long story short:

Some browsers (originally only IE, but Firefox 3 and Safari jumped on the wagon) support the document.activeElement property, which achieves what you want.

For older browsers, you need this hack to emulate the property:

function _dom_trackActiveElement(evt) {
    if (evt && evt.target) { 
        document.activeElement = evt.target == document ? null : evt.target;
    }
}

function _dom_trackActiveElementLost(evt) { 
    document.activeElement = null;
}

if (!document.activeElement) {
    document.addEventListener("focus",_dom_trackActiveElement,true);
    document.addEventListener("blur",_dom_trackActiveElementLost,true);
}
Paolo Bergantino
+1  A: 

You could attach onfocus to your body element, and let the focus change event bubble up

Jason Watts