Skip to content

Instantly share code, notes, and snippets.

@sawantuday
Created May 18, 2016 15:17
Show Gist options
  • Save sawantuday/2dd8eb284df9ec248eff2a7d06469899 to your computer and use it in GitHub Desktop.
Save sawantuday/2dd8eb284df9ec248eff2a7d06469899 to your computer and use it in GitHub Desktop.
Plain JavaScript based sorting for HTML tables. Source http://stackoverflow.com/questions/14267781/sorting-html-table-with-js
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<link rel="stylesheet" type="text/css" href="http://ak0.scstatic.net/1/cdn1.sweetcouch.com/shopify.css">
<style type="text/css">
table {width: 100%;font: 12px arial;}
th, td {min-width: 40px;text-align: center;}
th {font-weight: bold;}
</style>
<body>
<div style="width: 60%;padding-left: 100px;padding-top: 30px;">
<table>
<thead>
<tr>
<th>#</th>
<th>Store Domain</th>
<th>Count</th>
<th>Last updated</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>asdasd.com</td>
<td>4000</td>
<td>2015-06-20</td>
</tr>
<tr>
<td>1</td>
<td>qweqwe.com</td>
<td>6000</td>
<td>2015-06-20</td>
</tr>
<tr>
<td>1</td>
<td>werwer.com</td>
<td>3000</td>
<td>2015-06-20</td>
</tr>
<tr>
<td>1</td>
<td>twitter.com</td>
<td>1500</td>
<td>2015-06-20</td>
</tr>
<tr>
<td>1</td>
<td>sdfsdf.com</td>
<td>1050</td>
<td>2015-06-20</td>
</tr>
<tr>
<td>1</td>
<td>xcvxcvcx.com</td>
<td>1000</td>
<td>2015-06-20</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment