How to Remove the Focus on an Element in JavaScript

08/03/2021

Contents

In this article, you will learn how to remove the focus on an element in JavaScript.

Removing focus from an element

In JavaScript, you can remove focus from an element using the blur() method. This method is available on most DOM elements, including form controls, links, and buttons.

const myElement = document.getElementById('my-element');
myElement.blur();

In this example, the getElementById() method is used to get the element with the ID of my-element. The blur() method is then called on the element to remove focus.

Removing focus from an element when the user clicks outside of it

You can also remove focus from an element when the user clicks outside of it. To do this, you can listen for the click event on the document object and remove focus from the element when the click is outside of it.

document.addEventListener('click', function(event) {
  const myElement = document.getElementById('my-element');
  if (event.target !== myElement) {
    myElement.blur();
  }
});

In this example, the addEventListener() method is used to listen for the click event on the document object. The event.target property is used to get the element that was clicked on. If the clicked element is not the same as the my-element element, the blur() method is called on the my-element element to remove focus.

Removing focus from an element when the user presses the Tab key

You can also remove focus from an element when the user presses the Tab key to navigate to the next form control. To do this, you can listen for the keydown event on the my-element element and remove focus when the Tab key is pressed.

const myElement = document.getElementById('my-element');

myElement.addEventListener('keydown', function(event) {
  if (event.key === 'Tab') {
    myElement.blur();
  }
});

In this example, the addEventListener() method is used to listen for the keydown event on the my-element element. The event.key property is used to get the key that was pressed. If the Tab key was pressed, the blur() method is called on the my-element element to remove focus.