Is there a JavaScript way to pass custom data to a manually created JavaScript event?
Ok, let's say I got this code to create and trigger a JavaScript event:
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent('submit', bubbling, cancelable);
anElement.dispatchEvent(evObj);
This works fine and can be handled by using this code:
document.addEventListener('submit', mySubmitEventHandler, true);
But, I need a way to pass additional data to the event, so that mySubmitEventHandler
knows whether the event was fired by a user or by JavaScript event creation as shown above. A boolean value would be sufficient.
So, how can I add something like "myEvent = true" to the newly created evObj
?
And please no jQuery answers, I need to do this one in pure JavaScript.
A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.
Adding custom data – CustomEvent()To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows: const event = new CustomEvent('build', { detail: elem.
Attach the parameter to evObj
.
evObj.flag = 'Hi!';
anElement.dispatchEvent(evObj);
This code demonstrates that the event object passed by dispatchEvent
is equal to the one in the event listener (Live demo):
var evObj = document.createEvent('HTMLEvents');
document.body.addEventListener('test', function(e){ alert(e === evObj); },true);
evObj.initEvent('test', true, true);
document.body.dispatchEvent(evObj); // Shows alert, "true"
your evObj it's a normal object you can add any data as a property of the object like evObj.myData = "blablabla"; and then read the data in the listener
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With