4

With jQuery, I would like to trigger a keypress event where the event is handled by another version of jQuery.

jQuery2 = jQuery.noConflict(true);
$(function(){
    $("#fff").keypress(function(event) { 
        if (event.which == 13) { alert('jQuery'); } 
    });
    jQuery2('#fff').trigger(jQuery2.Event("keypress",{keyCode:13, which:13}));

});

Note that the handler is defined with $ while the event is triggered with jQuery2.

Here is a demo: jsfiddle. The handler code doesn't run!

Please help!

viebel
  • 19,372
  • 10
  • 49
  • 83

2 Answers2

3

jQuery's .trigger function only traverses event handlers that were registered with jQuery.

Instead, use Native DOM event creation and triggering functions - your event should then be caught regardless of which jQuery instance registered it:

var ev = new Event('keypress');
ev.keycode = 13;
ev.which = 13;

document.getElementById('fff').dispatchEvent(ev);

See http://jsfiddle.net/alnitak/b9mCL/

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

My guess is since $ and jQuery2 are two different wrappers, the objects they select are different, too. That is why event does not get triggered. You can cache the selected object in a variable and then raise events:

    var $input = $("#fff");
    $input.keypress(function (event) {
        if (event.which == 13) {
            alert('jQuery');
        }
    });
    $input.trigger(jQuery2.Event("keypress", {
        keyCode: 13,
        which: 13
    }));

Fiddle demo

Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57