Artboard 16light, inspiration, solution, idea, innovation,ionicons-v5_logosGoogle Sheets iconSwift icon
Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

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.

  .addEventlistener('focus', (event) => {
    // ๐Ÿ‘† the element that received focus
    // ๐Ÿ‘† the element that lost focus (if any)

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

Event nametargetrelatedTarget
focuselement receiving focuselement loosing focus
blurelement loosing focuselement receiving focus
focusinelement receiving focuselement loosing focus
focusoutelement losing focuselement 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.

relatedTarget prototype on CodePen.

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 14 days ago.

Related Topics

Related Articles