0
$(document).keypress(function(e) {
    if(e.which == 32) {
        alert('You pressed spacebar!');
    }
});

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

$(document).keypress(function(e) {
    if(e.which == 40) {
        alert('You pressed down arrow!');
    }
});

Here's my javascript file. There is no CSS and the HTML is just a blank skeleton.

It reads the enter and spacebar just fine, but the down arrow, up arrow, or pretty much any key I press that isn't enter or spacebar does not register?

How would one solve this problem?

Any help is appreciated.

R. Little
  • 13
  • 4

1 Answers1

2

Arrow keys don't generate a keypress event. They generate keydown and keyup events.

Note that while letters keys do generate keypress, the which value may not be the value you expect. On my browser and operating system, for instance, pressing the a key generates which = 65, which is the character code for A, not a. Key codes are key codes, not character codes. More on this no-longer-maintained, but still quite useful, page.

Live Example: (I added a return false to prevent default handling, since otherwise the Stack Snippet window tends to scroll around, but that isn't necessary to receive the event)

$(document).keypress(function(e) {
    if(e.which == 32) {
        display('You pressed spacebar!');
        return false;
    }
});

$(document).keypress(function(e) {
    if(e.which == 13) {
        display('You pressed enter!');
        return false;
    }
});

$(document).keydown(function(e) {
    if(e.which == 40) {
        display('You pressed down arrow!');
        return false;
    }
});

function display(msg) {
  $("<p>").text(msg).appendTo(document.body);
}
p {
  margin: 0;
}
<p>Click this pane to focus it, then press spacebar, Enter, or down-arrow</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Would that also be the case for letter keys? – R. Little Dec 07 '15 at 15:47
  • @R.Little: No, letter keys generate `keypress`. Note, though, the `which` value may not be the value you're expecting for the character. Remember keycodes are *key* codes, not character codes. More on [this no-longer-maintained, but still quite useful, page](http://unixpapa.com/js/key.html). – T.J. Crowder Dec 07 '15 at 15:50
  • http://stackoverflow.com/questions/5597060/detecting-arrow-key-presses-in-javascript – CoderPi Dec 07 '15 at 15:51
  • 1
    Rather embarrassing the answer was this simple. I'll give you the green checkmark thingy when it lets me... in about 7 minutes – R. Little Dec 07 '15 at 15:52