DOM / Javascript - Event target / currentTarget

About

An event object has target properties that points to elements related to the event.

Type

target

event.target returns the object to which event is dispatched (its target). Ref.

This is:

  • for an implicit dispatch: ie event handler (ie on event), the element where the handler is defined
  • for an explicit dispatch: the element where the dispatchEvent function is called

currentTarget

currentTarget returns the object whose event listener’s callback is currently being invoked. Ref

This is:

Demo

Implicit Dispatch

You have an implicit dispatch when your event propagate (ie bubble).

Demo:

  • The button that will be clicked and a div where the event will propagate.
<div>
    <button>Click me</button>
</div>
function printNodeNameCallback(e) {
     console.log('-------------------');
     console.log("Target: "+e.target.nodeName.toLowerCase());
     console.log("Current Target: "+e.currentTarget.nodeName.toLowerCase());
}
document.querySelector("div").addEventListener("click", printNodeNameCallback);
document.querySelector("button").addEventListener("click", printNodeNameCallback);

Explicit dispatch

  • The HTML code. We will execute an event against the world span.
<p>Hello <span id="world">world</span>!</p>
  • Utility function to print the node id
function getNodeId(node){
  let nodeId = node.nodeName;
  if ("id" in node){
     nodeId += "#"+node.id;
  }
  return nodeId.toLowerCase();
}
function eventCallback(e) {
     console.log('-------------------');
     console.log("Target: "+getNodeId(e.target));
     console.log("Current Target: "+getNodeId(e.currentTarget));
     console.log("Event Phase: "+e.eventPhase);
}
let eventName = "myEvent";
  • Add two listeners on document and body that executes the callback for this event
document.addEventListener(eventName , eventCallback, {capture: true})
document.body.addEventListener(eventName , eventCallback)
  • Create the event and dispatch it against the span world element
var myEvent = new Event(eventName, {bubbles:true})
document.getElementById("world").dispatchEvent(myEvent)
  • Result:

Documentation / Reference


Powered by ComboStrap