Cross-browser Keypress Event Handler
While doing a javascript cross-browser check of an web application. I have encountered a javascript error in handling keypress events on Firefox and Opera browser. Apparently the previous programmer who created the web application did not took into consideration Firefox and Opera browsers. The code is only working under IE. This is the part of the javascript code which is for IE only.
if (event.keyCode==13){
[do something here...]
return true;
}
In Firefox the event.keyCode will throw an error since the event model for Firefox are different. What I first did is to create a function to handle the event using the onkeypress like this:
onkeypress="pressYouBastard(event);"
And on the pressYouBastard function:
function pressYouBastard(evt){
evt = (evt) ? evt : (window.event) ? event : null;
if (evt)
{
var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if (charCode == 13) validate();
}
}
The function retrieves the events (in this case keyboard press) ASCII code and passes it to a variable, and checks the value (13 is the ASCII value of ENTER key) if the value is ENTER key it will call a new function i called validate to handle more specific functions.
This will work on IE, Firefox and Opera. I have never tried it on Safari though.
Bookmark This!








I am Filipino Web Developer, focusing on PHP in LAMP framework. As a kid, I spent a lot of my time exploring computers and computer games from Atari to PS, from INTEL 80286 - CoreDuo. I am happily married, with two kids. Currently working in Japan as an IT Engineer.