Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
Use the blur()
method to remove the focus from an element, e.g.
input.blur()
. If you need to remove the focus from the currently active
element without selecting it, call the blur
method on the activeElement
property - document.activeElement.blur()
.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" autofocus /> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const input = document.getElementById('first_name'); // ✅ Remove focus from specific element input.blur(); // ✅ Remove focus from currently active element // document.activeElement.blur();
We selected the input
element using the document.getElementById()
method.
We used the HTMLElement.blur() method to remove the focus from the element.
blur()
method removes the keyboard focus from the element it was called on.If you want to remove the focus from the currently active element without
selecting it, call the blur()
method on the document.activeElement
property.
// ✅ Remove focus from currently active element document.activeElement.blur();
The document.activeElement property returns the element that currently has focus.
document.activeElement
property will return the body
element in most browsers, but it could also return null
depending on the browser's implementation.To avoid getting an error due to calling the blur()
method on a null
value,
use the optional chaining (?.) operator.
document.activeElement?.blur();
document.activeElement
property returns null
, the optional chaining operator will short-circuit returning undefined
instead of calling the blur()
method.If you need to focus a different element, you can use the focus()
method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" autofocus /> <input type="text" id="country" placeholder="Country" /> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const countryInput = document.getElementById('country'); countryInput.focus();
Even though the input
element with id
of first_name
has the autofocus
attribute set, we are able to change the focused element by calling the
focus()
method on a different element.