javascript - How do addEventListener and attachEvent works? Keydown and Keyup is not working properly -


i wrote code snippet "shift key" keydown , keyup events mozilla not working expect. code:

<html> <head> <title>testing page</title> <script type="text/javascript"> var key_capslock = 0; var key_shift = 0;  function print1(){ window.alert("shift status" + key_shift);} function print2(){ window.alert("shift status" + key_shift);} function keyset(evt){   evt.preventdefault();   if(evt.keycode == 16){      if(key_shift == 0 ){key_shift = 1; evt.stoppropagation();}      else {key_shift = 0; evt.stoppropagation();}   } print1(); return; } function keyrelease(evt){    evt.preventdefault();    if(evt.keycode == 16){       if(key_shift == 0 ){key_shift = 1; evt.stoppropagation();}       else {key_shift = 0; evt.stoppropagation();}    } print2(); return; }  function init(){ document.body.setattribute("contenteditable", true); document.body.addeventlistener("keydown", keyset, false); document.body.addeventlistener("keyup", keyrelease, false); } </script> </head> <body onload="init()"> <br> <body> </html> 

steps: 1. press shift key (keydown , keyup events occur). 2. alert comes shift status (print1 function runs). click that. expected: alert should come shift status (print2 function should run). actual: print2 function not run.

if press shift key second time print2 function runs. don't understand how mozilla handling addeventlistener function. can please me resolve issue? don't want use third party framework resolve issue (jquery, dojo etc).

thanks

your code fine, alert message takes focus browser, preventing detecting keyup.

if change functions write div, instance, see both functions work:

http://jsfiddle.net/jtbowden/vqnvg/

although, don't understand code:

if(key_shift == 0 ){key_shift = 1; evt.stoppropagation();}  else {key_shift = 0; evt.stoppropagation();} 

if in keyset, key_shift should 1 seems, rather toggling:

function keyset(evt){   evt.preventdefault();   if(evt.keycode == 16){      key_shift = 1;      evt.stoppropagation();   }   print1();   return; } function keyrelease(evt){    evt.preventdefault();    if(evt.keycode == 16){       key_shift = 0;       evt.stoppropagation();    }    print2();    return; } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -