javascript - Why am I unable to get the alt key pressed? -


i trying alt key set shortcut shift+alt+a orctrl+alt+a when `shift or ctrl key pressed can't determine whether alt key pressed or not .the following code makes problem more clear.

    el.onkeydown=function(e){     //alert(e.keycode);      if(e.shiftkey==true){     document.body.appendchild(document.createtextnode("shiftkey"));     document.body.appendchild(document.createelement("br"));     }     else if(e.ctrlkey==true){     document.body.appendchild(document.createtextnode("ctrlkey"));     document.body.appendchild(document.createelement("br"));     }     else if(e.altkey==true){     document.body.appendchild(document.createtextnode("altkey"));     document.body.appendchild(document.createelement("br"));     }     }; 

when try press alt key after shiftorctrl key e.altkey doesn't value of true , result as

    shiftkey     shiftkey     shiftkey     shiftkey     shiftkey     shiftkey... 

or ctrl:

    ctrlkey     ctrlkey     ctrlkey     ctrlkey     ctrlkey     ctrlkey     ctrlkey... 

design flaw. you're checking if shiftkey pressed down. if isn't, check others. let's think of step step.

you press shift key first. event fires, , first condition satisfied. now, when press down alt key, keydown event called again, , time, since you're holding down both shift , alt, first , third conditions met. however, program never gets third condition, because it's in else clause. means first condition's code evaluated, , rest of conditons skipped, since first true.

change design check keys individually, not else clauses each.

your code this:

el.onkeydown=function(e){ //alert(e.keycode);  if(e.shiftkey==true){ document.body.appendchild(document.createtextnode("shiftkey")); document.body.appendchild(document.createelement("br")); } if(e.ctrlkey==true){ document.body.appendchild(document.createtextnode("ctrlkey")); document.body.appendchild(document.createelement("br")); } if(e.altkey==true){ document.body.appendchild(document.createtextnode("altkey")); document.body.appendchild(document.createelement("br")); } }; 

think of example make flaw clearer:

if(true){     console.log('first'); } else if(true){     console.log('second'); } 

you can see doesn't matter whether second condition true or not, long first is.

in case, though, using && logical operator make more sense, since want when 3 keys held down create shortcut. that'd make code this:

if(e.shiftkey && e.altkey && e.keycode === 65){     console.log('shortcut active'); } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -