Can we add virtual keys to a snake game website, like that website we can only play on the laptop because the phone doesn't have arrow up, arrow down, etc keys. So I am asking can we add virtual keys to this website -> https://prashoon123.github.io/SnakeGame/ with the help of javascript?
Asked
Active
Viewed 358 times
-1
-
so, HTML buttons perhaps? yes, HTML does have button elements – Jaromanda X Aug 31 '20 at 05:42
-
This seems like a yes/no question (the answer is yes BTW), you might want to check out how do I ask a good question: https://stackoverflow.com/help/how-to-ask – zhon Aug 31 '20 at 06:14
1 Answers
1
Hi and welcome to Stackoverflow.
Yes you can add virtual keys, and then trigger the event types, that would normally be sent by your computer, manually.
Check the keycode data here: https://keycode.info/
and to dispatch the event:
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
And you need to use the <element>.addEventListener
to listen for det keydowns.
Keydown documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
--
If the idea is to support mobile browsers, you can instead use the touchstart
and touchend
events.
Based on the start and end values (x,y positions) - you can calculate if the user swiped in any direction.
https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event

Christer
- 1,651
- 1
- 17
- 34
-
1You might want to check https://keyjs.dev, which includes some explanations of things like Alt Codes and virtual/mobile keyboards and will soon include information about cross-browser inconsistencies! – Danziger Oct 05 '20 at 23:21