Search code examples
jqueryhtmlkeypress

Simulate keypress using jQuery


I want to simulate an keypress with jQuery.

I already tried this:

$("#canvas").trigger( jQuery.Event( 'keypress', { keyCode: 87, which: 87 }) );

But nothing's happening.

Full code:

$(document).on('keydown', function(e) {

    if(e.keyCode == 49) {

        $("#canvas").trigger( jQuery.Event( 'keypress', { keyCode: 87, which: 87 }) );

    }

});

What am i doing wrong?


Solution

  • you can try this one:

    You can create an Event object

    $('#canvas').trigger(jQuery.Event('keypress', {keyCode: 87, which: 13}));
    

    You maybe have to try which parameter to set, e.g. keyCode.

    or

    The real answer has to include keyCode:

    var e = jQuery.Event("keydown");
    e.which = 50; // # Some key code value
    e.keyCode = 50
    $("input").trigger(e);
    

    Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.

    or

    jQuery has a .keypress method accepting no arguments that simulates a keypress.

    $("#canvas").keypress();
    

    Will trigger a keypress on #canvas

    If you'd like to also select which key was pressed, you can use .trigger. This example is from the Docs.

    var e = $.Event("keydown", { keyCode: 87}); //"keydown" if that's what you're doing
    $("body").trigger(e);
    

    The key code 87 is the Key code backspace in javascript

    Let me know how that works for you :)

    My demo pages:

    DEMO 1

    DEMO 2