Skip to content

Instantly share code, notes, and snippets.

@crdrost
Created April 3, 2012 10:09
Show Gist options
  • Save crdrost/2290811 to your computer and use it in GitHub Desktop.
Save crdrost/2290811 to your computer and use it in GitHub Desktop.
Hacker News Comment Hiding
// ==UserScript==
// @name Hacker News Comment Hiding
// @namespace http://drostie.org/
// @include https://news.ycombinator.com/item?id=*
// @include http://news.ycombinator.com/item?id=*
// ==/UserScript==
function repeat(element, selector, n) {
return n <= 0 ? element : repeat(element[selector], selector, n - 1);
}
var comments_hidden = "\u25B9", // unicode: "white right-pointing small triangle"
comments_shown = "\u25BF"; // unicode: "white down-pointing small triangle"
function indent_level(block) {
return block === null ? -1 : repeat(block, 'firstChild', 6).width;
}
[].forEach.call(document.getElementsByClassName("comment"), function (comment) {
var block = repeat(comment, 'parentNode', 6),
indent_comment = indent_level(block),
ratings = comment.parentNode.previousSibling.firstChild,
showing = true,
link = document.createElement("a"),
child_blocks = [];
block = block.nextSibling;
while (indent_level(block) > indent_comment) {
child_blocks.push(block);
block = block.nextSibling;
}
// logic should work, but don't display the link if no children
if (child_blocks.length === 0) {
return;
}
link.setAttribute("href", "#");
link.innerHTML = comments_shown;
link.onclick = function () {
if (showing) {
child_blocks.forEach(function (c) {
if (!c.hidden_by) {
c.hidden_by = comment;
c.style.display = "none";
}
});
link.innerHTML = comments_hidden;
showing = false;
} else {
child_blocks.forEach(function (c) {
if (c.hidden_by === comment) {
c.hidden_by = undefined;
c.style.display = "block";
}
});
link.innerHTML = comments_shown;
showing = true;
}
return false;
};
ratings.appendChild(document.createElement("br"));
ratings.appendChild(link);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment