73

Possible Duplicate:
How do I find out which DOM element has the focus?

Is there a way in javascript to determine which html page element has focus?

1

5 Answers 5

90

Use the document.activeElement property.

The document.activeElement property is supported on Chrome 2+, Firefox 3+, IE4+, Opera 9.6+ and Safari 4+.

Note that this property will only contain elements that accept keystrokes (such as form elements).

3
  • 5
    Since Safari 4 was released yesterday. The latest release of all major browsers now support the document.activeElement property. You should still use the event-hack for older browsers though (see Paolo's answer): if(!document.activeElement) { /* add event-listeners to set document.activeElement for older browsers */ }
    – gregers
    Jun 9, 2009 at 15:24
  • MDN says document.activeElement is supported in IE4 even, let alone Chrome 2+ and Firefox 3+. Any chance to update this answer? Nov 13, 2012 at 6:59
  • Chrome supports this now
    – Philip
    May 3, 2013 at 1:32
49

Check out this blog post. It gives a workaround so that document.activeElement works in all browsers.

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);
}

Something to note:

This implementation is slightly over-pessimistic; if the browser window loses focus, the activeElement is set to null (as the input control loses focus as well). If your application needs the activeElement value even when the browser window doesn't have the focus, you could remove the blur event listener.

1
  • amazing stuff. It worked for me.
    – VJOY
    Sep 7, 2010 at 5:27
9

Just for the record, a little late, and of course not supported in old browsers:

var element = document.querySelector(":focus");

Should work on all elements (e. g. also anchors).

3

Maybe document.activeElement, don't know about browser support tho. Seems to work in Firefox and IE7, but I guess you have to try it in Opera and so on too.

0
-2

Check the bottom post. I think that would work...

Not the answer you're looking for? Browse other questions tagged or ask your own question.