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?

Community
  • 1
  • 1
Peanut
  • 18,967
  • 20
  • 72
  • 78

5 Answers5

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).

Aron Rotteveel
  • 81,193
  • 17
  • 104
  • 128
  • 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 09 '09 at 15:24
  • [MDN says document.activeElement](https://developer.mozilla.org/en-US/docs/DOM/document.activeElement) is supported in IE4 even, let alone Chrome 2+ and Firefox 3+. Any chance to update this answer? – Dan Dascalescu Nov 13 '12 at 06:59
  • Chrome supports this now – Philip May 03 '13 at 01: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.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
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).

ernesto
  • 1,771
  • 2
  • 18
  • 18
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.

cic
  • 7,310
  • 3
  • 23
  • 35
-2

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

Restore the Data Dumps
  • 38,967
  • 12
  • 96
  • 122