Sergi Sergi - 1 month ago 15
jQuery Question

Draggable elements to stack into droppable container(bottom to top)

When I drag my draggable elements (clones) into a droppable container, they stack from top to bottom, is there a way to invert that? I have tried adding a relative position to the parent element, and a "position:absolute;bottom:0" to the dragabble, but it doesn't work properly as then they all stay on the exact same position, so they don't stack on top of each other.

The code and a JSFiddle example:

https://jsfiddle.net/f3gzrtar/

HTML:

<div class="containtment">

<div class="cube">
</div>

<div class ="makeMeDroppable">
</div>

</div> <!--containtment-->


CSS:

.containtment {
height: 600px;
width: 600px;
border: 1px solid;
}

.cube {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
display: block;
margin: 1%;
}

.cube.ui-draggable-dragging {
background: green;
}

.draggableHelper {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
display: block;
}

.makeMeDroppable {
float: right;
width: 200px;
height: 300px;
border: 1px solid #999;
position: relative;
overflow: hidden;
}


JS:

$(document).ready(function() {

$('.cube').draggable({
containment: "parent",
cursor: 'move',
helper: myHelper,
})

function myHelper() {
return '<div class="draggableHelper"></div>';
}

$('.makeMeDroppable').droppable({
drop: handleDropEvent
});

function handleDropEvent(event, ui) {
var draggable = ui.draggable;
$(".makeMeDroppable").append("<div class='cube'></div>")
}
});

Answer

Based on this answer you can use display: table-cell and vertical-align: bottom to stack divs from the bottom. Note that using float: right on the drop container means this won't work however. You need an additional surrounding element like in this fiddle

Alternatively you could use flexbox if you don't care about some older browsers by doing:

.makeMeDroppable {
  display: flex;
  float: none;
  width: 200px;
  height: 300px;
  border: 1px solid #999;
  position: relative;
  overflow: hidden;
  justify-content: flex-end;
  flex-direction: column;
}

flex fiddle