I'm trying to make the background color change when certain keys are held down. For example, when the 'r' key is being held down, the background should be red. When the 'r' key is not being pressed anymore, the background should default to 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 is that keyup is not working specifically for each individual key.
$('body').keyup(function(e){
$(this).css({'background':'white'});
});
I know if I remove the if conditionals from keyup altogether then it will behave how I said I wanted it to — but I want to be able to do different things later on using keyup with specific keys. For example, when just the 'b' key is released, maybe it will say something on the screen like "You just released the b key!" How can I keep track of keydown and keyup events for specific keys and make different things happen for each? I know this isn't very organized either (I'm pretty new to this stuff) so if there's a completely different and better way of doing this...
Now just match the css rules with your css classes
LIVE DEMO
FYI R = 82
An object oriented example would be to create a list of actions for a desired KEY:
LIVE DEMO
where instead of the Ternary Operator (?:) I used:
you can also use the NOT bitwise operator like:
any way you just need to know which event is occurring (from the designated "keydown" / "keyup") and get the desired array position
[0]
,[1]
of the property value you need, e.g:["red"]
,["white"]
(where "red" == 0 and "white" == 1)DEMO with NOT bitwise operator
An more advanced way DEMO of the above would be to add to your list also
which would result in:
You can even hold down your B key and press the H key to do simultaneous actions.
If you have questions (I think you would) feel free to ask.
EDIT
If you want to control CSS classes than do like:
http://jsbin.com/awolab/22/edit