Slide up, sort, slide down
Demonstrates traversal of DOM in jquery, animation, delaying continuation until animation of multiple elements have completed, sorting elements, and forcing divs to remain at their starting size while their children are resized.
by doug65536
HTML
<div class="productlist" id="list1">
<button> Sort this list</button>
<div class="product" id="one">
<h2>zzProduct1 (click me to check event handler)</h2>
Im product One
</div>
<div class="product" id="two">
<h2>rrProduct2</h2>
Im product Two
</div>
<div class="product" id="three">
<h2>aaProduct3</h2>
Im product Three
</div>
</div>
<div class="productlist" id="list2" style="margin-top:3em;">
<button> Sort this list </button>
<div class="product" id="four">
Im product Four
</div>
</div>
JavaScript
$(function() {
$('#one').on('click', function() {
alert('you clicked zzProduct1');
});
$('button').on('click', function(ev) {
var button = $(ev.target);
var list = button.closest('.productlist');
var listheight = list.height();
list.css({position: 'relative', height: listheight+'px' });
var divs = list.find('div');
divs.slideUp('fast');
divs.promise().done(function() {
divs = divs.detach();
divs.sort(function(a,b) {
var h2_1 = $(a).find('h2').text();
var h2_2 = $(b).find('h2').text();
//return h2_1 < h2_2 ? -1 : h2_1 > h2_2 ? 1 : 0;
if (h2_1 < h2_2) {
return -1;
}
if (h2_1 > h2_2) {
return 1;
}
return 0;
});
list.append(divs);
divs.slideDown();
divs.promise().done(function() {
list.css({position: '', height: ''});
});
});
});
});