Created
August 28, 2014 14:27
-
-
Save mtranter/88e363590c4f2c4b132e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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