Select theme

Custom Events in JavaScript

Published by on

Today I learned that you can very easily trigger custom events in JavaScript. This only works in the DOM, but it is very practical, for example to exchange data between scripts that are unrelated to each other.

In the event.detail object you can send any data.

const event = new CustomEvent("my-custom-event", {
  detail: { data: { hello: "world" } },
});

document.dispatchEvent(event);

// Elsewhere in the code, or maybe even in a separate script:

document.addEventListener("my-custom-event", (event) => {
  console.log("a thing happened", event.detail);
});

A simple demo (with a more or less practical example):

JavaScript Custom Event Example