Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery triggers keyup event only if it was attached with jQuery

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!

like image 267
disfated Avatar asked Jun 18 '11 20:06

disfated


1 Answers

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');
});
like image 189
Anurag Avatar answered Nov 07 '22 19:11

Anurag