POOLab18-SlopifyV2/res/template/base.js

58 lines
1.4 KiB
JavaScript

function initTable(table) {
table.tHead.querySelectorAll("th").forEach((header, i) => {
header.addEventListener("click", () => {
toggleSort(table, header, i)
})
})
}
function toggleSort(table, header, colI) {
if (header.classList.contains("sort-asc")) {
header.classList.remove("sort-asc")
header.classList.add("sort-desc")
doSort(table, colI, true)
} else if (header.classList.contains("sort-desc")) {
header.classList.remove("sort-desc")
header.classList.add("sort-asc")
doSort(table, colI, false)
} else {
table.tHead.querySelectorAll("th.sort-asc,th.sort-desc").forEach(th => {
th.classList.remove("sort-asc")
th.classList.remove("sort-desc")
})
header.classList.add("sort-asc")
doSort(table, colI, false)
}
}
function doSort(table, colI, desc = false) {
let swapped = true
while (swapped) {
let rows = Array.from(table.rows)
swapped = false
let rowA, rowB
for (let i=1; i<rows.length-1; i++) {
rowA = rows[i]
rowB = rows[i+1]
if (desc == compareRows(rowA, rowB, colI)) {
swapped = true
break
}
}
if (swapped) {
rowA.parentNode.insertBefore(rowB, rowA)
}
}
}
function compareRows(rowA, rowB, colI) {
let valA = rowA.querySelectorAll("td")[colI].innerText
let valB = rowB.querySelectorAll("td")[colI].innerText
if (!Number.isNaN(+valA) && !Number.isNaN(+valB)) {
valA = +valA
valB = +valB
}
return valB > valA
}