Find the Keycode of Keyboard Key Pressed

Sam Deering

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.

Demo

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

The Code

(function($) 
{

	/* 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).ready(function()
	{
		$(document).keydown(function (eventObj)
		{
			/* display the key and character code for the key you pressed */
			alert("Key pressed: "+getKey(eventObj)+ " Code = "+getKeyCode(eventObj));
		});
	});
	
})(jQuery);

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

Related posts:

Win an Annual Membership to Learnable,

SitePoint's Learning Platform