views:

597

answers:

4

Hello. I've written this code inside the HEAD tags of my HTML page. It works fine in FF, Chrome and Safaria, but doesn't in IE7. I would like to know how to fix it.

<script type="text/javascript">
if ( window.addEventListener ) {
  window.addEventListener("keydown", function(e) {
    alert(e.keyCode);
  }, true);
}
</script>

Thanks in advance.

+2  A: 

There is no window.addEventListener in IE, you need to use attachEvent. There's good documentation on events here, or you could switch to using a library that abstracts browser differences.

Annie
+2  A: 

Microsoft has implemented their own way of doing this called attachEvent. You can read more about this over at quirksmode.org: http://www.quirksmode.org/js/events%5Fadvanced.html

vrutberg
+1  A: 

Try:

window.attachEvent

More fully:

//set page event handlers
if (window.attachEvent) {
//IE and Opera
window.attachEvent("keydown", "");
} else if (window.addEventListener) {
// IE 6
window.addEventListener("keydown", "");
} else {
//FireFox
document.addEventListener("keydown", "");
}
graphicdivine
A: 

You're screwed: you're using event capturing (passing true as the last parameter to addEventListener). IE has no such equivalent, in any version, including IE8 in IE8 mode.

Is there a reason you must use event capturing rather that event bubbling here? IOW, pass false as your last parameter? Then, you'd be able to port this (somewhat) to use IE's attachEvent proprietary method, or use a library (as others have suggested and added links for).

Roatin Marth