JavaScript Code

Capturing Key Codes with JavaScript

Ever wonder how ThinkFree of Gmail are able to save your content when you hit 'Ctrl + s'? They are capturing the key combination, and using to it fire a client-side function. Here's a function you can adapt to use whichever keycode or combination to suit your purposes.

Note: in IE, when pressing the ctrl + shift + key, it gives the key code for the capitalized key (probably because shift is pressed). In Netscape. pressing ctrl, shift and another key doesn't change the keycode. If you need to determine what the keycode is for your combination, just un-comment the 'debug' line.

var captureKeys = function(ev) {
	ev = ev || window.event;             // gets the event in ie or ns
	kCode = ev.keyCode || ev.which;   // gets the keycode in ie or ns
	//alert(kCode); // debug

	if (ev.ctrlKey && ev.shiftKey && kCode == 19 || ev.ctrlKey && ev.shiftKey && kCode == 83) {	// ctrl+alt+s
                saveFunction() // or whatever you call your function
		return false;  // now make the browser ignore the key combo
	if (ev.ctrlKey && kCode == 119) { // ctrl+w
		closeWin();  // run your own script to close the window 
                                 // doesn't work in ie, ie just closes the window
		return false;

Then add this to your HTML:

<body onload="document.onkeypress=captureKeys;">


  1. Hey, thanks a lot for this good little script.

  2. How can I capture key events in the IE for windows mobile?

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image