What's the best way to clone a JavaScript event object so that it can be resent?

Some browsers will not allow you to resubmit an event that has already been sent, but allow you to create new event objects based on values ​​that can be retrieved from an existing event object.

Is there a general and reusable solution that will work with any type of event or, if it is not, a way to do it for a specific type of event (in my case, I am currently associated with the mousewheel event)?

+7
source share
3 answers

I found my own answer, at least for MouseEvents:

 function cloneMouseEvent( e ) { var evt = document.createEvent( "MouseEvent" ); evt.initMouseEvent( e.type, e.canBubble, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget ); return evt; } 

Then you can send the event to the target with:

 target.dispatchEvent( evt ); 
+4
source

There seems to be an even better solution now, since initMouseEvent and the like are deprecated. The MouseEvent () constructor, for example, takes a property table as the second parameter, for which you can use an existing MouseEvent object:

 let my_event = new MouseEvent(`foo`, some_existing_mouse_event); dispatchEvent(my_event); 

Other event classes have similar constructors that should be used the same way. For example ClipboardEvent () .

Jsfiddle example

+4
source

You might want to use the (poorly documented) NWEvents library

 NW.Event.dispatch(target, e.type, false, e); 

It works with any event, as well as in old IE.

+1
source

All Articles