javascript - keydown + keyup events for specific keys -


i'm trying make background color change when keys held down. example, when 'r' key being held down, background should red. when 'r' key not being pressed anymore, background should default white.

$(document).ready(function () {     $('body').keydown(function(e){         if(e.keycode == 114){             $(this).css({'background':'red'});           }         if(e.keycode == 121){             $(this).css({'background':'yellow'});         }     });     $('body').keypress(function(e){         if(e.keycode == 114){             $(this).css({'background':'red'});           }         if(e.keycode == 121){             $(this).css({'background':'yellow'});         }     });     $('body').keyup(function(e){         if(e.keycode == 114){             $(this).css({'background':'white'});         }         if(e.keycode == 121){             $(this).css({'background':'white'});         }     });  }); 

the problem i'm having keyup not working each individual key.

    $('body').keyup(function(e){         $(this).css({'background':'white'});     }); 

i know if remove if conditionals keyup altogether behave how said wanted — want able different things later on using keyup specific keys. example, when 'b' key released, maybe on screen "you released b key!" how can keep track of keydown , keyup events specific keys , make different things happen each? know isn't organized either (i'm pretty new stuff) if there's different , better way of doing this...

live demo

fyi r = 82

$(document).ready(function () {      $('body').on('keydown keyup',function(e){       var color = e.type=="keydown" ? 'red' : 'white' ;       if(e.which==82){           $(this).css({background: color});         }     });  }); 

an object oriented example create list of actions desired key:
live demo

$(document).ready(function () {      $('body').on('keydown keyup', function( e ) {        var key = e.which;       var io  = e.type=="keydown" ? 0 : 1; // "0"if keydown; "1" if keyup       var keyaction = {                    // object store our stuff //  keycode : [(0)keydown, (1)keyup]         82  : ['red' ,'white'],            // r key         66  : ['blue','white']             // b key  (last 1 without comma!)       };       var propobj = {};                    // object store property + value jquery methods       var keyarr = keyaction[key];        if(typeof keyarr != 'undefined') {   // test keyarr (82, 66) returned/populated prevent errors          propobj.background = keyaction[key][io];   // created jq method's object e.g: {background:"red"}          $(this).css(propobj);             // create / use        }      });  }); 

where instead of ternary operator (?:) used:

var io = e.type=="keydown" ? 0 : 1; 

you can use not bitwise operator like:

var io = ~~(e.type=="keyup"); // evaluating false|true == 0|1 

any way need know event occurring (from designated "keydown" / "keyup") , desired array position [0],[1] of property value need, e.g: ["red"],["white"] (where "red" == 0 , "white" == 1)

demo not bitwise operator


an more advanced way demo of above add list also

  • elements target,
  • a jquery method use,
  • the properties method apply

which result in:

$(document).ready(function () {      $('body').on('keydown keyup', function(e) {        var keyaction = {          82  : ['body', 'css', "background", ['red','white'] ],  // r key         66  : ['body', 'css', "background", ['blue','white'] ], // b key         72  : ['h1', 'animate', "top", [100,30] ]       // h key        },           key = e.which,              // keycode           keyarr = keyaction[key],    // our array our list           io  = e.type=="keydown" ? 0 : 1, // io 0 || 1 depending if key down or           element,           method,           property={}; // method properties object e.g: {"background":"red"}        if(typeof keyarr != "undefined"){          element = keyarr[0],           method = keyarr[1],          property[keyarr[2]] = keyarr[3][io];                 $(element)[method](property);  // stuff       }        console.log( key, io, element, method, property);      });  }); 

you can hold down b key , press h key simultaneous actions.

if have questions (i think would) feel free ask.

edit

if want control css classes like:

http://jsbin.com/awolab/22/edit


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -