Skip to content

Instantly share code, notes, and snippets.

@knbknb
Created August 21, 2024 20:51
Show Gist options
  • Save knbknb/b4b641dd3e51bb5fa46f074ec2c3f6c8 to your computer and use it in GitHub Desktop.
Save knbknb/b4b641dd3e51bb5fa46f074ec2c3f6c8 to your computer and use it in GitHub Desktop.
Hacker News Collapse Button
// ==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(event) {
if(event.detail === 1){
document.querySelectorAll("#hnes-comments > div header .collapser").forEach(elem => elem.click());
}
}
// Function to expand all comments
function expandAllComments(event) {
// You can replace this with the logic to expand all comments if it's different from the collapse logic
if (event.detail === 2 || event.key === "x") {
document.querySelectorAll("#hnes-comments > div header .collapser").forEach(elem => elem.click());
} else if(event.detail === 1){
document.querySelectorAll("#hnes-comments > div header .collapser:not(section.replies .collapser)").forEach(elem => elem.click());
}
}
// Function to inject the "Collapse all" button
function injectButton(event) {
// 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(event);
button.innerText = "Expand all";
} else {
expandAllComments(event);
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