17

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.

2 Answers 2

25

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"
Sign up to request clarification or add additional context in comments.

2 Comments

So easy that it hurts! Thanks alot :)
Event.initEvent is depreciated. see: developer.mozilla.org/en-US/docs/Web/Guide/Events/…
8

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

1 Comment

Similar answer but +1 since this was posted a minute earlier than the above answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.