How do you clear the focus in javascript?
Solution 1:
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);
Solution 2:
.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.
Solution 3:
document.activeElement.blur();
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();
Solution 4:
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.