About
This page shows you how you can create your own event type.
Steps
1):
Creation of the callback function executed when the event dispatch
In this step, we create the HTML and the code that will be called when the event is fired/dispatched.
- This utility function is used to print a node id
function getNodeId(node){
let nodeId = node.nodeName;
if ("id" in node){
nodeId += "#"+node.id;
}
return nodeId.toLowerCase();
}
- The HTML that we use where javascript will run.
<p>Hello <span id="world">world</span>!</p>
- The callback function that uses the utility function and that we 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);
}
Add the event listeners
- The custom event type (ie event name) is just a string with a name as identifier
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
- Create the event and dispatch it against the span world element
var myEvent = new Event(eventName, {bubbles:true})
document.getElementById("world").dispatchEvent(myEvent)
Result
The two listeners will execute their callback function.