0

I am trying to stay clear of jQuery and want to detect if the left or right key is pressed. I am having trouble just getting this to work.

var keyPress = function(event) {
  var keyCode = event.keyCode;
  if (keyCode == 37)
    //do something
  if (keyCode == 39)
    //do something
}
document.onkeydown = keyPress(event);

The problem I am having is that I just cannot detect any keyboard events.

Any help would be greatly appreciated.

2
  • have u checked if firebug is throwing any error ? Commented Jun 27, 2013 at 14:10
  • If you don't have jQuery or another library to normalise it for you you might want to say something like var keyCode = event.keyCode || event.which; (and possibly if (!event) event = window.event). Commented Jun 27, 2013 at 14:16

1 Answer 1

6

You need to pass the function reference to onkeydown

document.onkeydown = keyPress;

what you are doing to calling the function keyPress and passing the value returned by it as the onkeydown handler, in this case undefined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.