0

Is there a way to pass data to an event handler using either EventTarget.dispatchEvent() or HTMLElement.click()?

http://jsfiddle.net/yq7yqpL8/1/

var button = document.getElementById('button');

button.addEventListener('foobar', function() {
    console.log(arguments); // [Event]
});

button.addEventListener('click', function() {
    console.log(arguments); // [MouseEvent]
});

button.click({ foo: 'bar' });

var event = document.createEvent('HTMLEvents');
event.initEvent('foobar', true, false);
button.dispatchEvent(event, { foo: 'bar' });
cantera
  • 24,479
  • 25
  • 95
  • 138

2 Answers2

3

I think what you are looking for are custom Events, that can attach custom parameters like so:

//Listen for the event
window.addEventListener("foobar", function(evt) {
    alert(evt.detail);
}, false);

//Dispatch an event
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("foobar", true, true, "Object");
window.dispatchEvent(evt);

Read along here

Community
  • 1
  • 1
Colonize.bat
  • 188
  • 1
  • 11
  • 1
    Thanks for responding; confirming this works for the `foobar` event: http://jsfiddle.net/yq7yqpL8/3/. Is there a way to pass data for native UI Events, such as click? – cantera Jun 03 '15 at 14:37
  • Maybe [this](http://stackoverflow.com/questions/3273350/jquery-click-pass-parameters-to-user-function) will help you in that case. Please mark the answer as solved if it helped you. – Colonize.bat Jun 03 '15 at 16:32
-3

This should answer your qestion using jquery:

button.bind('click', { name: 'something' }, function(event) {
    alert(event.data.name);
});

See also: http://api.jquery.com/event.data/

user3072843
  • 308
  • 3
  • 13