Capture Key Press

pradeep's Avatar author of Capture Key Press
This is an article on Capture Key Press in Web Design, HTML And CSS Tutorials.
The following code works for capturing key presses on IE, Netscape, Opera 7,and somewhat with Opera 6.

HTML Code:
 <html>
 <script language="JavaScript">
 function keyHandler(e)
 {
 	var pressedKey;
 	if (document.all)	{ e = window.event; }
 	if (document.layers) { pressedKey = e.which; }
 	if (document.all)	{ pressedKey = e.keyCode; }
 	pressedCharacter = String.fromCharCode(pressedKey);
 	alert(' Character = ' + pressedCharacter + ' [Decimal value = ' + pressedKey + ']');
 }
 document.onkeypress = keyHandler;
 </script>
 <body>Press any key.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Does it work with FF
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Oh! That can be fixed with changing line 7 to this

Code: javascript
if (document.layers || e.which) { pressedKey = e.which; }
0
kanchan's Avatar, Join Date: Feb 2007
Newbie Member
hi pradeep.
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Hi, Do i know you?
0
kanchan's Avatar, Join Date: Feb 2007
Newbie Member
no you dont know me
I am from aurangabad.
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Can I help you out in some way?
0
rahul bakshi's Avatar, Join Date: May 2007
Newbie Member
Hi i m rahul.Your promming excellent for everyone.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Everyone, Please keep the discussion related to the article here and other discussions in the respective threads or create a new one.
0
ClayC's Avatar
Light Poster
thanks for the code but it had a small bug in it which was when you press 2 keys very very fast it will capture 1 of them and the other just be ignored, I am personally using it to disable the Fx keys and the arrow keys etc... letting the user use only the alphanumeric keys...

here is what I did
Code:
<script language="JavaScript">
	<!--
	function keyHandler(e) {
		var pressedKey;
		if (document.all)	{ e = window.event; pressedKey = e.keyCode; }
		if (document.layers || e.which) { pressedKey = e.which; }
		if (!pressedKey) { return false; }
	}
	
	document.onkeypress = keyHandler;
	-->
</script>
I added the comment tags cause in IE 5 it sometimes prints out the code so using those will make it think it's a comment so it will just be ignored :P

tnx alot for the code you gave out here, you really helped me and also thnx to pradeep for telling us how to make it work with FF too

hope what I did helps you as much as what you did helped me

Last edited by shabbir; 31Mar2009 at 07:36.. Reason: Code blocks