Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript, how to eliminate any focus in the document?

Tags:

javascript

I mean, is there a way to force a blur? so if any component (button, inputext, etc.) is focused it will be blured, hope this makes sense :)

like a document.blur(), I need this because everytime user pressed F5 I need to eliminate any focus before it refreshes.

like image 202
BugsForBreakfast Avatar asked Nov 21 '25 02:11

BugsForBreakfast


2 Answers

You can use document.activeElement.blur() but in my experience, some element is always going to have focus, even after you do that. For instance, on Chrome, the following ends up with body having focus, even after removing focus from (say) the input:

setInterval(() => {
    if (document.activeElement) {
        document.activeElement.blur();
    }
    console.log(document.activeElement && document.activeElement.nodeName);
}, 1000);
<input type="text" id="x">

But it does remove focus from the input, perhaps that's good enough for your use case.


From your comments explaining the situation further, I'd tend to think you'd want:

if (document.activeElement && document.activeElement !== document.body) {
    document.activeElement.blur();
}
like image 107
T.J. Crowder Avatar answered Nov 22 '25 14:11

T.J. Crowder


https://developer.mozilla.org/en-US/docs/Web/API/Window/blur window.blur() should do the trick.

like image 39
Rob Moll Avatar answered Nov 22 '25 16:11

Rob Moll