Skip to content

Instantly share code, notes, and snippets.

@olsgreen
Last active December 31, 2015 07:59
Show Gist options
  • Save olsgreen/7957448 to your computer and use it in GitHub Desktop.
Save olsgreen/7957448 to your computer and use it in GitHub Desktop.
Simple jQuery Table Sorter
/**
* Simple jQuery Table Sorter
*/
(function($){
$(document).ready(function(){
// Table Sorter
$('table.sortable').each(function () {
var n = 0,
tbl = $(this);
$(this).find('th').each( function() {
// Append the cell index and title
$(this).attr('data-header-id', $(this).html()).attr('data-cell-index', n);
// Add the default selector
if( 'asc' === $(this).data('sorted') ) {
$(this).html($(this).data('header-id') + ' ▲');
} else if( 'desc' === $(this).data('sorted') ) {
$(this).html($(this).data('header-id') + ' ▼');
}
// Sort on click
$(this).click(function() {
var sort_direction = 'asc';
function flipResult( r ) {
if( 'desc' === sort_direction ) {
return (r === 1) ? -1 : (r === -1) ? 1 : 0;
}
return r;
}
// Remove all other selected attrs
tbl.find('th').not(this).each(function() {
$(this).html($(this).data('header-id')).removeAttr('data-sorted');
});
// Either switch or add selected attr
if( 'asc' === $(this).data('sorted') ) {
$(this).data('sorted','desc');
sort_direction = 'desc';
$(this).html($(this).data('header-id') + ' ▼');
} else {
$(this).data('sorted','asc');
$(this).html($(this).data('header-id') + ' ▲');
}
// Remove elements and add to array
var rows = [],
index = $(this).data('cell-index');
tbl.find('tbody > tr').each(function() {
rows.push($(this).detach());
});
// Sort Array
rows = rows.sort(function(o1, o2) {
var c1 = o1.find('td').eq(index).html(),
c2 = o2.find('td').eq(index).html();
// Numeric remove £
if( '£' === c1.substr(0, 1) ) {
c1 = c1.substr(1);
c2 = c2.substr(1);
}
if( parseInt( c2 ) ) { // Numeric
return ('asc' === sort_direction ) ? c1 - c2 : c2 - c1;
} else { // String
return flipResult( (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0 );
}
});
// Reattach Elements
$.each(rows, function(k, row) {
tbl.find('tbody').append(row);
});
});
n++;
});
});
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment