Knowledge for the World

How to handle keyboard events in jQuery

If you've never handled keyboard events in jQuery this is a good place to start.

1

The main keyboard events you need to understand are keydown, keypress, and keyup. In order to handle these events, you must understand what they are and when they'll be triggered.

keydown

The keydown event is triggered as soon as a user presses a key down. This event doesn't require the user to finish the keypress in order to be triggered. In fact, in many cases, if the user holds down the key, the keydown event will be triggered continuously.

To test out keydown event you can use this code:

$(function(){
    $(document).on('keydown', function(){
        console.log('keydown');
    });
});

keypress

Keypress is very much like the keydown event, except it isn't triggered for modifier keys like 'shift', 'esc', and 'delete'. Furthermore, the behavior of the keypress event will vary across different browsers and platforms. However, in many cases, the keypress event will behave like the keydown event and will be fired as soon as the key is pressed.

To test out keypress event you can use this code:

$(function(){
    $(document).on('keypress', function(){
        console.log('keypress');
    });
});

keyup

The keyup event, as you would imagine, is triggered when the user releases a key. It is only triggered once per keypress. So if the user holds down a key, the keydown and keypress events may be fired multiple times, but the keyup event will only be triggered once after they've released the key.

To test out keyup event you can use this code:

$(function(){
    $(document).on('keyup', function(){
        console.log('keyup');
    });
});

In the above examples, the events were attached to the document, but in reality you'd probably want to attach them to a more specific DOM object. For example, if I have the following textarea:

<textarea id="message"></dv>

.. and I wanted to display a warning if the length of the textarea is greater than 100, I could do this:

$(function(){
    $("#message").on('keyup', function(){
        if ($(this).val().length > 100) {
            displayWarning();
        }
    });
});

You should become familiar with the default behavior of each of these events. You can do some initial testing without any code. Simply put your cursor inside of a textarea or text input and press down a key without lifting it up. You'll see that the key is added on the keydown event. With this in mind, if you wanted to override the default behavior of a key you'd probably want to listen for the keydown event.

And in the case of our example above, if you wanted to do some calculation on the textarea after the key has been added, you'd want to use the keyup event. Otherwise, your calculation will always be one character off.

2

When your dealing with keyboard events you'll often want to know which key was pressed. The callback function for an event listener takes the event, e, as the first parameter.

$(function(){
    $(document).on('keypress', function(e){
        console.log(e);
    });
});

The event object contains many properties, but they can be inconsistent across different browsers. For a keyboard event, the event object lets you know which key was pressed, but as you might guess this isn't the same across every browser.

There are actually a few options you can use to get the key code (depending on browser): e.which, e.keyCode, and e.charCode.

Fortunately, jQuery has normalized this across all browsers. So with jQuery you can always rely on e.which. Check out the docs for e.which.

3

Since we know to use e.which, here are a few examples of how you can handle keyboard events for different keys.

Log all key codes

$(function(){
    $(document).on('keypress', function(e){
        console.log(e.which);
    });
});

Listen for the enter key

$(function(){
    $(document).on('keypress', function(e){
        if (e.which == 13) {
            console.log("Enter pressed!");
        }
    });
});

Listen for ctrl + p

$(function(){
    $(document).on('keypress', function(e){
        if (e.which == 80 && e.ctrlKey) {
            console.log("ctrl + p pressed");
        }
    });
});

Listen for multiple keys

$(function(){
    $(document).on('keypress', function(e){
        switch (e.which) {
            case 8:
                console.log('backspace pressed');
                break;
            case 9:
                console.log('tab pressed');
                break;
            case 16:
                console.log('shift pressed');
                break;
        }
    });
});