darkcode
darkcode

Reputation: 938

Canvas - addEventListener not working simulating keypress

I have the below addEventListener in one canvas game to control the keyboard events:

document.addEventListener("keydown", keyDown, true);
document.addEventListener("keypress", keyPress, true); 

And the below jQuery code that simulate the keypress event to start the game.

$("#new").click(function(event) {
  event.preventDefault(); // Stop the link click from doing anything.
  var ev = jQuery.Event("keypress"); // Build an event to simulate keypress.
  ev.which = 78; // Keycode for 'N' is 68
  ev.ctrlKey = false; // Control key is down.
  $(this).trigger(ev); // Fire!
});

If I press 'N' with my keyboard the canvas game is starting correctly, but when I click the #new div nothing happens.

My canvas element:

<canvas width="500px" height="480px" tabindex="1" id="game"></canvas>

Upvotes: 0

Views: 936

Answers (1)

Robin
Robin

Reputation: 7894

jQuery .trigger only runs events bound using jQuery, not addEventListener.

You need to use

$(document).bind('keydown',function(){

or

$(document).keydown(function(){

to be able to use jQuery trigger. All or nothing jQuery.

Alternatively, you could use native dispatchEvent, but that's complicated, messy and not jQuery.

Upvotes: 1

Related Questions