views:

149

answers:

3

Hi! I'm doing a chess game. In there, I want to move an element with effect and then append it to new div. Following is my code.

    //--> #p70 is just ablove #p80
    //--> each square is 64px
    $('#p80').animate({bottom:'+=64px'},500); //--> move one square above
    $('#b70').append($('#p80')); //--> append the animated element to owner 'div'

The problem is, it moves 2 square( equivalent to 128px) where I only did is 64px. Here is my page and if you click the white square just above the pawn, you'll see the problem. I've tried adding delay(1000) and even javascript setTimeout but nothing works :( Really appreciate your helps in advance!

+2  A: 

Try:

$("p80").animate({bottom: "+=64px"}, 500, function() {
  $(this).css("bottom", 0).appendTo("#b70");
});

Basically you're animating the position relatively but you move the piece to a new location before the animation completes so it is now relative to the new location not the old one.

The above version doesn't move the piece until the animation completes, which should solve the problem. animate() can be provided a callback to be called on completion of the effect.

Also, you need to reset the attribute you're animating once it's in the new location.

This is why it's moving twice the distance. It's only animating 64px but then you move it to another square which is 64px away and it's still positioned 64px away in relative terms. 64px + 64px = 128px. You need to reset the effect in the new location.

cletus
Perfect answer. You saved my life :)
Devyn
+1  A: 

You can also take this approach, a bit backwards from current:

$('#b70').unbind().click(function(){        
  $('#p80').css({bottom: '-64px', zIndex: 1})
           .appendTo($('#b70')).animate({bottom:'0px'},500);
});

This sets it 64px below (z-index places it above the checker pattern...I'd do this in CSS for all pieces and remove it here) then attaches it to the cell and animates back to a 0 bottom position.

The advantage here: This moves the piece to the new cell immediately while the animation finishes later, best for future events that check if the space is empty (e.g. a quick click after for another piece moving here).

Nick Craver
A: 

Well, the optional callback parameter is exactly for such situtions of sequential processing. Just a little correction: In cletus' code example the $("p80") has to be $("#p80").

efi