You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
1.1 KiB
30 lines
1.1 KiB
window.onload = function() { |
|
var arrows, headers, header; |
|
|
|
headers = document.getElementsByTagName("th"); |
|
|
|
for (var g = 0; g < headers.length; g++) { |
|
arrows = document.createElement('a'); |
|
arrows.href = "#"; |
|
arrows.className = "sort-by"; |
|
headers[g].appendChild(arrows); |
|
headers[g].onclick = sortTable(g); |
|
headers[g].onkeypress = sortTable(g); |
|
} |
|
} |
|
|
|
function sortTable(n) { |
|
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent; |
|
|
|
const comparer = (idx, asc) => (a, b) => ((v1, v2) => |
|
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2) |
|
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx)); |
|
|
|
// do the work... |
|
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => { |
|
const table = th.closest('table'); |
|
Array.from(table.querySelectorAll('tr:nth-child(n+2)')) |
|
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc)) |
|
.forEach(tr => table.appendChild(tr)); |
|
}))); |
|
} |