onKeyPress event in Firefox and IE8

Solution 1:

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();
});

Solution 2:

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
}

Solution 3:

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();  
}