'Event handler not working in Internet Explorer
I am creating a website using JavaScript. The purpose of the JS part is to attach my own keyboard handler to certain text fields.
I managed to narrow down the problem to the code as simple as this fiddle:
http://jsfiddle.net/k9s3n/1/
In Firefox, Opera and Chrome, typing a character in any of the three fields results in displaying an alert box with the key code. In Internet Explorer (IE8 in my case, that's the lowest version I usually support), however, only input3 works properly - that is, it is the only field to display the dialog box when releasing a key. Trying to type in the other two boxes gives no results, it just logs an error in the console:
keyCode is null or isn't an object
(not sure if the error message is right, I translated it from my native language).
It seems that only the third solution works regardless of the browser, but in my scenario I have to use the first one or the second one.
I have created another fiddle for further investigation:
http://jsfiddle.net/bSdaJ/
Both of the buttons, when clicked, cause a message box to display. In Firefox, Opera and Chrome, the box says "[object MouseEvent]", while in IE it says "undefined".
What can I do about that?
P.S. As indicated by the first fiddle, everything works fine if I use inline event handling. However, my goal in this project is to separate HTML and JS completely, so I cannot use that. I'm doing it for a friend and I want the HTML part to be plain, clear markup code.
Solution 1:[1]
try this:
function clickHandler(e) {
if(!e)
e = window.event;
alert(e);
}
Solution 2:[2]
try this:
function funcToCall(e)
{
//alert('here');
var keycode;
if (window.event)
{
if (window.event.keyCode == '112') { // F1 was pressed
// call your methods in this area
window.event.returnValue = false;
return false;
}
}
else if(e)
{
if (e.which == '112') { // F1 was pressed, search for other keycodes
// call your methods in this area
e.preventDefault();
return false;
}
}
}
call on your textfield:
onKeyDown="funcToCall(event)"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom |
| Solution 2 | Waqas Mahmood |
