Remove the focus from an Element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Remove the focus from an Element using JavaScript #

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.

index.html
<!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.

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

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

index.js
// ✅ Remove focus from currently active element document.activeElement.blur();

The document.activeElement property returns the element that currently has focus.

If there is no focused element, the 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.

index.js
document.activeElement?.blur();
If the 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.

index.html
<!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.

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

Use the search field on my Home Page to filter through my more than 3,000 articles.