DEV Community

Discussion on: Mind the `document.activeElement`!

Collapse
 
westbrook profile image
Westbrook Johnson

A focusout event will be dispatched (and bubble, whereas blur events do not) when an element loses focus. This mirrors the focusin event that would have told you that an element has gained focus. You can checkout event.composedPath()[0] to ensure you reference the element from which this even originated. Check out open-wc.org/faq/events.html for more info on handling events in custom elements and across shadow DOM boundaries.

Is that what you're looking for?

At any one time, the following code can compare that:

const el = ... ; // how ever you gain access to the element in question
const root = el.getRootNode();
const { activeElement } = root;
const isElFocused = el === activeElement;
Collapse
 
ianemv profile image
Ian Villanueva

I think this is it. What I wanted is, to know that my component loses focus so I can toggle or trigger other events.

For now what I did is add a focusable element such as button to check if that is on focus and if focus out, trigger the event I wanted to do (basically just hide a pop-up div)