Posts Tagged ‘cross-browser’

onkeypress: IE and JavaScript

Tuesday, April 1st, 2008

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?