Is there a way in javascript to determine which html page element has focus?
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.
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.
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.
What about IE9 Beta? document.activeElement doesn't work. Returns Unspeciafied error.