Forum Moderators: open

Message Too Old, No Replies

Action Listeners in javascript - IE

javascript action listeners - IE compatible

         

nil111

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

10+ 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">
//window.addEventListener("keyup",function(evt){myfunc(evt);},false);

function myfunc(e)
{
if(e.keyCode==17){
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 {
//FireFox
document.addEventListener("keyup", function(evt){myfunc(evt);},false);
}


</script>



Thanks in advance!

nil111

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

10+ Year Member



oh btw keyCode 17 is for the ctrl key

Fotiman

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

WebmasterWorld Senior Member 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.