JavaScript CustomEvent

By  on  

JavaScript events have been the gateway to user interaction within the browser since its inception. Not only do events tell us when an interaction happens, but events tell us type of interaction, the nodes involved, and provide us methods for working with the event. Creating custom events and triggering them have always been trickier. Using JavaScript's CustomEvent API, that trickery can be eliminated. The CustomEvent API allows developers to not only create custom events but trigger them on DOM nodes, passing data along the way. Best of all, the API is super simple!

The JavaScript

When working with customizing events, there's two components included in an event being "custom": a custom event name and the ability to trigger that event. Adding an event listener to an element, however, stays the same:

myElement.addEventListener("userLogin", function(e) {
	console.info("Event is: ", e);
	console.info("Custom data is: ", e.detail);
})

Here we've added a userLogin event, just as easily as we could add a native mouseover or focus event -- that's not special. The special part is creating and triggering the event:

// First create the event
var myEvent = new CustomEvent("userLogin", {
	detail: {
		username: "davidwalsh"
	}
});

// Trigger it!
myElement.dispatchEvent(myEvent);

The CustomEvent constructor allows for creation of the custom event, allowing you to pass both a custom event name as well as a number of special properties; dispatchEvent triggers the event on the given element. Let's make the event to be triggered super-customized by configuring its bubbling, cancelable, detail properties:

var myEvent = new CustomEvent("userLogin", {
	detail: {
		username: "davidwalsh"
	},
	bubbles: true,
	cancelable: false
});

Creating and trigger custom events with custom data is incredibly useful. Not only can you create your own naming convention for events, but you may also pass custom data along the way! You can keep up with browser support on the CustomEvent API on MDN, but this API is available in most modern browsers.

Recent Features

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

Incredible Demos

  • By
    MooTools FontChecker Plugin

    There's a very interesting piece of code on Google Code called FontAvailable which does a jQuery-based JavaScript check on a string to check whether or not your system has a specific font based upon its output width. I've ported this functionality to MooTools. The MooTools...

  • By
    Detect Vendor Prefix with JavaScript

    Regardless of our position on vendor prefixes, we have to live with them and occasionally use them to make things work.  These prefixes can be used in two formats:  the CSS format (-moz-, as in -moz-element) and the JS format (navigator.mozApps).  The awesome X-Tag project has...

Discussion

  1. This looks really good, it resembles by 99% the way Actionscript3 handles events and custom events, and I have to say it is really useful to be able to dispatch custom events with or without custom data.

    Thanks.

  2. Manu

    Good article David ! Some framework propose an implementation. Dojo use dojo/on to expose CustomEvent.

  3. Nice way to show the concept of Custom Event, it is deeply explanatory and helpful. Thanks David.

  4. Nice post, It looks very straight forward. Can you have sub events or events that trigger other events?

  5. Georgiy

    That’s great, but how to remove listeners for such events?
    Traditional way, i.e. el.removeEventListener('userLogin', callback) doesn’t work =(

  6. Georgiy

    UPDATE to previous comment: my fault, removeEventListener works, I just tried remove all of the callbacks, not a single one, but that’s another story.

  7. Humberto

    I’d been reading about CustomEvent interface, but when is it useful, seeing that I need to dispatch it manually?

  8. Ram

    Nice post…

    Looks like IE 10 onwards there is no support for CustomEvent constructor…

    https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent?redirectlocale=en-US&redirectslug=Web%2FAPI%2FEvent%2FCustomEvent

  9. Hank

    If you are allowed to use JQuery for your projects, one simple Trigger takes care of it all! Across all browsers too!

  10. Diego

    Sorry, but i don’t understand the concept, who is firing the event?. u attached the event to an specific node with the dispatchEvent but it does not trigger the event handler.
    How can I really trigger the code inside the handler?

    • @Diego you would call the myElement.dispatchEvent(myEvent); from within your own JavaScript code whereever you want your event to fire. FOr example if you are building a Slider/Slideshow then you could have a custom event that is triggered when you slide to a new slide

  11. Mani Kiran

    Thanks for the article.

    Quick question:
    if we want to dispatch the event multiple times with different data then how can we
    d that?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!