Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

Today I discovered an MDN page that describes relatedTarget property of focus events ( blur, focus, focusin, and focusout). What's a relatedTarget?

If you attach a focus event listener the fired events will include the target element, but also element that stand in relation to the event.

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)
  });

The target and relatedTarget relations are:

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 or the next focused element will be, when a user is "tabbing" around in your interface.

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

If you want to play around and see the property in action, I've 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.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles