JSFiddle - React, Tailwind, and code Playground

by jairajdesai

HTML

<table>
	<thead>
		<tr>
			<th>Name</th>
			<th>Times</th>
			<th>Count</th>
			<th>Size</th>
			<th>Info</th>
		</tr>
	</thead>

	<tbody>
		<tr>
			<td>Mike</td>
			<td>15</td>
			<td>42314</td>
			<td>29</td>
			<td>stuff</td>
		</tr>

		<tr>
			<td>Great</td>
			<td>10</td>
			<td>7558</td>
			<td>43</td>
			<td>info</td>
		</tr>

		<tr>
			<td>Mitch</td>
			<td>20</td>
			<td>7841</td>
			<td>129</td>
			<td>stuff</td>
		</tr>

		<tr>
			<td>Leslie</td>
			<td>25</td>
			<td>16558</td>
			<td>423</td>
			<td>info</td>
		</tr>
	</tbody>
</table>

CSS

table {width: 100%;font: 12px arial;}
th, td {min-width: 40px;text-align: center;}
th {font-weight: bold;}
td:hover::after, thead th:not(:empty):hover::after {
    content:'';
    left: 0;
    width: 100%;
    z-index: -1;
}
td:hover::after, th:hover::after {
    background-color: #348A75;
}

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
        
        
        if(!isNaN(a.cells[col].textContent) && !isNaN(b.cells[col].textContent))
        return reverse * ((+a.cells[col].textContent) - (+b.cells[col].textContent))
       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();};