Skip to content
Advertisement

Check if a FocusEvent was caused by tab losing focus

How, if possible, would I check if an input has lost focus because of a tab switch/window lost focus.

Usecase: I am resetting a form on blur and would like to make the data persist if a user merely switches tabs or the window loses focus

I am aware that I could instead just check for a click event happening outside the input but I would also like to include the possibility of a user tabbing out of the form which is why I have the handle attache to the general blur event.

Advertisement

Answer

I managed to acheive this using document.hasFocus.

e.g code:

 handleBlur = () => {
    if (!document.hasFocus()) {
      return;
    }

    this.deactivate()
  };
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement