Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Action Listeners in javascript - IE

javascript action listeners - IE compatible



7:03 am on Sep 3, 2010 (gmt 0)

5+ Year Member

I'm trying to attach an event to detect key press in internet explorer.

the current works for firefox but not for internet explorer.

<script type="text/javascript">

function myfunc(e)
alert('ctrl pressed');
else {alert("ok");}

//set page event handlers
if (window.attachEvent) {
//IE and Opera
window.attachEvent("keyup", function(evt){myfunc(evt);},false);
} else if (window.addEventListener) {
// IE 6
window.addEventListener("keyup", function(evt){myfunc(evt);},false);
} else {
document.addEventListener("keyup", function(evt){myfunc(evt);},false);


Thanks in advance!


7:36 am on Sep 3, 2010 (gmt 0)

5+ Year Member

oh btw keyCode 17 is for the ctrl key


1:38 pm on Sep 3, 2010 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

attachEvent [msdn.microsoft.com] takes only 2 parameters (not 3 as you have it), the event must be specified as "onkeyup" instead of "keyup", and it needs to be attached to the document object instead of the window object.

document.attachEvent("onkeyup", function(evt){myfunc(evt);});

Also, your else if and else conditions are the same, and you incorrectly marked the 'else if' condition with a comment indicating that it's for IE6 (which is not the case... IE6 will use the attachEvent method.

Hope that helps.

Featured Threads

Hot Threads This Week

Hot Threads This Month