Skip to content

Instantly share code, notes, and snippets.

@knbknb
Last active November 30, 2023 19:17
Show Gist options
  • Save knbknb/e537a50af2a7be9a0f3fe404415a5725 to your computer and use it in GitHub Desktop.
Save knbknb/e537a50af2a7be9a0f3fe404415a5725 to your computer and use it in GitHub Desktop.
(JS, defunct) Sketch of a Browser userscript for news.ycombinator.com
// ==UserScript==
// @name HN Comment Collapse/Expd Button Injector
// @version 1
// @grant none
// @namespace http://userscripts.org/people/14536
// @description Toggle all comments from collapsed to expanded state
// @match https://news.ycombinator.com/*
// @author Knut Behrends, ChatGPT
// ==/UserScript==
(function() {
// Function to collapse all comments
function collapseAllComments() {
document.querySelectorAll("#hnes-comments > div header .collapser").forEach(elem => elem.click());
}
// Function to expand all comments
function expandAllComments() {
// You can replace this with the logic to expand all comments if it's different from the collapse logic
// document.querySelectorAll("#hnes-comments > div header .collapser").forEach(elem => elem.click());
//
document.querySelectorAll("#hnes-comments > div header .collapser:not(section.replies .collapser)").forEach(elem => elem.click());
}
// Function to inject the "Collapse all" button
function injectButton() {
// Find the target element where the button should be appended
let targetElem = document.querySelector("tr#content form");
if (!targetElem) {
targetElem = document.querySelector("table.fatitem tr:last-of-type");
if (!targetElem) {
console.warn("Target element not found!");
return;
}
}
// Create the "Collapse all" button
let button = document.createElement("button");
button.innerText = "Collapse all";
button.style.marginTop = "25px"; // Add some margin for better spacing
// Add click event listener to the button
button.addEventListener("click", function(event) {
event.preventDefault(); // Prevent any default button actions
if (button.innerText === "Collapse all") {
collapseAllComments();
button.innerText = "Expand all";
} else {
expandAllComments();
button.innerText = "Collapse all";
}
});
// Append the button to the target element
targetElem.appendChild(button);
}
// Execute the main logic
injectButton();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment