onkeypress: IE and JavaScript
I have been fiddling with a script today for quite some time, trying to go around Microsoft’s buggy implementation of the DOM in their browser. Yes, Internet Explorer not only lacks proper CSS rendering capabilities, but has problems on the scripting side as well.
My problem was that I needed to listen for a key press, so that I know when [space] or [enter] is pressed by the user. Luckily for me, Firefox, Opera and Safari know about event.which. IE6 doesn’t. IE7 (still) doesn’t. Microsoft thought that using window.event.keyCode would be so much more chic. I found out about this from the w3schools.com website. As I soon found out, their code was flawed. Really, there’s just one tiny bug, triggered by the lovely IE7. We should not use e.keyCode, but window.event.keyCode.
function onkeypress(e){
if(window.event) // for IE
var keynum = window.event.keyCode;
else if(e.which) // for all the abnormal, stupid and useless other browsers
var keynum = e.which;
}
Eat that irony, Microsoft is not changing. This worked for me though, for onkeypress, onkeyup and onkeydown. Does it work for you?
Tags: cross-browser, ie, javascript, keyCode, onkeydown, onkeypress, onkeyup


May 13th, 2008 at 2:15 am
Cool Thanks! I’ve been playing with this myself all day. Wait until you start playing around with grabbing certain keys and realizing that all the browsers map their keyCodes and onKeyPress vs. onKeyDown differently. (Like the arrows, shift and tab).
Thanks for the tip!
June 2nd, 2008 at 7:49 pm
Thanks for the tip! And hey, don’t forget to visit
http://www.spreadfirefox.com/en-US/worldrecord
and learn how a real internet browser works.
Thanks!
September 7th, 2008 at 5:07 pm
thanx the code works for IE7 and Mozilla, just IE is unable to get the keycode value from e, so you got to write “window.event.keyCode” how stupid. microsoft makes me crazy with this monopoly approaches. it’s torture and waste of time dealing with browser compatibility, we have to give support for most browsers and there should be something standart
September 9th, 2008 at 5:48 pm
Thanks for the tip!
More and more IE makes web developers pull their hair.