Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone a DOM event object to re-dispatch

Some browsers won't allow you to re-dispatch an event that has already been dispatched, but allow you to create new event objects based on values that can be obtained from the existing event object.

Is there a generic and reusable solution that will work with any event type, or failing that, a way to do this for a specific event type (in my case I'm currently concerned with the mousewheel event)?

like image 605
devios1 Avatar asked Oct 05 '12 19:10

devios1


People also ask

How do you clone an event?

To clone an eventFrom Define an event window, select the event you want to clone. Click Clone to open the Event Clone window. Enter a new event code for the cloned event. Click Save.

Which property of Dom dispatched an event?

target property is initialized to the current EventTarget . Unlike "native" events, which are fired by the browser and invoke event handlers asynchronously via the event loop, dispatchEvent() invokes event handlers synchronously. All applicable event handlers are called and return before dispatchEvent() returns.

What are Dispatch events?

To dispatch an event means to "fire" it. The handlers listening to that event will be called.


2 Answers

It seems there is now an even better solution, since initMouseEvent and the like are deprecated. The MouseEvent() constructor, for example, takes a table of properties as its 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 classes of events have similar constructors that should be usable in the same way. Such as ClipboardEvent().

jsfiddle example

like image 105
Cauterite Avatar answered Sep 19 '22 03:09

Cauterite


I found my own answer, at least for MouseEvents specifically:

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;
}

You can then dispatch the event on a target with:

target.dispatchEvent( evt );
like image 20
devios1 Avatar answered Sep 17 '22 03:09

devios1