js999
js999

Reputation: 2083

How to create a new Event

I would like to create new events (using document.createEvent() or Jquery.Event + copying all important attributes) and send the clone to avoid modifying the original event.
Here is the source code http://jsfiddle.net/uymYJ/20/

This question is related to this one How to avoid to modify the event object in this situation

Any ideas why when I type a key on my keyboard I get for newEvent.keyCode undefined value?

$("#box").keydown(function(event){

    var newEvent = $.Event("keydown");

    console.log(event.keyCode); // 68 
    console.log(newEvent.keyCode); // undefined
});

Upvotes: 2

Views: 2269

Answers (2)

Alnitak
Alnitak

Reputation: 339856

From the jQuery API manual:

As of jQuery 1.6, you can also pass an object to jQuery.Event() and its properties will be set on the newly created Event object.

So you could try var newEvent = $.Event('keydown', event), but as far as I know that will only create a shallow copy of the original event object.

Alternatively just copy the properties you need:

var newEvent = $.Event("keydown", {
    keyCode:  event.keyCode
});

Unless you do that, your event object will have no useful properties on it at all.

Upvotes: 2

MrFischer
MrFischer

Reputation: 117

http://jsfiddle.net/uymYJ/21/

var e = $.Event('keydown', en);

this does the effect you (really?) want ;)

Upvotes: 1

Related Questions