Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether browser has keyboard/arrow keys in web page

Tags:

I have a full-screen game in HTML+JavaScript, which uses the arrow keys as primary controls. This cannot be used on keyboardless Android devices (I haven't tested on iOS), and even if the soft keyboard had arrow keys it would take up unnecessary space. Therefore, I have added onscreen control buttons. However, the buttons are unnecessary (and absurdly large) on desktop browsers, so I would like them to not pop up unless they are needed.

What heuristics can I use to decide whether they are needed — that is, whether it is impossible or awkward for the user to input arrow-key events — other than recognizing specific User-Agents (which is straightforward, but not future-proof)?

I will of course allow the user to hide/show the buttons; I am looking for useful heuristics for choosing the default setting.

like image 373
Kevin Reid Avatar asked Jan 14 '11 21:01

Kevin Reid


People also ask

How do you tell which arrow key is which?

Alternatively referred to as cursor keys, direction keys, and navigation keys, the arrow keys are usually located between the standard section and the numeric pad on computer keyboards. It is made up of four keys: the left arrow (back arrow), up arrow, down arrow, and the right arrow (forward arrow).

How do I use arrow keys in JavaScript?

To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.


2 Answers

No need for any user-agent sniffing, config options or any kind of guessing. Just do this:

  1. Have a title screen which says "press to continue".
  2. On click or key press, hide touch controls and start game.
  3. On touch, show touch controls and start game.

You never even needed to mention the option to the user and you auto-detected their preferred control perfectly.

like image 129
AshleysBrain Avatar answered Oct 16 '22 23:10

AshleysBrain


Use feature detection with Modernizr: http://www.modernizr.com/docs/#touch

While this is not a reliable way to check if the user has a keyboard it is definitely reliable to see if the browser is capable of touch.

like image 24
Alex Lawrence Avatar answered Oct 17 '22 01:10

Alex Lawrence