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?
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:
const newEvent = new MouseEvent(oldEvent.type, oldEvent)
If you want more than just mouse events, you could do something like this:
const newEvent = new oldEvent.constructor(oldEvent.type, oldEvent)
And in the original context:
function handler(e) {
const copied = new e.constructor(e.type, e);
document.getElementById("decoy").dispatchEvent(copied);
}
document.getElementById("source").addEventListener("click", handler);
(For jQuery users: you may need to use e.originalEvent.constructor instead of e.constructor)