Hosted by
dotmaui.com
|
Download
-
Raw
See original
/** * Licensed under the MIT license. * https://opensource.org/licenses/MIT * * Orderfy - jQuery plugin * @author .Maui * @link https://dotmaui.com/ * @version 0.3 * @desc A small script that sorts DOM elements within common parent. */ (function($) { $.fn.orderBy = function(orderby, _options) { var defaults = { order: "asc", parent: null, onTopIfValue: null, onBottomIfValue: null, isOrderedByAttr: false }; var options = $.extend(defaults, _options); var elements = []; var elements_top = []; var elements_bottom = []; var is_all_numeric = true; var $parent = (options.parent == null) ? $(this).parent() : options.parent; $(this).each(function() { var order_value; if ($.trim(orderby) == "") { order_value = $(this).text(); } else if (options.isOrderedByAttr) { order_value = $(this).find(orderby).attr(orderby.substr(1, orderby.length - 2)); } else { order_value = $(this).find(orderby).html(); } order_value = $.trim(order_value); if (options.onTopIfValue != null && options.onTopIfValue == order_value) { elements_top.push({ element: $(this), value: order_value }); } else if (options.onBottomIfValue != null && options.onBottomIfValue == order_value) { elements_bottom.push({ element: $(this), value: order_value }); } else { if (isNaN(order_value)) { is_all_numeric = false; } elements.push({ element: $(this), value: order_value }); } }); if (options.order == "asc") { if (is_all_numeric) { elements.sort(function(a, b) { return a.value - b.value; }); } else { elements.sort(function(a, b) { if (a.value < b.value) return -1; if (a.value > b.value) return 1; return 0; }); } } else if (options.order == "desc") { if (is_all_numeric) { elements.sort(function(a, b) { return a.value - b.value; }); } else { elements.sort(function(a, b) { if (a.value > b.value) return -1; if (a.value < b.value) return 1; return 0; }); } } __DetachAppend(elements_top, $parent); __DetachAppend(elements, $parent); __DetachAppend(elements_bottom, $parent); }; function __DetachAppend(elements, $parent) { $(elements).each(function() { var elm = $(this)[0].element; $(elm).detach().appendTo($parent); }); } })(jQuery);