The FocusEvent.relatedTarget
property refers to the the secondary target of a focus event. Depending on the type of focus event, this is either the element losing focus (for focus
and focusin
) or the element receiving focus (for blur
and focusout
).
This is handy when you need to know which was the last element in focus, or which will be the next element in focus.
The focus and focusin events
The focus
event fires when an element receives focus; the focusin
event fires when an element is about to receive focus. The main difference is that the former doesn't support event bubbling, while the latter does.
For the focus
and focusin
events:
- The
target
property refers to the element receiving focus. - The
relatedTarget
property refers to the element losing focus (if any).
The blur and focusout events
The blur
event fires when an element loses focus; the focusout
event fires when an element is about to lose focus. The main difference is that the former doesn't support event bubbling, while the latter does.
For the blur
and focusout
events:
- The
target
property refers to the element losing focus. - The
relatedTarget
property refers to the element receiving focus (if any).
A note on null
Not all elements are focusable, meaning the relatedTarget
property may be null
. The MDN Web Docs say that relatedTarget
may also be set to null
for security reasons, like when tabbing in or out of a page.
An example
Here's a simple example. It listens to all focusin
and focusout
events in the document body, logging the values of the target
and relatedTarget
properties for comparison:
/**
* Handle focusin and focusout events.
* @param {FocusEvent} event - The FocusEvent interface.
*/
function handleFocus(event) {
// Log the event type
console.log(event.type.toUpperCase());
// Log the target and relatedTarget
console.log("target:", event.target);
console.log("relatedTarget:", event.relatedTarget);
// Log a newline character
console.log("\n");
}
// Handle focusin and focusout events
document.body.addEventListener("focusin", handleFocus);
document.body.addEventListener("focusout", handleFocus);
You can view the demo on CodePen.