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:

Tags: jquery keyboard shortcuts
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.