JavaScript
Article

Find the Keycode of Keyboard Key Pressed

By 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:

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.