Hey! This is the dev blog for the app named gosnip.
If you need a neat way to organize your code, gosnip, it's free.

This blog talks about the how's and why's behind gosnip and features articles and tutorials on the techniques used.

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: , , , , , ,

4 Responses to “onkeypress: IE and JavaScript”

  1. Doug Says:

    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!

  2. URSoNice Says:

    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!

  3. Stillborn Says:

    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

  4. BornAgain Says:

    Thanks for the tip!
    More and more IE makes web developers pull their hair.

Leave a Reply