-2

I have a game I made with HTML5, CSS, and JavaScript. I have HTML image tags of joystick arrows. I would like users to be able to click my joystick arrow images with the mouse and have it work as if the arrows on the keyboard were pressed. How do I make keyCode 39 fire when the image of the right arrow is clicked? I wrote the code like this but it doesn't work:

var $rt_arrow = $('.rt_arrow') 

$rt_arrow.on('click' , function (e) {
    e.keyCode == 39 
}) 
Sudipta Mondal
  • 2,550
  • 1
  • 19
  • 20
  • 1
    Possible duplicate of [trigger a keypress on click event](https://stackoverflow.com/questions/12297912/trigger-a-keypress-on-click-event) – Mukyuu Dec 17 '18 at 07:11
  • 1
    Possible duplicate of [Is it possible to simulate key press events programmatically?](https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically) – But those new buttons though.. Dec 17 '18 at 07:11
  • 2
    [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Instead, make a function `goRight`, and call it on both `keyDown` and `mouseDown`. There is no reason for a mouse click to trigger a key event. – Amadan Dec 17 '18 at 07:19

2 Answers2

1

You are facing an XY problem.

You don't want to trigger a keyboard event in this case, you just want your mouse event to trigger the same action as your keyboard event.

That is make you code more modular and create functions for each actions, then you can make your handlers call the required function:

onkeydown = e => {
  if(e.key === 'ArrowLeft') goLeft();
  else if(e.key === 'ArrowRight') goRight();
  // ...
};
onclick = e => {
  if(e.target === left_arrow) goLeft();
  else if(e.target === right_arrow) goRight();
  // ...
};
Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

I believe this is what you're looking for http://www.port135.com/2017/12/24/how-to-simulate-keyboard-key-press-in-javascript-using-jquery/

I haven't tested this so I'm not 100% sure, though it seems pretty straight-forward.

So instead of:

    e.keyCode == 39

Put:

    jQuery.event.trigger({ type: 'keydown', which: 39 });
victorsh
  • 19
  • 1
  • 2
  • 8
  • Instead of putting something that haven't been tested yet and might be misleading, please test it yourself first – Andreas Dec 17 '18 at 07:19