Created
January 30, 2024 12:42
-
-
Save nake89/da99121ef5557e99ea6ca3804e219d4f to your computer and use it in GitHub Desktop.
TLD Squatting - Sortable Table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name TLD Squatting - Sortable Table | |
// @namespace http://tampermonkey.net/ | |
// @version 2024-01-30 | |
// @description Ability to sort the table. | |
// @author nake89 | |
// @match https://captnemo.in/tld-squatting/ | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=captnemo.in | |
// @grant none | |
// ==/UserScript== | |
// Coded by nake89 (https://github.com/nake89) with the help of ChatGPT. | |
(function() { | |
'use strict'; | |
// Find the first table element on the page | |
let table = document.querySelector('table'); | |
// Create arrays to store header and body rows separately | |
let headerRow = []; | |
let bodyRows = []; | |
// Create an array to store the sorting order for each column | |
let sortingOrder = []; | |
// Check if a table was found | |
if (table) { | |
// Separate header and body rows | |
for (let i = 0; i < table.rows.length; i++) { | |
let rowArray = []; | |
for (let j = 0; j < table.rows[i].cells.length; j++) { | |
rowArray.push(table.rows[i].cells[j].textContent.trim()); | |
} | |
// Determine if it's the header row or a body row | |
if (i === 0) { | |
headerRow = rowArray; | |
// Initialize sorting order for each column to be ascending (1) | |
sortingOrder = Array(headerRow.length).fill(1); | |
} else { | |
bodyRows.push(rowArray); | |
} | |
} | |
// Add click event listeners to the header cells for sorting | |
for (let i = 0; i < headerRow.length; i++) { | |
let headerCell = table.rows[0].cells[i]; | |
headerCell.style.cursor = 'pointer'; | |
table.rows[0].cells[i].addEventListener('click', function () { | |
// Toggle sorting order for the clicked column | |
sortingOrder[i] *= -1; | |
// Sort the body rows based on the values in the clicked column | |
bodyRows.sort((a, b) => sortingOrder[i] * a[i].localeCompare(b[i])); | |
// Clear the existing table body content | |
let tbody = table.querySelector('tbody'); | |
if (tbody) { | |
tbody.innerHTML = ''; | |
} | |
// Populate the table body with the sorted body rows | |
for (let j = 0; j < bodyRows.length; j++) { | |
let newRow = tbody.insertRow(j); | |
for (let k = 0; k < bodyRows[j].length; k++) { | |
let newCell = newRow.insertCell(k); | |
newCell.textContent = bodyRows[j][k]; | |
} | |
} | |
}); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment