Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Data Attribute Sort

I'd like to sort DOM elements that has data attributes defined for rating and date. What is the best way to implement sorting on the front-end with jQuery?

Sample code can be seen on: http://jsfiddle.net/gercheq/zhqXd/

Here is the desired functionality implemented with tables: http://tablesorter.com/docs/

Thanks,

like image 867
Gerçek Karakuş Avatar asked Apr 06 '11 01:04

Gerçek Karakuş


2 Answers

There is a cool jQuery plugin that sorts DOM elements by attribute. You can find it here: http://tinysort.sjeiti.com/

Example implementation: http://jsfiddle.net/statico/JNFFj/7/

like image 98
Gerçek Karakuş Avatar answered Nov 14 '22 01:11

Gerçek Karakuş


Here is the basic idea...

var sortedSet = $('#sort li').toArray().sort(function(a, b) {
   return $(a).data('rating') - $(b).data('rating');
});

You select the elements, convert them to a proper array, and then sort (the comparison function I used is an example, change it to suit your requirements).

jsFiddle with lowest button.

like image 38
alex Avatar answered Nov 14 '22 00:11

alex