Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there an accepted method for capturing player input in HTML5 games? I have seen several methods, and the browsers seem to be in varying states of implementation; On MDN they tell you not to use both the newer and older implementations. I'm open to methods utilizing various libraries, but I would also like to see a pure JavaScript and DOM version as well.

share|improve this question

What "several methods" have you seen? AFAIK, there's one method, which involves listening for the appropriate DOM Level 2/3 events like keydown via the addEventListener function. There might be some inconsistencies with the way you retrieve key codes, which you can deal with by using var keyCode = event.keyCode || event.which. There are also some inconsistencies with mouse button numbers, only the higher ones though. That's about it.

The only reason why, i see, you could be confused is if you were looking at old IE APIs. You want HTML5, so that's IE9+ and those browsers conform to the standards i described above.

For the keyboard events, you can probably just listen to the document object, though this depends on how you serve your game. For mouse events, you can listen to the canvas object directly.

share|improve this answer

As @dreta said there's only one way and it's by using a keypress event handler just like this:

var keyInput = document.getElementById("keyInput");

function inputFunc(e) {
    If (e.keyCode == 82) {// 82 = R
        //Do Something
keyInput.addEventListener("keypress", inputFunc);

You can also visit this website where you can check the keyCode char keyCode char

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.