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

Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
Lists
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
Quotations
> Quoted text
Code blocks
```
// A simple code block
```
```php
// Some PHP code
phpinfo();
```
Links
[Link text](https://example.com)
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!