Creating Custom Events in JavaScript



Creating Custom Events

DOM events provide a great deal of functionality. In some cases, you might want to create a custom event to use more generically.

To create a custom event, you use the CustomEvent object.

To use custom events, you first need to create one by using the window.CustomEvent object as show in the following code:

<body>
<script type="text/javascript">
var myEvent;
  var customEvent = function () {
      try {
      myEvent = new CustomEvent(
         "anAction",
          {
              detail: { description: "a description of the event", 
                        timeofevent: new Date(), 
                        eventcode: 2 },
              bubbles: true,
              cancelable: true
          }
      );
</script>
</body>

The CustomEvent object constructor accepts two parameters:

  • The first parameter is the name of the event. This is anything that makes sense for what the event is supposed to represent. In this example, the event is called anAction.
  • The second parameter is a dynamic object that contains a detail property that can have properties assigned to it containing information that should be passed to the event handler.
    Also, the parameter provides the ability to specify if the event should bubble and whether the event can be cancelled.

Next, the event is assigned to an element on the page by using the addEventListener method and the event is raised by using the dispatchEvent method.

The following code demonstrates when using a custom event:

<body>
<input type="submit" onclick="customEvent()" value="SHOW CUSTOM EVENT"/>
<script type="text/javascript">
    var myEvent;
    var customEvent = function () {
        try {
            myEvent = new CustomEvent(
               "anAction",
                {
                    detail: {
                        description: "a description of the event",
                        timeofevent: new Date(),
                        eventcode: 2
                    },
                    bubbles: true,
                    cancelable: true
                }
            );
            document.addEventListener("anAction", customEventHandler);
            //Finally, the event is raised by using the dispatchEvent method:
            document.dispatchEvent(myEvent);
        } catch (e) {
            alert(e.message);
        }
    }
    //A function called customEventHandler must exist for all this to work:
    function customEventHandler() {
        alert(window.event.detail.description);
    }
</script>
</body>

Ads Right