Find the Keycode of Keyboard Key Pressed

Sometimes it’s useful to quickly find out the keycode for keyboard character especially when your coding keyboard events in jQuery or JavaScript. This code snippet provides you with an easy way to capture the current key press and key code for use with “keypress”, “keydown” and “keyup” events.


I’ve loaded this script into this page so simply press any keyboard key now to display it’s code.

The Code


	/* get key code */
	function getKeyCode(key)
		//return the key code
		return (key == null) ? event.keyCode : key.keyCode;
	/* get key character */
	function getKey(key)
		//return the key
		return String.fromCharCode(getKeyCode(key)).toLowerCase();

		$(document).keydown(function (eventObj)
			/* display the key and character code for the key you pressed */
			alert("Key pressed: "+getKey(eventObj)+ " Code = "+getKeyCode(eventObj));

If I get time i’ll code something to capture codes for mutiple key presses.

Related posts: