How to Change the Active Element using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 08 20222 min read

banner

Photo by Alex Jones

Change the Active Element using JavaScript #

To change the active element, call the focus() method on the element you want to focus. If the element can not be focused by default, set its tabIndex property to -1 before calling the focus method.

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" autofocus /> <div id="box">Hello world</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// โœ… set activeElement to another element const box = document.getElementById('box'); box.tabIndex = '-1'; box.focus(); // โœ… set activeElement back to `body` // document.activeElement.blur(); // ๐Ÿ‘‡๏ธ <body> element // console.log(document.activeElement);

We have an input element with the autofocus attribute set, which means that it will automatically get focused on page load.

To change the focus to a div element, we set the tabIndex property on the element to -1.

If I load the page from the example above, I can see that the div element has focus.

active element changed

Setting the tabindex property is not required for some elements, e.g. form elements.

A negative tab index means that the element cannot be reached using the keyboard, but can be focused with JavaScript.

To change the active element on the page back to the default (the body element), call the blur() method, e.g. document.activeElement.blur(). The blur method removes the focus from the element it was called on.

index.js
// โœ… set activeElement back to `body` document.activeElement.blur(); // ๐Ÿ‘‡๏ธ <body> element console.log(document.activeElement);

By calling the blur() method on the active element, we are able to remove focus from it, which sets the focus to the body element on the page.

If you console.log the value of document.activeElement after calling theblur method, you will see the body element logged to the console.

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