Sometimes, we want to clear the focus of an active element with JavaScript.
In this article, we’ll look at how to clear the focus of an active element with JavaScript.
Get the Focused Element with the document.activeElement Property
We can get the element that’s in focus with the document.activeElement
property.
Then we can call the blur
method on it to remove focus from the focused element.
For instance, if we have an input element:
<input>
Then we can prevent users from focusing on it by writing:
document.addEventListener("focus", (e) => {
document.activeElement.blur()
}, true);
We call addEventListener
with 'focus'
to listen to the focus event on document
.
In the event listener, we call document.activeElement.blur
to remove focus from the active element, which can be the input.
And we pass in true
as the 3rd argument so that the focus event propagates from parent to child instead of the other way around.
This way, we can get the element that’s focused on and call blur
on it to remove focus from it.
Conclusion
We can remove focus from an active element with the document.activeElement.blur
method.