I am trying to put some basic jQuery animation on an element based on single or multiple arrow key press events. The objective is to animate the element in the direction of the key/keys that has been pressed. I have followed the approach that has been discussed here to detect multiple key press. But for some reason when multiple keys are pressed, the code for single key press of any of the keys gets executed randomly along with the code for multiple key press. But if I comment out the code from line 25-41, the events of multiple key press work as expected. I can not figure out what's going wrong.
var key = [];
$(document).keydown(function(e) {
key[e.which] = true;
}).keyup(function(e) {
if (key[37] && key[38]) {
$('.box').animate({
'top': '-=50px',
'left': '-=50px'
}, 250);
} else if (key[39] && key[40]) {
$('.box').animate({
'top': '+=50px',
'left': '+=50px'
}, 250);
} else if (key[38] && key[39]) {
$('.box').animate({
'top': '-=50px',
'left': '+=50px'
}, 250);
} else if (key[37] && key[40]) {
$('.box').animate({
'top': '+=50px',
'left': '-=50px'
}, 250);
} else if (key[37]) {
$('.box').animate({
'left': '-=50px'
}, 250);
} else if (key[38]) {
$('.box').animate({
'top': '-=50px'
}, 250);
} else if (key[39]) {
$('.box').animate({
'left': '+=50px'
}, 250);
} else if (key[40]) {
$('.box').animate({
'top': '+=50px'
}, 250);
}
key[e.which] = false;
});
* {
margin: 0;
padding: 0;
}
.container {
border: 1px solid #ccc;
height: 250px;
margin: 49px;
position: relative;
width: 250px;
}
.box {
background-color: #ccc;
height: 50px;
left: 50%;
margin: -25px 0 0 -25px;
position: absolute;
top: 50%;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="box"></div>
</div>
After following these steps:
your key array contains true values at key[37] (left) and key[40] (down). When keyup() executes, it will apply the animate() in your fourth if statement, but it will only clear key[40]. Then, when you release the left key, your key array still contains a true value at key[37], so keyup() applies the animate() in your fifth if statement. That's why you're seeing multiple actions.
One possible solution is to clear both entries in the key array if one of the first four if statements is executed. Doing so should probably be OK with how I'm interpreting your users to be interacting with the page, in that they will be pressing and releasing both keys at the same time.