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 every element.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Darrell Brogdon
  • 6,843
  • 9
  • 47
  • 62

2 Answers2

9

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);
}
Community
  • 1
  • 1
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
2

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

Jason Watts
  • 1,086
  • 5
  • 13