Last active
August 29, 2015 14:02
-
-
Save yangacer/9d9c53896f7ec0a754e5 to your computer and use it in GitHub Desktop.
Mini sort table with jquery
This file contains hidden or 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 sortable(table_dom, column_types, default_ordering) { | |
var rows = $(table_dom).find('tbody tr') | |
var dataset = []; | |
for (var i = 0; i < rows.length; ++i) { | |
var vals = $(rows[i]).find('td').toArray().map(function(v){ | |
// console.log(arguments); | |
return v.innerText; | |
}); | |
dataset.push(vals); | |
} | |
function make_comparator(offset, column_type, ordering) { | |
switch(column_type) { | |
case 'n' : | |
if(ordering == 'asc') { | |
return function(x, y) { | |
return x[offset] - y[offset]; | |
} | |
} else { | |
return function(x, y) { | |
return y[offset] - x[offset]; | |
} | |
} | |
break; | |
case 's': | |
if(ordering == 'asc') { | |
return function(x,y) { | |
if(x[offset] > y[offset]) return 1; | |
if(x[offset] < y[offset]) return -1; | |
return 0; | |
} | |
} else { | |
return function(x,y) { | |
if(x[offset] > y[offset]) return -1; | |
if(x[offset] < y[offset]) return 1; | |
return 0; | |
} | |
} | |
break; | |
} | |
} | |
function populate() { | |
$(table_dom).find('tbody tr').each(function(row_index, row){ | |
$(row).find('td').each(function(col_index, cell) { | |
$(cell).text(dataset[row_index][col_index]); | |
}); | |
}); | |
} | |
var ordering_ = { a: 'asc', d: 'desc' }; | |
function make_sort_by(index, ele) { | |
return $(ele).click(function(){ | |
var col = $(this); | |
var ord_orig = col.attr('data-sort-order') ; | |
var ord_new; | |
if ( ord_orig ) { | |
ord_new = (ord_orig == 'asc') ? 'desc' : 'asc'; | |
dataset.reverse(); | |
} else { | |
ord_new = ordering_[default_ordering[index]]; | |
// clear other columns' data-sort-order attrib | |
col.parent().find('th').not(col).removeAttr('data-sort-order'); | |
// sort table | |
dataset.sort(make_comparator(index, column_types[index], ord_new)); | |
} | |
col.attr('data-sort-order', ord_new); | |
populate(); | |
}); | |
}; | |
return $(table_dom).find('thead th').map(make_sort_by); | |
} | |
sortable('table', 'nss', 'daa'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment