Home > Enterprise >  How to unfocus current element?
How to unfocus current element?

Time:08-25

I use (document.activeElement as HTMLElement).blur(); and it works. But when I press Tab after that, the focus moves forward one element, which is why I think about how to make the focus go to the previous element every time the command (document.activeElement as HTMLElement).blur(); fires.

CodePudding user response:

Based on your response to my comment (Appreciate it!) the only way I know how to do something like this is to keep track globally of the last active element and then restore it.

In the example below I save the last focused element when a user hits space (the key I chose to make an element blur). When a user presses tab or shift tab if we happen to have a saved element we prevent it's default action (which would be going to the next or previous element). Instead we manually set the focused element to the one we saved. We then make sure to clear the saved state.

let lastFocused = null;

document.body.addEventListener('keydown', (e) => {
  if (e.code === 'Space') {
    lastFocused = document.activeElement
    document.activeElement.blur();
  }

  if (e.code === 'Tab') {
    if (lastFocused) {
      e.preventDefault()
      lastFocused.focus();
      lastFocused = null;
    }
  }
});

Here is a working example as well

let lastFocused = null;

document.body.addEventListener('keydown', (e) => {
  if (e.code === 'Space') {
    lastFocused = document.activeElement
    document.activeElement.blur();
  }

  if (e.code === 'Tab') {
    if (lastFocused) {
      e.preventDefault()
      lastFocused.focus();
      lastFocused = null;
    }
  }
});
<p>Press Space to unfocus an element, then press tab or shift tab to continue on that element</p>

<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">

  • Related