Question 9 Drag and Drop then Sort
Create a drag and drop region where user can drag numbers into the box and see them automatically sorted.
by cassfinn
HTML
<p>
Drag the number into the box to sort:
</p>
<ul id="sortable1" class="connectedSortable ui-helper-reset">
</ul>
<ul id="sortable2" class="connectedSortable ui-helper-reset">
<li class="ui-state-highlight">23</li>
<li class="ui-state-highlight">51</li>
<li class="ui-state-highlight">9</li>
<li class="ui-state-highlight">12</li>
<li class="ui-state-highlight">71</li>
</ul>
CSS
#sortable1 {
margin: 12px 12px 12px 12px;
height: 80px;
width: 410px;
background-color: #dedede;
}
#sortable2 {
margin: 20px 20px 20px 20px;
height: 120px;
width: 410px;
background-color: #fff;
}
#sortable1 li {
margin: 10px 10px 10px 10px;
padding: 10px;
font-size: 1.2em;
width: 40px;
height: 40px;
border: 1px solid black;
background: red;
display: inline-block;
text-align: center;
font-family: 'verdana, sans-serif';
}
#sortable2 li {
margin: 12px 12px 12px 12px;
padding: 5px;
font-size: 1.2em;
width: 40px;
height: 40px;
border: 1px solid black;
background: red;
display: inline-block;
text-align: center;
vertical-align: middle;
font-family: 'verdana, sans-serif';
}
p {
font-family: Arial, Helvetica, sans-serif;
margin: 16px 16px 16px 16px;
}
JavaScript
$("#sortable1, #sortable2").sortable({
connectWith: '.connectedSortable, #trash'
}).disableSelection();
$("#sortable1").droppable({
accept: ".connectedSortable li",
hoverClass: "ui-state-hover",
drop: function(ev, ui) {
ui.draggable.remove();
if($(this).find(".placeholder").length>0) //add first element when cart is empty
{
$(this).find(".placeholder").remove();
$("<li></li>").text(ui.draggable.text()).appendTo(this);
}
else
{
var i=0;
$(this).children('li').each(function()
{
var text = parseInt($(this).text());
var textDrag = parseInt(ui.draggable.text());
if( textDrag < text) {
$("<li></li>").text(ui.draggable.text()).insertBefore($(this));
i=1;
return false; // break
}
})
if(i!=1) //if number dropped at the end
{
$("<li></li>").text(ui.draggable.text()).appendTo(this);
}
}
}
});