Kyle
Kyle

Reputation: 67194

jQuery "stacking" divs (like Lego)

I've been working on something fun, stacking my divs like lego. I've been able to get it to stack once using appendTo and positioning, but if you click more than once the divs appear in an unexpected (to me) place!

You can see what I mean here: jsfiddle example. (You can click the red div to remove the stacked divs)

Is there a way to make the divs stack exactly like the first one, "on top" of each other like a tower of legos?

Thanks :)

Upvotes: 1

Views: 587

Answers (2)

Andreas Wong
Andreas Wong

Reputation: 60526

var lastPos = [-4, -3];
$('.cube, .cubeStack').click( function() {
    lastClicked = $('<div class="cubeStack"></div>')
       .css({top:lastPos[0], left:lastPos[1]})
       .appendTo($(this));

    lastPos[0] -= 1;
    lastPos[1] -= 1;
});
  • Set .cubeStack position to absolute
  • Decrement each time you add a new stack

http://jsfiddle.net/Dk585/8/

P.S. I found it rather cute actually <3

Upvotes: 2

Sven Bieder
Sven Bieder

Reputation: 5681

Far "stacking" the divs on top of each other use prependTo(). The difference is that appendTo() adds the element as last child and prependTo() add the element as first child to the element.

Upvotes: 0

Related Questions