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 Andrew Pociu (View Profile)
*****   (Rated 4.5 with 80 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

by kevin on Friday, November 21st 2008 at 07:01 AM

Thanks! it helped a lot

by Praveen on Tuesday, December 23rd 2008 at 06:54 AM

Hi i have one text which should accept more than 200 value. in first text box if i give 90 and press tab it works in mozilla but does not work in IE
here is my code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

<head>

<title> New Document </title>

<meta name="Generator" content="EditPlus">

<meta name="Author" content="">

<meta name="Keywords" content="">

<meta name="Description" content="">



<script language="javascript" type="text/javascript">



function saveForm(oEvent)

{

//document.getElementById("aa").value=event.keyCode ;

// here i tried to making it work in both Internet Explorer and Firefox
var KeyID = (window.event) ? event.keyCode : oEvent.keyCode;
if(KeyID == 13 || KeyID == 9 )

{

if(isLimitForSave(document.getElementById("txtSupAccount1"))==false)

return false;

if(isLimitForSave(document.getElementById("txtSupAccount2"))==false)

return false;

if(isLimitForSave(document.getElementById("txtSupAccount3"))==false)

return false;



alert("Enter Hit Success");



}

else

return false;

}





function isLimitForSave(field1)

{

var test1=field1.value;

if(test1.length>0

by Yashu on Wednesday, January 7th 2009 at 01:35 PM

How to Create an Image as button? And when Press it then in a cell of a table my another snap display on the same page ?? Please suggest.. Thanks in advance..

by Yashu on Wednesday, January 7th 2009 at 01:35 PM

How to Create an Image as button? And when Press it then in a cell of a table my another snap display on the same page ?? Please suggest.. Thanks in advance..

by SUSEELA on Tuesday, January 27th 2009 at 03:56 AM

Hi,

I have a doubt in javascript.I have selection of cities, in that i would like to select "chennai" ,
the selection is responding only if i press "c",
then i have to check chennai in all C related cities.Instead of that i would like to search like
if i press "che", then i can easily select my city soon.I want a code for this in java script.Pls help me in this

by javakid0456 on Wednesday, January 28th 2009 at 05:14 PM

Is there anyway to make it count and display the number of presses on screen

by chris on Friday, April 3rd 2009 at 02:42 AM

how do i get the press key on a form?

example getting the press key event on text form

by chris on Friday, April 3rd 2009 at 02:55 AM

i tried this
<input type="text" name="KeyName" onkeyup="return KeyCheck(event)" />

and removed the
document.onkeyup = KeyCheck;

it works but when i change the onkeyup to onkeypress it doesnt work? do you know why?


thanks

by eeti on Friday, April 3rd 2009 at 04:20 AM

hi,
im creating a login form. I want to take input from user in different fields. When the user enters his/her name in textbox then he/she cannot enter numeric code(1,2,3...) in textbox

Plz help me out. I need code in javascript.

by Praveen on Friday, April 3rd 2009 at 06:04 AM

Hi eeti

function isnotInteger(s){
var i;
for (i = 0; i < s.length; i ){
// Check that current character is number.
var c = s.charAt(i);
if (((c < “0″) || (c > “9″))) return true;
}
// All characters are numbers.
return false;
}

by Eeti on Saturday, April 4th 2009 at 12:56 AM

hi,

If we check a checkbox then:
1. a row of a table (which is hidden by default) shud be displayed
2. at the same time another row of same table shud hide.

If we uncheck d checkbox then:
1. d row of table (which is hidden by default) shud be hidden
2. at the same time dat another row of same table shud be visible.

do u kno d code in javascript.

by dfyty on Tuesday, April 7th 2009 at 02:40 AM

Fools

by kiku on Tuesday, April 7th 2009 at 04:44 AM

@chris

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

by chris on Wednesday, April 8th 2009 at 03:48 AM

@kiku

thx for the reply but still it doesnt work
here is the code

<script language="javascript">
function KeyCheck(e)
{
//var KeyID = (window.event) ? event.keyCode : e.keyCode;
var KeyID = (window.event) ? window.event.keyCode : e.which;

switch(KeyID)
{
case 38:
document.form.interval.value = "Arrow Up";
break;

case 40:
document.form.interval.value = "Arrow Down";
break;
}
}
</script>
<form name="form">
<input type="text" id="interval" name="interval" size="2" maxlength="2" value="0" onkeypress="return KeyCheck(event)" autocomplete="off" />
</form>

by Kangkan on Wednesday, April 8th 2009 at 11:28 PM

A very nice and helpful topic. After reading this, I have just created a calculator that can be invoked in a page.

Currently, the key combination for invoking the calculator is the Ctrl Windows key. This shows and hides the calculator. The calculator has a text area and the user can type in an arithmetic (Validation is pending for non arithmetic keys) expression and on enter key, the same is evaluated.

Here is the code
=============================
<html>
<head>
<script language="javascript">
document.onkeyup = KeyCheck;
var calcVisible = false;

function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 91:
if (!calcVisible)
ShowCalc('CalcPlace')
else
HideCalc('CalcPlace');
break;
default:
//alert(KeyID);
}
}

function ShowCalc(ParentId)
{
var strCalcEl="<div id='calc'><textarea id='calcInput' style='width:300px; height: 50px;' onkeydown='EvalCalc(event);'></textarea><br/><input id='calcResult' type='text' readonly STYLE='width:300px;'/></div>";
document.getElementById(ParentId).innerHTML=strCalcEl;
calcVisible = true;
document.getElementById("calcInput").focus();
}

function HideCalc(ParentId)
{
document.getElementById(ParentId).innerHTML="";
calcVisible = false;
}

function EvalCalc(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 13:
document.getElementById('calcResult').value=eval(document.getElementById("calcInput").value);
break;
default:
//alert(KeyID);
}
}
</script>
</head>
<body>
<div id="CalcPlace" style="width:100%;"></div>
</body>
</html>
=============================

Kangkan
Http://www.geekays.net/

by ivica on Wednesday, June 3rd 2009 at 02:18 AM

great man, tnx a lot... this works very fine


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