Remove the focus from an Element using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 01 20222 min read

banner

Photo by Paul Green

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.

To remove the focus from the element, we used the HTMLElement.blur() method.

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

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 nulldepending on the browser's implementation.

To avoid getting an error due to calling the blur() method on a null value, you can 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee