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>