Skip to content

Instantly share code, notes, and snippets.

@davatron5000
Created April 19, 2011 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davatron5000/926629 to your computer and use it in GitHub Desktop.
Save davatron5000/926629 to your computer and use it in GitHub Desktop.
jQuery.sortByData
/*
* SortByData
* Copyright 2011 Dave Rupert
* www.daverupert.com
*
* Version 1.0 - Updated: Apr. 18, 2011
* Requires jQuery 1.5+
*
* This Plug-In sorts a list of of elements by any HTML5 data-attribute you specify.
* It can also handle doing that by ASC or DESC order.
*
* This jQuery plug-in is dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Sample Usages:
* $("ul#videos").sortByData('ranking'); // Will sort a list videos by their `data-ranking` attribute. Defaults to 'DESC' (highest to lowest).
*
* $("div#muppets").sortByData('created', 'ASC'); // Will sort sub-Divs of each muppet by the year they were created in their `data-created` attribute. Specified 'ASC' to sort lowest to highest.
*/
(function($) {
$.fn.sortByData = function( metadata, order ) {
var order = order || "";
return this.each(function() {
$( $(this).children().toArray().sort(function(a, b) {
if(order.toLowerCase() == 'asc') {
return $(a).data( metadata ) - $(b).data( metadata );
} else {
return $(b).data( metadata ) - $(a).data( metadata );
}
}) ).appendTo($(this));
});
};
})(jQuery);
@md2perpe
Copy link

md2perpe commented May 4, 2011

Normal JS style is
var order = order || "";
instead of
var order = order ? order : "";

@davatron5000
Copy link
Author

sweet! thanks for the help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment