event.target vs event.relatedTarget

javascript, jquery

Solution

The `relatedTarget` event target is used by some events to specify a secondary target. On the other hand, target will be used by most DOM events to specify the primary target of an event.

For instance, during `focus` events, `target` will be the element gaining focus, and relatedTarget will be the element losing focus.

You can check out an exhaustive list of DOM events that specify a relatedTarget here: MouseEvent.relatedTarget.

As answered here

So judging from the above explanation we can say that

<div class="outer">
  <div class="inner"></div>
</div>

In this example, when you hover inside the inner div, then in the handler:

- `event.target` refers to the `.inner` element (this gives you the element where the event originated)

- `event.relatedTarget` refers to the `.outer` element (this gives you the element that receives the focus first and the loose the focus to other element)

you can check this fiddle for better understanding

Now in your own scenario

ondragleave: function (event) {
    /*when the dragged element leaves the drop target, remove the 
    .drop-target class from the current focused element*/
    event.target.classList.remove('drop-target');
    
    /*remove the .can-drop class from the element that looses focus 
    to the current focused element and changed the text to Dragged Out*/
    event.relatedTarget.classList.remove('can-drop');
    event.relatedTarget.textContent = 'Dragged out';

  }

Thanks.

Problem

I want to know the difference between event.target and event.relatedTarget. The following is a code chunk from drag and drop activity. ``` ondragleave: function (event) { // remove the drop feedback style event.target.classList.remove('drop-target'); event.relatedTarget.classList.remove('can-drop'); event.relatedTarget.textContent = 'Dragged out'; } ```

Original source

Related problems