0

I am trying to write a Solitaire card game in Javascript. For dragging and dropping the cards I use jQueryUI. As shown in http://jsfiddle.net/HY8g7/1/ you can drag cards to the column where you stack the cards in a Solitaire game.

Here comes the problem. Say I have all three cards stacked in one column: card 1, card 2 and card 3 each on top of each other. When I drag card 1, card 2 and 3 also need to follow card 1 when dragging around etc.

In order to achieve this I have already tried to make each successor card a child of the previous card. Unfortunately this method causes lots of DOM manipulation and dragging does not work as expected.

When I move a card to an invalid droppable it should be moved back to its original position which I now achieve with:

$('.card').draggable({
    revert: 'invalid'
});

This should still work when I move a stack of cards around.

Does anyone have an idea what could be a clean approach to drag the pile of cards around, when picked at an arbitrary point?

Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91

2 Answers2

1

It turned out the most efficient approach was to use the DOM to nest the cards as show in this Fiddle: http://jsfiddle.net/HY8g7/3/

card.detach()
    .appendTo(cardsInColumn.last());

This code adds the card to the last card of the row. When a parent is dragged the children are coming along automatically without the need to handle coordinates of each card manually.

Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
0

You could use jQuery's next() - jQuery Next Function. Then using a click event you could simply get the next siblings and then use the position of the dragged card to align the other cards below it. Since when you stack the cards they are aligned in the DOM as you see them.

Div#1 gets dragged/dropped and then DIv#2 gets placed on top, and so on. So then you would use the click event to target one of the DIV's and if it has siblings grab those and position them with the card that's being dragged.

user1470118
  • 412
  • 2
  • 9
  • 24
  • I tried this, but it causes a problem with reverting. When an invalid move has been made jQuery moves only the original item back and not the siblings. – Bas van Dijk Jul 28 '14 at 21:06
  • If you see this http://stackoverflow.com/questions/14571919/adding-a-function-to-jquery-draggable-revert-event question it talks about adding a function to the revert option. You could add a function in where that returns true if it's an invalid drop and will also trigger the siblings to return to the original position. - Here is the JSFiddle from the discussion http://jsfiddle.net/mori57/Xpscw/ – user1470118 Jul 28 '14 at 21:14