Geekpedia Programming Tutorials






Get key press event using JavaScript

This tutorial will show you how to get the pressed key in the browser window, whether it's Ctrl, Alt, Shift, Page Up, Arrow Up or any other key. There's both an Internet Explorer and a Firefox way of doing this.

On Saturday, August 13th 2005 at 01:42 PM
By Andrei Pociu (View Profile)
*****   (Rated 4.5 with 71 votes)
Contextual Ads
More JavaScript Resources
Advertisement
There are several reasons why you may want to capture the key press event in a browser window. Perhaps you're making a JavaScript game, or a map similar to Google Maps and you want to allow navigation through the arrow keys. Getting the pressed key is easy in JavaScript, however different browsers use different ways for this. We will first see how this can be done using Internet Explorer, and then how we can make it work on both Internet Explorer and Firefox.

The Internet Explorer way


Thanks to onkeyup we can easily handle the key pressing event in Internet Explorer. Here is the script we need to capture some of the keys on the keyboard:





<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck()
{
var KeyID = event.keyCode;

switch(KeyID)
{
case 16:
document.Form1.KeyName.value = "Shift";
break;

case 17:
document.Form1.KeyName.value = "Ctrl";
break;

case 18:
document.Form1.KeyName.value = "Alt";
break;

case 19:
document.Form1.KeyName.value = "Pause";
break;


case 37:
document.Form1.KeyName.value = "Arrow Left";
break;


case 38:
document.Form1.KeyName.value = "Arrow Up";
break;


case 39:
document.Form1.KeyName.value = "Arrow Right";
break;

case 40:
document.Form1.KeyName.value = "Arrow Down";
break;
}
}
</script>



And the HTML to use with this is:





<form name="Form1">

<input type="text" name="KeyName" value="" />

</form>



See this code in action



We get the char code of the pressed key and we display its equivalent inside the TextBox. Note that when pressing the Alt key, the page loses focus and other elements on the browser window gain focus, and thus it might not always be catched as an event. Also, inside the JavaScript we catch only a small number of the keys on the keyboard, but that doesn't mean the rest of the keys can't be catched using the event. There is a list of the char codes and their equivalent key on the keyboard, so that you can catch the key you want.

Making it work in both Internet Explorer and Firefox


To make it work in both Internet and Firefox, we're going to use the same function - KeyCheck() - but with an argument this time (e). Also, we use an inline condition so that the appropriate method is used depending on the browser:





<script type="text/javascript">
document.onkeyup = KeyCheck;

function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;

switch(KeyID)
{
case 16:
document.Form1.KeyName.value = "Shift";
break;

case 17:
document.Form1.KeyName.value = "Ctrl";
break;

case 18:
document.Form1.KeyName.value = "Alt";
break;

case 19:
document.Form1.KeyName.value = "Pause";
break;


case 37:
document.Form1.KeyName.value = "Arrow Left";
break;


case 38:
document.Form1.KeyName.value = "Arrow Up";
break;


case 39:
document.Form1.KeyName.value = "Arrow Right";
break;

case 40:
document.Form1.KeyName.value = "Arrow Down";
break;
}
}
</script>






See this code in action
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by 323 on Friday, August 26th 2005 at 11:16 AM

3232

by Nabeel Akhtar on Tuesday, August 30th 2005 at 11:14 PM

this is great stuff man..thanks alot

-Nabeel
http://www.nabeelakhtar.net

by Puneet Sehgal on Wednesday, August 31st 2005 at 06:24 AM

Great article but would have been better if covered how to fire a server side event after catching the keypress.

by Danilo on Monday, November 7th 2005 at 11:01 AM

Excellent article, nice example, but there is a little problem, I tried the code in Opera 8 and the Arrow Down case didn't work out, for the rest of cases, works perfect

by Tapasya on Saturday, November 26th 2005 at 07:04 AM

Article is Fantastic, and helped me alot!!
Thx!

by Tapasya on Saturday, November 26th 2005 at 07:04 AM

Article is Fantastic, and helped me alot!!
Thx!

by Vijay Saraf on Tuesday, December 27th 2005 at 01:51 AM

Good enough and working !
Thanks.

by Peter on Monday, January 9th 2006 at 01:10 AM

