Search code examples
javascriptjquerykeypress

Keypress not responding to character codes


$(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.


Solution

  • 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>