refactor: Re-usable table sorting

Relates-to: [EM-8]
main
earnest ma 2 weeks ago
parent 8187234fba
commit 0657fbb671
Signed by: earnest ma
GPG Key ID: A343F43342EB6E2A
  1. 40
      assets/tablecolsort.js
  2. 51
      layouts/recipes/single.html

@ -0,0 +1,40 @@
window.sortTable = function(table, n){
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
// table = document.getElementById("recipesAll");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
};

@ -12,9 +12,9 @@
<p><i>Columns can be clicked to sort!</i></p>
<table id="recipesAll">
<tr>
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Category</th>
<th onclick="sortTable(2)">Date</th>
<th onclick="window.sortTable(recipesAll, 0)">Name</th>
<th onclick="window.sortTable(recipesAll, 1)">Category</th>
<th onclick="window.sortTable(recipesAll, 2)">Date</th>
</tr>
{{ range .Site.Data.recipes.all }}
<tr>
@ -25,47 +25,6 @@
{{ end }}
</table>
</content>
<script>
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("recipesAll");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
</script>
{{- $tablecolsort := resources.Get "/tablecolsort.js" | js.Build "/tablecolsort.js" | fingerprint }}
<script src="{{ $tablecolsort.Permalink }}"></script>
{{ end }}

Loading…
Cancel
Save