0

I have the following code:

function optionkey()
{
    e = window.event;
    if( e.altKey )
    {
        return "down";
    }
    else
    {
        return "up";
    }
}

interval = setInterval(function(){
    if( optionkey() == "down" ) {
        clearInterval(interval);
        alert( 5 );
    }
}, 100);

Basically the code should run alert(5) when the user presses the optionkey, but instead I get a load of errors: Uncaught TypeError: Cannot read property 'altKey' of undefined

Can anyone tell me why it does this and how to fix it?

Thanks.

jsfiddle

user2370460
  • 7,470
  • 10
  • 31
  • 46

2 Answers2

0

Please let me know if I have misinterpreted your needs, but if you want an alert to fire when pressing the key you need to create an event listener for onkeydown like so

window.onkeydown = function ( e ) {
    if(e.altKey){
        alert(5);
    }
}
Shan Robertson
  • 2,742
  • 3
  • 25
  • 43
0

First of all event.altKey can only be detected on keypress (input) events like keydown and keyup. However calling a function from setInterval will not trigger the altkey. You will need to catch that in a event handler and pass it on.

function optionkey()
{
 if( window['globalAltKey'])
 {
  return "down";
 }
 else
 {
  return "up";
 }
}

interval = setInterval(function(){
    if( optionkey() == "down" ) {
        clearInterval(interval);
        alert( 5 );
    }
}, 100);

window.addEventListener("keydown", function(e){
    if (e.altKey)
    {
        globalAltKey = true;
    }
    else
     {
        globalAltKey = false;
    }   
        
    
}, false)

Now the interval will still test if the optionkey() will return down or up. Only when the user clicks alt this will fire the alert.

I don't know why you have chosen this approach, you can simply attach a click handler to a button and use the keydown event I provided to check if the alt key is globally pressed.

Mouser
  • 13,132
  • 3
  • 28
  • 54