Why doesn't onkeydown working properly on IE?

function checkEnter(event) {
    var charcode;
    if (event && event.which) {
        charcode = event.which;
        alert("Case 1. event.which is " + charcode);
    }

    else if (event && !event.which) {
        charcode = event.keyCode;
        alert("Case 2. event.keyCode is " + charcode);
    }

    document.getElementById("text1").value="";
}

<input type="text" id="text1" onkeyup="checkEnter(event)" />

The above function works on both IE7 and Chrome.

function checkKeyPressed() {
    document.onkeydown = function(event) {
        var charcode;
        if (event && event.which) {
            charcode = event.which;
            alert("charcode is " + charcode);
        }

        else if (event && !event.which) {
            charcode = event.keyCode;
            alert("charcode (keyCode) is " + charcode);
        }
    }
}

<input type="button" id="button1" onclick="checkKeyPressed(event)" value="Button" />

However this one works only in Chrome. Any idea why?

Answers


You can combine the two by simply checking to see if the parameter is undefined.

function MyOnClick(oEvent)
{
  if (typeof(oEvent) == "undefined")
     oEvent = event;

  // continue with your code
}

This will work for firefox, chrome, IE, etc.


Okay problem solved. Apparently all you have to do is remove the "event" parameter from onkeydown(). I think that's because IE doesn't read javascript the way Chrome does, thus it fails to work properly because there isn't a parameter passed along. =.=


Need Your Help

What is the API to "create applications like Flip3D"

aero flip dwm

I am trying to figure out how to use DWM to render a copy of a Window into my own desired location. The only thing I can find to tell DWM to render somewhere is with the thumbnail APIs.

Fake incoming call

android monkeytalk

I am looking for a way how to automate incoming calls for testing with MonkeyTalk. That means I can run some external scripts. In our Continuous Integration tool I need something capable of running...