Nathan Friend
Nathan Friend

Reputation: 12814

Moving a jQuery draggable() element to a new parent

I'm writing a simple card game in JavaScript, and I'd like to have a "card" img snap to its target when played. I'm accomplishing this by removing the img from its current parent and placing it in a new parent (the target). However, when I place the img in its new container with jQuery's .appendTo(), the card snaps to the corner of the screen.

See this demo for a working example.

Is there a reason the div snaps to the corner of the screen when it's moved to a new parent? I'm wondering if there are css properties that are being inherited/lost behind the scenes when I change the div's parent.

Any help would be appreciated.

- EDIT -

Additional information: while it has been suggested that I simply add this to my drop handler (which works) -

$(ui.draggable).css({'top' : '0', 'left' : '0'});

I'd like to .animate() to this position, so the snap isn't instantaneous. While the card does end up in the correct spot, it first snaps to the corner and then eases into the correct position. I'd like to avoid that first snap to the corner.

Upvotes: 3

Views: 3541

Answers (1)

Brandon
Brandon

Reputation: 3494

$(ui.draggable).css({'top' : '0', 'left' : '0'});

Sorry, I had to leave for work, but try this:

$("#target").droppable({
    drop: function (event, ui) {
      var offset = $('#target').offset()
      var top = parseInt($(ui.draggable).css('top')) - offset.top;
      var left = parseInt($(ui.draggable).css('left')) - offset.left;            
      $(ui.draggable).appendTo("#target");
      $(ui.draggable).css({'top' : top, 'left' : left})
      $(ui.draggable).animate({
        top: 0,
        left: 0           
      }, 500, function() {
        // Animation complete.
      });
    }
});

http://jsfiddle.net/hsjvP/22/

Upvotes: 5

Related Questions