0

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.

krishwader
  • 11,141
  • 1
  • 32
  • 51

1 Answers1

0

This code:

$('#snake-body').stop().add('#one').animate({marginTop:'-2%'},'fast');

Is the same as this code:

$('#snake-body').stop();
$('#snake-body, #one').animate({marginTop:'-2%'},'fast');

Which means you're updating both the #snake-body, and the #one part.

This is because add() adds the #one div to what you've already selected... meaning you've got both the parent (#snake-body) and the part (#one) selected at the same time.

What you probably want to do instead is this:

$('#snake-body').stop();
$('#one').animate({marginTop:'-2%'},'fast');

Depending on what you're intending the .stop() for, you may want to stop the individual parts instead of the parent:

$('#snake-body .part').stop();
$('#one').animate({marginTop:'-2%'},'fast');
jcsanyi
  • 7,953
  • 2
  • 25
  • 51