How do you clear the focus in javascript?
Asked Answered
F

9

242

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?

Fluctuant answered 26/3, 2010 at 1:35 Comment(2)
what does clear focus mean? - is it the same as blur?Flowers
I want to make it so that no element in the browser has focus.Fluctuant
C
263

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);
Chiron answered 26/3, 2010 at 1:39 Comment(5)
If Firefox 2, with 0.66% browser share, is a deal breaker ... I have a fix, which is in my edited answer.Chiron
In 2013, the browser share of Firefox 2 is substantially less than 0.66%, and the simple document.activeElement.blur() is the best way to achieve this effect.Thorwald
I get the following: Property 'blur' does not exist on type 'Element'.ts(2339)Inclination
@Inclination See the answer I posted to this question, which addresses this problem.Prudi
document.activeElement is a read-only property. You cannot assign to it anythingDouse
C
99

.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.

Chuckwalla answered 26/3, 2010 at 1:43 Comment(6)
Is there a way to make an invisible element that has focus?Fluctuant
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.Chuckwalla
I think that setting the focus to an element off-screen will force a scroll to that element. However, you can create an invisible element for the purpose. That being said, some browsers may have a hard time to remove the caret. Just blur() would probably work better. You could still get keys with a keyup (keydown) event handler.Ammieammine
This answer is out of date and doesn't apply in the year 2017. Use activeElement instead, as in https://mcmap.net/q/116486/-how-do-you-clear-the-focus-in-javascriptUnlatch
It still works, just longer and moves the focus (which may interfere with TAB navigation) Also it's not immediately apparent what should "something else arbitrary" be.Rakeoff
Don't do this. Some screen readers will follow the keyboard focus, and will read out the change in focus.Landaulet
J
67
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();
Javelin answered 4/2, 2014 at 11:56 Comment(3)
I get Property 'blur' does not exist on type 'Element'.ts(2339)Inclination
you would need to cast as HTMLElement.Windham
Although IE9 has fallen by the wayside, what it was doing actually was somewhat sensible, and supporting this behavior seems like a good idea, should other browsers decide to implement this same behavior. Heck, chrome could implement a flag for this behavior tomorrow.Elbrus
P
65

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.

Prudi answered 5/7, 2019 at 8:36 Comment(3)
A similar solution with the newer as type cast: (document.activeElement as HTMLElement).blur().Glabella
I prefer document.activeElement?.blur && document.activeElement.blur()Abysmal
as does not ensure that the element is an HTMLElement. It just satisfies the type checker. It will crash if blur is not defined.Compassion
L
10

For anyone using typescript, use

(document.activeElement as HTMLElement).blur();

This makes sure the element is of type HTMLElement

Luncheonette answered 18/1, 2022 at 0:23 Comment(1)
This does not ensure that the element is an HTMLElement. It just satisfies the type checker. Wrap it in if(document.activeElement instanceof HTMLElement) to avoid crashing on non-HTML DOM nodes.Compassion
N
4

I prefer document.activeElement?.blur && document.activeElement.blur().

I am using vue & react: In my case, I can call this about anywhere between components, and it will remove the focus.

Nephritis answered 14/6, 2022 at 6:34 Comment(1)
This one throws an error too. 'blur' does not exists on Element. So there is "non instanceof" version of the Element.blur typeguard. document.activeElement && "blur" in document.activeElement && document.activeElement.blur && typeof document.activeElement.blur === "function" && document.activeElement.blur();Brandeebranden
F
2

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

Flowers answered 26/3, 2010 at 2:3 Comment(0)
E
1

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.

Emylee answered 26/3, 2010 at 2:34 Comment(0)
P
-5

With jQuery its just: $(this).blur();

Prynne answered 21/9, 2018 at 6:44 Comment(1)
This is an old answer so you may know by now, but there are two reasons this answer does not apply. 1. It assumes the OP was using jquery, 2. this needs to be the focused element, while the question explicitly states the OP does not know the focused element ahead of time.Longspur

© 2022 - 2024 — McMap. All rights reserved.