5

Realy messed up with triggering keyup event using jQuery.

Here is the clean example

http://jsfiddle.net/xQcGM/2/

When I type in any of input's, they both fire event, but when I try to fire it programmatically ($(element).trigger('event')) only the second one is triggered, but I expect both.

Where do i miss something?

UPD I can't change the way handler was attached!

disfated
  • 10,633
  • 12
  • 39
  • 50

1 Answers1

6

The native way to trigger events is to call dispatchEvent. Unfortunately, this method does not appear anywhere in jQuery's source. So I am guessing you have to either create the event objects yourselves and dispatch them manually.

Here's a longer version with a working example.

$('button').click(function() {
        var myEvent = document.createEvent('KeyboardEvent');
        myEvent.initKeyboardEvent('keyup', true, true, null, false, 
                                false, false, false, 76, 0);
        $('input').each(function() {
            this.dispatchEvent(myEvent);
        });
    });

Or you could look at jQuery simulate plugin which makes it slightly easier. Here's a shorter version with another working example.

$('button').click(function() {
    $('input').simulate('keyup');
});
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • Thanks, that's clear now. It's not necessary, but may be I could somehow extend jQuery trigger functionality that it would do those fake `KeyboardEvent`s inside? – disfated Jun 18 '11 at 21:14
  • I haven't looked at the source of trigger, but replacing it with your own code is fairly `easy`. However, then you would have to deal with problems of normalizing a DOM event to a jQuery event to make sure all other event handling works normally, setting the right properties on that event object, and dealing with cross-browser issues. The solution is not as simple as creating a wrapper, which dispatches the DOM events directly and then calls jQuery's implementation as then the same event will be triggered twice in that case - once for all events on the element, and once for jQuery bound events – Anurag Jun 18 '11 at 22:02