I have the following javascript code...Here I am using onKeyPress=\"someFunction( )\" in the body tag to get the keyCode of the key that is pressed.
I think Firefox are not caring programmers... and this is the reason why so, In Firefox navigator.appName returns "Netscape". so user can edit his code like,
if(navigator.appName == "Netscape")
Key = event.charCode; //or e.which; (standard method)
else
Key = event.keyCode;
Browsers have different ways of handling keyboard events. Have a look at http://unixpapa.com/js/key.html for more info.
For example, these changes to your code will get it working in Firefox:
<body bgcolor="lightblue" onkeypress="keypress(e)">
and
function keypress(e) {
alert(window.event ? event.keyCode : e.which);
// other stuff
}
Pass event object as an parameter and your code will work in IE as well as firefox. The code example is as follows :
<body bgcolor="lightblue" onkeypress="keypress(event)">
function keypress(event) {
alert(event.keyCode);
var key=event.keyCode;
if(key==112 || key==80)
printDiv();
else if(key==101 || key==69)
window.location="http://google.com";
else if(key==114 || key==82)
window.reset();
}
When problems like this show up, I start to use any kind of a JavaScript framework. Those frameworks are build to avoid problems with different browsers.
To catch all different keypress()
apis, like the link from Emmett shows, can be very difficult.
Example:
In HTML head:
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
In the JS tag:
$(document).keydown(function(event) {
alert('You pressed '+event.keyCode);
event.preventDefault();
});