views:

3445

answers:

5

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

A: 

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

Jason Punyon
+1  A: 

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
+21  A: 

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
amazing stuff. It worked for me.
Vijay Balkawade
+14  A: 

There is a document.activeElement property, but at the moment it is only supported by Internet Explorer and Firefox 3+ and Opera.

It seems like Safari and Chrome don't support this yet. As it is included in the HTML5 draft, I presume it will be more widely supported in a matter of time and the best way to go is simply use this property and try to gracefully degrade for non-supporting browsers.

Note: this property does only contain form elements.

Aron Rotteveel
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
A: 

What about IE9 Beta? document.activeElement doesn't work. Returns Unspeciafied error.

Ilia