Created
April 19, 2011 01:23
-
-
Save davatron5000/926629 to your computer and use it in GitHub Desktop.
jQuery.sortByData
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
/* | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sweet! thanks for the help!