Tracking a keyCode can be very helpful if you would like to give your visitors a user friendly experience. For instance, if there is an overlay open on a page, I usually press the ESC (Escape) button to close the overlay and most of the sites nowadays respond to it and close the overlay. It wouldn’t work without the keyCode being tracked. We do not have events like “onEscKeyPressed”, “onEnterKeyPressed” etc , so the only way to handle this type of functionality is by tracking the keyCode of the key pressed.

KeyCode is the Unicode value of a character key pressed.

How to identify the keyCode / the key pressed using jQuery ?

You can use jQuery’s event.which to identify the key pressed. It basically normalizes the event.keyCode and the event.charCode for keyboard key input. Hence it would be advisable to use event.which unless you really want to use event.keyCode. Let’s look at few examples to understand the use of event.which .

How to close an overlay on Esc / Escape key press?

The KeyCode for the Esc or Escape key is 27. You can find out the keyCode of a key by putting an alert on your page or by using this tool. The following example hides a div with ID “overlay” when the ESC key is pressed.

Similarly we can use the keyCode to limit the type of characters allowed inside a particular field. For instance, let’s say that we have an input field that should contain only numbers and we don’t want the user to enter anything inside the field other than integers/numbers. In such a scenario we can use the event.which API to detect the keyCode and restrict the input.

How to restrict keyboard character input to digits?

The following example restricts the keyboard character input to digits.

Identifying the key pressed using keyCode / character Code is helpful and it also improves the user experience for the end user. You can do a lot of creative stuff by detecting the key pressed.

Happy Coding !