Skip to content
Advertisement

Listen to a specific data attribute in events

I need to listen to a message event that will have a data attribute and depending on this attribute do different actions.

JavaScript

Now, I want to test this with a button by dispatching such an event. However, I can only find the detail attribute, but not how to set the data attribute:

JavaScript

and

JavaScript

How can I send with the data attribute instead of the detail attribute?

Advertisement

Answer

If you’re testing a message event, you probably want MessageEvent rather than CustomEvent. MessageEvent‘s constructor accepts an “init” object with a data property:

JavaScript

Example:

JavaScript
JavaScript

But if you want to use CustomEvent, you’d create the event object, then add the property to it:

JavaScript

Example:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement