How to clone or re-dispatch DOM events?

Razvan Caliman picture Razvan Caliman · Aug 15, 2012 · Viewed 21.5k times · Source

I'm looking for a simple and abstract way of cloning or re-dispatching DOM events only. I am not interested in cloning DOM nodes.

I've experimented a bit, read the DOM Events specification and I found no clear answer.

Ideally, I'm looking for something as straight-forward as:

handler = function(e){
  document.getElementById("decoy").dispatchEvent(e)
}
document.getElementById("source").addEventListener("click", handler)

This code example, of course, does not work. There's a DOM exception stating that the event is currently being dispatched - obviously.

I'd like to avoid manually creating new events with document.createEvent(), initializing them and dispatching them.

Is there a simple solution to this use case?

Answer

Alexis picture Alexis · Dec 12, 2013

I know, the question is old, and the OP wanted to avoid creating / initializing approach, but there's a relatively straightforward way to duplicate events:

new_event = new MouseEvent(old_event.type, old_event)

If you want more than just mouse events, you could do something like this:

new_event = new old_event.constructor(old_event.type, old_event)

And in the original context:

handler = function(e) {
  new_e = new e.constructor(e.type, e);
  document.getElementById("decoy").dispatchEvent(new_e);
}
document.getElementById("source").addEventListener("click", handler);

(For jQuery users: you may need to use e.originalEvent.constructor instead of e.constructor)