Welcome to WebmasterWorld Guest from 54.167.219.201

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)

Junior Member

5+ Year Member

joined:July 8, 2008
posts: 80
votes: 0


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!
7:36 am on Sept 3, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:July 8, 2008
posts:80
votes: 0


oh btw keyCode 17 is for the ctrl key
1:38 pm on Sept 3, 2010 (gmt 0)

Senior Member from US 

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

joined:Oct 17, 2005
posts:4996
votes: 14


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.
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members