views:

119

answers:

5

I know this shouldn't be that hard, but I couldn't find the answer on Google.

I want to execute a piece of javascript that will clear the focus from whatever element it is on without knowing ahead of time which element the focus is on. It has to work on firefox 2 as well as more modern browsers.

Is there a good way to do this?

A: 

This question might have some answers for you: http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element-has-focus

Jonathan
Unfortunately, that simply isn't scalable. Thanks though.
Andres
A: 

Answer: document.activeElement

---edit----

Technically: document.activeElement.blur()

----edit 2----

function onElementFocused(e)
{
    if (e && e.target)
        document.activeElement = 
        e.target == document ? null : e.target;
} 

if (document.addEventListener) 
    document.addEventListener("focus", onElementFocused, true);
Jud Stephenson
Doesn't work in firefox 2.0.
Andres
If Firefox 2, with 0.66% browser share, is a deal breaker ... I have a fix, which is in my edited answer.
Jud Stephenson
+5  A: 

.focus() and then .blur() something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.

Kevin Reid
Is there a way to make an invisible element that has focus?
Andres
I'm not an expert on the best way to do that; but you could certainly position it off-screen or outside of the bounds of an `overflow: clip` styled element. But you could just use a field that already exists on the page. Or create one just for the purpose and remove it again.
Kevin Reid
+2  A: 

dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?

plodder
A: 

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

kennebec