Join MDN and developers like you at Mozilla's View Source conference, 12-14 September in Berlin, Germany. Learn more at https://viewsourceconf.org

relatedTarget

Summary

Identifies a secondary target for the event.

Description

The relatedTarget property is used to find the other element, if any, involved in an event. Events like mouseover are oriented around a certain target, but also involve a secondary target, such as the target that is exited as the mouseover event fires for the primary target.

Events

Only MouseEvents have this property, and its value makes sense only for certain MouseEvents:

Event name relatedTarget role
focusin which EventTarget is losing focus
focusout which EventTarget is receiving focus
mouseenter which EventTarget the pointing device entered from
mouseleave which EventTarget the pointing device exited to
mouseout which EventTarget the pointing device exited to
mouseover which EventTarget the pointing device entered from
dragenter which EventTarget the pointing device entered from
dragexit which EventTarget the pointing device exited to

Example

<!DOCTYPE html>
<html>
<head>

<style>
div > div {
  height: 128px;
  width: 128px;
}
#top    { background-color: red; }
#bottom { background-color: blue; }
</style>

<script>
function outListener(event) {
  console.log("exited " + event.target.id + " for " + event.relatedTarget.id);
}

function overListener(event) {
  console.log("entered " + event.target.id + " from " + event.relatedTarget.id);
}

function loadListener() {
  var top = document.getElementById("top"), 
      bottom = document.getElementById("bottom");

  top.addEventListener("mouseover", overListener);
  top.addEventListener("mouseout", outListener);
  bottom.addEventListener("mouseover", overListener);
  bottom.addEventListener("mouseout", outListener);
}
</script>

</head>

<body onload="loadListener();">

<div id="outer">
  <div id="top"></div>
  <div id="bottom"></div>
</div>

</body>
</html>        

View on jsFiddle

Specification

See also

Document Tags and Contributors

 Last updated by: JykOg3,