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:
- for a explicit event listener (ie addEventListener), the element where the listener is added.
relatedTarget
The related target gets the elements that has focus when the event occurs.
- ie a HTML element that has natively focus such as an anchor or a button
- or an element with the tabindex property set to 0 or more.
You will get it for instance in a blur event.
Demo
Implicit Dispatch
You have an implicit dispatch when your event propagate (ie bubble).
Demo:
<div>
<button>Click me</button>
</div>
- The callback function called on the click event
function printNodeNameCallback(e) {
console.log('-------------------');
console.log("Target: "+e.target.nodeName.toLowerCase());
console.log("Current Target: "+e.currentTarget.nodeName.toLowerCase());
}
- Attach event listener to the div and button element
document.querySelector("div").addEventListener("click", printNodeNameCallback);
document.querySelector("button").addEventListener("click", printNodeNameCallback);
- Result:
- the first callback is executed with the button as currenttarget
- the second callback is executed with the div as currenttarget showing that the event has propagated
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();
}
- A callback function that will give as listener parameter to be executed when the event is dispatched
function eventCallback(e) {
console.log('-------------------');
console.log("Target: "+getNodeId(e.target));
console.log("Current Target: "+getNodeId(e.currentTarget));
console.log("Event Phase: "+e.eventPhase);
}
- The custom event type (ie event name)
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: