Skip to content

Instantly share code, notes, and snippets.

@mtranter
Created August 28, 2014 14:27
Show Gist options
  • Save mtranter/88e363590c4f2c4b132e to your computer and use it in GitHub Desktop.
Save mtranter/88e363590c4f2c4b132e to your computer and use it in GitHub Desktop.
(function($){
var opts_key = '_sorter_opts_';
var defaults = {
desc: false,
duration: 300
};
function orderNumbers(a,b){
return b - a;
}
function orderStrings(a,b){
return a.localCompare(b);
}
function order(a,b, desc){
if(isNaN(a) || isNaN(b)){
return orderStrings(a,b) * (desc ? 1 : -1);
}else{
return orderNumbers(a,b) * (desc ? 1 : -1);
}
}
function doMove(){
var $that = $(this);
var opts = $(this).data(opts_key);
var children = opts.childFinder.apply($that);
children.sort(function(a,b){
var keya = opts.keyFinder.apply($(a));
var keyb = opts.keyFinder.apply($(b));
$(a).css({top:$(a).position().top});
$(b).css({top:$(b).position().top});
return order(keya, keyb, opts.desc);
});
var height = 0;
var totalHeight = $(this).height();
var length = $(children).length;
$that.css({position: 'relative', height: totalHeight});
$(children).each(function(_,v){
$(v).css({position: 'absolute'})
.animate( {top: height }, opts.duration, null,
function(){
if(--length === 0){
$(children).appendTo($that).css({position: '', top:''});
}
});
height = height + $(v).outerHeight();
});
}
$.fn.sortElements = function(opts){
var settings = $.extend({}, defaults, opts);
$(this).data(opts_key, settings);
doMove.apply($(this));
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment