How to create your own custom event type (Javascript, DOM)?

Devtool Chrome Event Listener

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>
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

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.





Discover More
Devtool Chrome Event Listener
DOM - Event Type (name)

An event is categorize by its type which is a property of the event object The type of an event is also known as the name of the event (Ref)...



Share this page:
Follow us:
Task Runner