How to detect keycode / key pressed in jquery

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.


			if(event.which == 27){


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.


       //KeyCode for digits 0-9 is 96 to 105 on the numeric pad.
       //KeyCode for digits 0-9 is 48 to 57 on the regular digit keys on a qwerty keyboard.
       //keyCode 8 is for backspace

	if((event.which >= 48 && event.which <= 57) || (event.which >= 96 && event.which <= 105) || (event.which == 8))
		return true;
		return false;


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!