jQury UI Sortable
by tjnicolaides
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<div class="demo">
<ul data-sortable-th>
<li data-sort-key="1" class="th-stacked">Name</li>
<li data-sort-key="2" class="th-stacked">Position</li>
<li data-sort-key="3" class="th-stacked">Office</li>
<li data-sort-key="4" class="th-stacked">Age</li>
<li data-sort-key="5" class="th-stacked">Start Date</li>
<li data-sort-key="5" class="th-stacked">Salary</li>
</ul>
</div>
<button data-reverse-order>Reverse order
</button>
<button data-randomize-order>Random order
</button>
SCSS
.th-stacked {
border: 2px solid #ddd;
background: #eee;
margin: .5em;
padding: 1em;
font: 16px Arial, sans-serif;
cursor: move;
}
button {
margin: .5em;
}
JavaScript
var $ul = $("[data-sortable-th]");
// sort the list manually with drag-and-drop or use one of the buttons to simulate a programmatic sort action coming from another script
$ul.sortable().on('sortupdate', function() {
var data = $(this).sortable('toArray', {
attribute: 'data-sort-key'
});
// console the order of the sortable child elements when a sortupdate is triggered
console.log(data);
}).disableSelection();
$('[data-reverse-order]').on('click', function() {
$ul.children().each(function(i, $li) {
$ul.prepend($li)
});
$ul.trigger('sortupdate');
});
$('[data-randomize-order]').on('click', function() {
$ul.randomize('[data-sort-key]');
$ul.trigger('sortupdate');
});
$.fn.randomize=function(a){(a?this.find(a):this).parent().each(function(){$(this).children(a).sort(function(){return Math.random()-0.5}).detach().appendTo(this)});return this};