How to Handle Keyboard Events in jQuery

JohnJohn John (304)
Nov 19, 2020
3 minutes

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

Posted in these interests:
h/javascript27 guides
h/code69 guides
h/jquery2 guides

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: