paul smith paul smith - 7 months ago 44
Javascript Question

cloning an event object in javascript/jquery

How can I create a completely separate and new event object that contains all of the same exact properties as a given event object e. So far I've tried the following but no luck:

function myHandler(e) {
// ...

e = e.originalEvent;

// method 1
var e2 = jQuery.extend(true, {}, e);

// method 2
var e2 = JSON.parse(JSON.stringify(e));

// ...
}


EDIT: I will add more details to help clarify. Very similar to this question I am trying to do: div.dispatchEvent(e.originalEvent), but doing so results in:

DISPATCH_REQUEST_ERR: DISPATCH_REQUEST_ERR: DOM Events Exception 1


so in order to avoid this, I need to duplicate the event object. However, this event object isn't a specific one (i.e., sometimes the e is a touchstart, touchmove, or touchend) and therefore it'd be easier if I could get a general cloning function instead of just hardcoding the specific properties. What I meant by "no luck" was that by trying the aforementioned methods and sending that thru the dispatch function I was getting errors. Hope this helps clarify a bit.

Joe Joe
Answer

I've had "good luck" with this code:

$.extend($.Event(event.type /* click, mousedown, touchstart, ect. ect. */), {
    which: 1,
    clientX: event.clientX,
    clientY: event.clientY,
    pageX: event.pageX,
    pageY: event.pageY,
    screenX: event.screenX,
    screenY: event.screenY
});

Obviously, this is everything; but you can add what you actually need in the other object. I create a new event here, because I'm actually forwarding an event to another element.


Update:

I use jQuery Touch Punch Plugin which basically maps click/mouse events to the associated touch event: touchstart, touchesmoved, touchend. So if you forward this event as the mouse event:

var newEvent = $.extend($.Event(event.type), {
    which: 1,
    clientX: event.clientX,
    clientY: event.clientY,
    pageX: event.pageX,
    pageY: event.pageY,
    screenX: event.screenX,
    screenY: event.screenY
});

// touch punch will convert to a touch event if needed
$('.some-other-element').trigger(newEvent); 

You simply need to include the touch punch script on your page. This will also allow jQuery UI elements to function on touch devices.

references:

Comments