very goood article. Can i make it like two key at a time. I mean ALT+T

by fadil on Friday, January 13th 2006 at 09:21 PM

Thanks bro..
This script is really helping me in windows but can u help me again cause i'm using mozilla firefox in linux fedora4 environment..The script doesn't working here..

by Richard on Sunday, February 26th 2006 at 11:59 AM

RE: Puneet Sehgal (Aug 31 2005 - 06:24: Great article but would have been better if covered how to fire a server side event after catching the keypress.) try;-

document.location="mydoc.htm?key=keyID";

by paul on Thursday, April 20th 2006 at 11:47 PM

for multi key try this

document.onkeydown = KeyCheck;
document.onkeyup = KeyMod;
var ctrlKey = false;
var altKey = false;
function KeyMod(e){
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 17:
ctrlKey = false;
break;
case 18:
altKey = false;
break;
}
}
function KeyCheck(e){
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 17:
ctrlKey = true;
break;
case 18:
altKey = true;
break;
case 46:
del();
break;
case 45:
add();
break;
case 83:
if(ctrlKey){
update();}
break;
}
}

by srinivas on Thursday, April 27th 2006 at 07:06 AM

hi sir,
i am getting problem in javascript . how to restrict the paste string in the textbox(for javascript code) .can u pls explain me.

by MoroS on Friday, May 5th 2006 at 09:31 AM

If you ever need a element level multi-browser key press check you can do the following:

function KeyPress(e, field)
{
var oEvent = window.event ? window.event : e;

//oEvent.keyCode checks go here
//the following example clears the input box when pressed
//the Tab key

if (oEvent.keyCode == 9)
field.value = '';
}

The HTML would look like this:
&lt;input type="text" name="test" onkeyup="KeyPress(event, field);"&gt;

The first parameter is important, because it's the keyboard event object for the current event. Happy coding.

by MoroS on Friday, May 5th 2006 at 09:34 AM

Well, didn't know that this site has HTML parsing in comments.
So once again, the HTML would look like this:

&lt;input type="text" name="test" onkeyup="KeyPress(event, field);"&gt;

Cheers. ;)

by Raju on Sunday, May 28th 2006 at 01:49 AM

Very Good Code, can you please suggest javascript code that can capture multi events such as ALT+LeftArrow.

by Pino on Monday, June 12th 2006 at 10:23 AM

How do I capture the default things like Backspace?
backspace has value 8 but case: 8 does noet work, it still goes back a page...

by sdfg on Wednesday, July 12th 2006 at 09:18 AM

sld




sdfsd
sdf
sdf
sdf

sdfs
sdf

by on Wednesday, August 23rd 2006 at 06:10 AM

sdadasd

by EVGENIA on Thursday, November 16th 2006 at 09:01 PM

that is excellent.but i am a beginner with java and i would like to know if i could use java and the press key event to control my flash movies.for instance by pressing the spacebar to stop and begin a flash movie.if someone has the answer i would be very happy if it could be posted here...many many thanks

by Nishant on Tuesday, December 5th 2006 at 05:41 AM

Good1

by on Wednesday, March 7th 2007 at 01:31 AM

by Chanchal Sharma on Monday, March 26th 2007 at 06:11 AM

Its very nice code
Thanks

by Bitcloud on Thursday, March 29th 2007 at 05:17 PM

Your example works great in IE, but does nothing in firefox

has anyone else seen this problem?

by grg on Sunday, April 22nd 2007 at 07:20 AM

Fools

by ghedfg on Wednesday, May 2nd 2007 at 08:31 AM

hdg

by xman on Wednesday, May 16th 2007 at 07:30 PM

How about a way to make this work.?
Javascript to send back Alt+Down Arrow for opening a dropdownlist with enter.

if (event.keycode==13)
{
event.altkey=true;
event.keycode=40;
}
Any Ideas / Help??

by IndDev on Tuesday, May 22nd 2007 at 09:52 AM

The article is great!!. But if you move the javascript code to a separate .js file and reference it, it does not work. This happens only in case of firefox. Let me know if you all find anything around this.

by on Tuesday, June 12th 2007 at 09:37 AM

4444444444444444444444444444444444444444

