remove focus after clicking in javascript

One solution to remove focus after clicking in JavaScript is to change the focus to a non-focusable and hidden element using the blur() method.

Here is an example code snippet that removes focus from a clicked element:

index.tsx
// Add event listener to document
document.addEventListener('click', removeFocus);

// Event handler function to remove focus
function removeFocus(event) {
  // Check if the clicked element is focusable
  if (event.target.tabIndex > -1) {
    // Create a non-focusable and hidden element
    const temp = document.createElement('button');
    temp.style.display = 'none';
    // Append the element to the document
    document.body.appendChild(temp);
    // Change the focus to the new element
    temp.focus();
    // Remove the element from the document
    document.body.removeChild(temp);
  }
}
599 chars
19 lines

In this code snippet, we are using the addEventListener() method to add a click event listener to the entire document. Whenever the user clicks anywhere on the page, the removeFocus() function is called.

Inside the removeFocus() function, we check if the clicked element is focusable by checking its tabIndex. If it is focusable, we create a new non-focusable and hidden element using the createElement() method and set its display property to none. We then append this element to the document.body element.

Next, we use the focus() method to set the focus on the new element, which automatically removes the focus from the clicked element. Finally, we remove the new element from the document.body element using the removeChild() method.

gistlibby LogSnag