...

View Full Version : a function(event) problem



stick_branch
06-20-2009, 03:15 PM
hi all,

i have to attach an event to the body, and in all eventuality it will be doing something completely different, but for the time being it is just bringing up an alert box for testing, but i'm attaching an event to the document onkeypress.



var test = new testFunction();
function testFunction(){
this.attachListener = function(){
if(document.addEventListener){
document.addEventListener('keypress',function(){test.onKeyPress(event)},false);
}
else if(document.attachEvent){
document.attachEvent(onkeypress,function(){test.onKeyPress(event)})
}
else{
//old way
}
}
this.onKeyPress = function(e){
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
alert(keynum);
}

}


but event returns undefined. Not sure why, as it's the only way I know how to get what key was pressed... but it's inaccessible

thanks for your help

Kor
06-20-2009, 07:10 PM
You need to define the e argument for IE


this.onKeyPress = function(e){
var e=(!e)?window.event:e;//IE:Moz
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
alert(keynum);


}

stick_branch
06-21-2009, 01:15 AM
event still returns undefined, and so does e.

Philip M
06-21-2009, 07:49 AM
Try this:-


<script type = "text/javascript">

function handleKeyPress(evt) {
var key = (window.event)?event.keyCode:evt.which;
alert ("Keycode = " + key);

which = String.fromCharCode(key).toUpperCase();
if (key>=48 && key<=90) {
alert ("You pressed the " + which + " key");
}

return true;
}

document.onkeydown= handleKeyPress
</script>

stick_branch
06-21-2009, 09:51 AM
Thankyou very much, that last code worked fine.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum