DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com on

TIL: Focus events include a relatedTarget property

Today I came across an MDN page describing the relatedTarget property of focus events. blur, focus, focusin, and focusout count as focus events.

It turns out that if you attach a focus event listener the fired event will include not only a target element but also a relatedTarget element.

document.querySelector('button')
  .addEventlistener('focus', (event) => {
    console.log(event.target);        
    // πŸ‘† the element that received focus
    console.log(event.relatedTarget); 
    // πŸ‘† the element that lost focus (if any)
  });
Enter fullscreen mode Exit fullscreen mode

The rules for target and relatedTarget in focus events are as follows:

Event name target relatedTarget
focus element receiving focus element loosing focus
blur element loosing focus element receiving focus
focusin element receiving focus element loosing focus
focusout element losing focus element receiving focus

Using relatedTarget, you can figure out what the previously focused element was when a user is "tabbing" around in your interface.

relatedTarget can also be null when there was no previous/next target. This happens, for example, when a button had focus, and the user clicks something that is not focusable.

That's complete news to me! 😲

If you want to play around and see the property in action, I built a quick prototype on CodePen.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!