0

I am trying to use vanilla javascript to dispatch a custom event. Along with the event, I would like to pass a custom object.

Here is what I have done

document.addEventListener('abcAppended', function (e) {
     console.log(e.el); // write the custom object to the console
});

var wrapper = document.getElementById('abc');
if (wrapper) {
    // do something with wrapper
   
    document.dispatchEvent(new CustomEvent('abcAppended', {
        el: wrapper // I tried to add custom object here
    }));
}

But the above write undefined to the console. How can I correctly pass an object and access it using a listener.

Jay
  • 1,168
  • 13
  • 41
  • You should review [documentation for the `CustomEvent` constructor](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent). What you pass to the constructor as the second object is not what is returned as the event object in the listener. – Heretic Monkey Feb 07 '22 at 21:37
  • 2
    I think you need to pass `detail` into the options object. Try using `detail: wrapper`? – evolutionxbox Feb 07 '22 at 21:39
  • A note for older browsers, and older versions of jQuery: [Javascript CustomEvent detail not getting passed](https://stackoverflow.com/q/13333683/215552) – Heretic Monkey Feb 07 '22 at 21:48
  • Does this answer your question? [Firing and capturing custom events](https://stackoverflow.com/questions/7057223/firing-and-capturing-custom-events) – Heretic Monkey Feb 07 '22 at 21:49
  • @evolutionxbox thank you. `detail` worked! – Jay Feb 07 '22 at 21:55

0 Answers0