by on Thursday, June 21st 2007 at 10:23 AM

e

by Lingappa on Friday, August 17th 2007 at 09:28 AM

Very good and simple code. It works perfectly. I am using internet explorer,
How do I capture F1 (function key F1) key press to show my own help rather than internet explorer help? Thanking you in advance.

Regards,
Lingappa

by Siddanth on Friday, August 24th 2007 at 11:10 AM

Nice Article!!!! i need a code which could move a icon in the page somethin like a star * to move rit when it in keyboard we press arrow rit or left respectively....thks ...

by ganesh on Wednesday, August 29th 2007 at 01:56 AM

what about the BACK SPACE key, can you please add it also?

by cj on Friday, September 28th 2007 at 12:49 AM

Thanks.

by Danny CC on Monday, October 1st 2007 at 06:32 AM

Easy stuff - To all the people asking for the codes for other characters, use this script to output the keyID for various keys. Run the script, press the key you want the keyID for, and the alert will tell you the keycode, just create a new case for the keycode.

<script type="text/javascript">
document.onkeyup = KeyCheck;


function KeyCheck(e)

{


var KeyID = (window.event) ? event.keyCode : e.keyCode;


switch(KeyID)

{

case 112:

alert("nothing!!");

}

}
</script>




Also, i'm looking for a way to cancel the request to the browser help on F1 press, so i can show my own help. Any ideas?

by Danny CC on Monday, October 1st 2007 at 06:34 AM

ah sorry, that should have been:

<script type="text/javascript">
document.onkeyup = KeyCheck;


function KeyCheck(e)

{


var KeyID = (window.event) ? event.keyCode : e.keyCode;

alert KeyID;

}
</script>

by jev on Wednesday, November 7th 2007 at 07:56 AM

great, thanks!!!!

by Kevin on Friday, November 16th 2007 at 03:30 PM

This is a great script, but I'm a beginner/non-programmer. Can anyone tell me how to take the captured arrow key and use it to reload a new page?

Thanks a million!!!
-Kevin

by Kevin on Friday, November 16th 2007 at 03:34 PM

This is a great script, but I\'m a beginner/non-programmer. Can anyone tell me how to take the captured arrow key and use it to reload a new page?

Thanks a million!!!
-Kevin

by malli on Tuesday, November 20th 2007 at 02:43 AM

hi sir,
i have problem in javascript.how to resstict char in textbox?what event have u clled?

by Chitra on Tuesday, December 18th 2007 at 06:12 AM


Hi,

Check below code for restricting keys in a field.

<html>
<head>
<!-- Below is the js code -->

<script type="text/javascript">
var _dom = 0;
_dom=document.all?3:(document.getElementById?1:(document.layers?2:0));
//document.onkeydown = keydownhandler;
//document.onkeyup = keyuphandler;
//document.onkeypress = keypresshandler;


