I'm having problem with some jquery code. So the story is, I'm trying to write a snake game using jquery.
$(document).ready(function(e) {
initial_move();
$(document).keydown(function(e){
switch (e.keyCode) {
case 38:
$('#snake-body').stop().add('#one').animate({marginTop:'-2%'},'fast');
return('null');
case 37:
return('null');
case 39:
return('null');
case 40:
alert('bottom');
return('null');
}
});
});
function initial_move(){
$('#snake-body').css('margin-left','0%');
$('#snake-body').animate({marginLeft:'100%'},5000,'linear',initial_move);
}
<div id="wrapper">
<div id="snake-body">
<div id="2" class="part"></div>
<div id="1" class="part"></div>
</div>
</div>
I'm stuck while trying to make the snake parts move according to keydown. when i press the up arrow key, first the div with id="one"
should move up and followed by id="two"
and so on.
But this code moves both the div simultaneously to margintop:'-2%'
. I don't understand because I've targeted only the id="one"
div in the code..
case 38:
$('#snake-body').stop().add('#one').animate({marginTop:'-2%'},'fast');
I hope someone could help me out with this. Thanks in advance.