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?
here is a test it works
you can try this one:
You can create an Event object
You maybe have to try which parameter to set, e.g.
keyCode.
or
The real answer has to include
keyCode:
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.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.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