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.
Attach the parameter to
evObj.This code demonstrates that the event object passed by
dispatchEventis equal to the one in the event listener (Live demo):