// _dom = 0;
function notSupported(){ alert('your browser is not supported.'); }
function fromKeyCode(k){ return ''; }
function keydownhandler(e){
if(document.all) e=window.event; // for IE
var f=document.searchcustomerform;

if(_dom==2){ // for NN4
if(e.modifiers& (Event.ALT_MASK || Event.CONTROL_MASK || Event.SHIFT_MASK) ){
return true;
}
} else {
if(e.shiftKey || e.ctrlKey || e.altKey){
//alert("shift/ ctrl/ alt");
return true;
}

var ch='';
if(_dom==3){ // for IE

if(
(e.keyCode >= 96 && e.keyCode <= 105) || // keys with num lock
(e.keyCode >= 48 && e.keyCode <= 57) || //0 - 9
((!e.shiftKey) && (e.keyCode >= 35 && e.keyCode <= 40)) || // arrow key
(e.keyCode == 8) || // backspace
(e.keyCode == 46) || // delete
(e.keyCode == 9) // tab
) {
return true;
} else {

return false;
}

} /*else { // for Mozilla
metaKeyD.value =e.metaKey;
}*/
}

return true;
}
function keyuphandler(e){
if(document.all) e=window.event; // for IE
var f=document.searchcustomerform;

if(_dom==2){ // for NN4
if(e.modifiers& (Event.ALT_MASK || Event.CONTROL_MASK || Event.SHIFT_MASK) ){
return true;
}
} else {
if(e.shiftKey || e.ctrlKey || e.altKey){
//alert("shift/ ctrl/ alt");
return true;
}

if(_dom==3){ // for IE
if(
(e.keyCode >= 96 && e.keyCode <= 105) || // keys with num lock
(e.keyCode >= 48 && e.keyCode <= 57) || //0 - 9
((!e.shiftKey) && (e.keyCode >= 35 && e.keyCode <= 40)) || // arrow key
(e.keyCode == 8) || // backspace
(e.keyCode == 46) || // delete
(e.keyCode == 9) // tab
) {
return true;
} else {

return false;
}

}
}

return true;
}
function keypresshandler(e){
if(document.all) e=window.event; // for IE
var f=document.searchcustomerform;

if(_dom==2){ // for NN4
if(e.modifiers& (Event.ALT_MASK || Event.CONTROL_MASK || Event.SHIFT_MASK) ){
return true;
}
} else {
var ch='';
if(_dom==3){ // for IE

if(
(e.keyCode >= 96 && e.keyCode <= 105) || // keys with num lock
(e.keyCode >= 48 && e.keyCode <= 57) || //0 - 9
//((!e.shiftKey) && (e.keyCode >= 35 && e.keyCode <= 40)) || // arrow key
(e.keyCode == 8) || // backspace
(e.keyCode == 46) || // delete
(e.keyCode == 9) // tab
) {
return true;
} else {

return false;
}

}
}

return true;
}
function initializeNumericFieldValidate(f){

field = f;
_dom=document.all?3:(document.getElementById?1:(document.layers?2:0));
document.onkeydown = keydownhandler;
document.onkeyup = keyuphandler;
document.onkeypress = keypresshandler;
}

function removeNumericFieldValidate(f){

field = null;
_dom=document.all?3:(document.getElementById?1:(document.layers?2:0));
document.onkeydown = null;
document.onkeyup = null;
document.onkeypress = null;
}

</script>
</head>

<body>
<form name="form1">
<input type="text" name="field1"/>


<input type="text" name="postcode" onfocus="initializeNumericFieldValidate(this)" onblur="removeNumericFieldValidate(this)" />

<input type="text" name="field3"/>
</form>
</body>

</html>

by Mahesh Kumar on Friday, February 8th 2008 at 03:23 AM

Hi Sir,
This is Mahesh. can you suggest me the script code which provides a numeric lock. Provided it has to work for both internet explorer and Mozilla Firefox. please it is urgent.

Thanks & Regards,
Mahesh Kumar.D
Ph: 9440000321

by kuko on Sunday, April 20th 2008 at 05:58 AM

hi,

any1 have found solution for opera with 37/39 char? ( % == <- | ' == -> )?

% should b possible to get work as it require shift key to b pressed ... but with character ' (39|->) im realy clueless :((
any1 can help with this pseudo ascii opera hell? any workaround?

by aled on Wednesday, April 23rd 2008 at 07:22 PM

Another thankfull soul apreciates your help. Thank you very much indeed. Really usefull.

by Amit Dusane on Wednesday, July 9th 2008 at 03:34 AM

Excellent !!

Your code has made my work easy
Keep it up man!
Thanks

by Rajul on Thursday, July 31st 2008 at 07:16 AM

Hi
Please help me in capturing event for ALT A or any two keys consecutively pressed.
if i press ALT A than i want to do some thing so how i can it?

by dharmesh on Monday, August 25th 2008 at 02:17 AM

plz provide mw javascript code for e-mail valliation ;
thanks

by Chaz Brown on Monday, September 15th 2008 at 10:49 PM

Please, I beg of you! The Cadbury Secret, man!!!

Nice tut/code snip.

by ss on Thursday, September 18th 2008 at 06:53 AM

ss

by Jaikumar on Friday, September 19th 2008 at 12:35 AM

Hi,
I have a doubt. When we press ALT h-- i want the home page to open, when i press ALT c i want the contact us page to open, etc. no enters after pressin ALT h or others, directly i wnat the url to come up on pressing of ALT (anykey) which should also be browser compatible. Please can someone help me with this. Please it is very urgent


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs JavaScript Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons