Skip to content

Instantly share code, notes, and snippets.

@dunhamsteve
Created December 3, 2013 19:42
Show Gist options
  • Save dunhamsteve/7776187 to your computer and use it in GitHub Desktop.
Save dunhamsteve/7776187 to your computer and use it in GitHub Desktop.
Quick and dirty sortable table for javascript. (I wrote this to embed in a single page html report.)
function sortedTable(id) {
var table = document.getElementById(id);
table.lastColumn = -1;
table.onclick = function(ev) {
if (ev.target.nodeName == 'TH') {
var row = ev.target.parentNode;
for (var j=0;j<row.cells.length;j++) {
if (row.cells[j] == ev.target) {
var rows = [];
for (var i=1;i<table.rows.length;i++) {
rows.push(table.rows[i]);
}
if (j == table.lastColumn) {
rows.reverse();
} else {
rows.sort(function(a,b) { return a.cells[j].textContent.localeCompare(b.cells[j].textContent) });
}
table.lastColumn = j;
for (var i=0;i<rows.length;i++) {
table.appendChild(rows[i]);
}
break;
}
}
}
return true;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment