Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
Answer:
document.activeElement
To do what you want, use
document.activeElement.blur()
If you need to support Firefox 2, you can also use this:
function onElementFocused(e)
if (e && e.target)
document.activeElement = e.target == document ? null : e.target;
if (document.addEventListener)
document.addEventListener("focus", onElementFocused, true);
–
–
–
–
–
–
Works wrong on IE9 - it blurs the whole browser window if active element is document body. Better to check for this case:
if (document.activeElement != document.body) document.activeElement.blur();
–
None of the answers provided here are completely correct when using TypeScript, as you may not know the kind of element that is selected.
This would therefore be preferred:
if (document.activeElement instanceof HTMLElement)
document.activeElement.blur();
I would furthermore discourage using the solution provided in the accepted answer, as the resulting blurring is not part of the official spec, and could break at any moment.
–
–
–
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.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.