Disable focus on a specific Element using JavaScript


Borislav Hadzhiev

Last updated: Jan 9, 2022


Photo from Unsplash

Disable focus on a specific Element using JavaScript #

To disable focus on a specific element, set the tabIndex property on the element to a value of -1. The tabIndex property can be used to specify that an element cannot be focused using keyboard navigation.

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" name="first_name" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

const element = document.getElementById('first_name'); element.tabIndex = '-1';

We set the element's tabindex to a value of -1.

This means that the element is not reachable via keyboard navigation, but could still be focused using JavaScript or by clicking on it with the mouse.

If you need to remove focus from a specific element, you can use the blur method.

const element = document.getElementById('first_name'); element.blur();

The method removes keyboard focus from the element it was invoked on.

If you need to make an element unclickable, set its disabled attribute.

const element = document.getElementById('first_name'); element.setAttribute('disabled', '');

When the element's disabled attribute is set, the element is not mutable or focusable.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.