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.

Community
  • 1
  • 1
Darrell Brogdon
  • 6,669
  • 8
  • 48
  • 59

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
  • 466,948
  • 77
  • 516
  • 433
2

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

Jason Watts
  • 1,088
  • 5
  • 13