Focus events include a relatedTarget property
- Published at
- Updated at
- Reading time
- 1min
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 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 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.
Join 5.4k readers and learn something new every week with Web Weekly.