Vanilla JavaScript Projects

Project 87, Content and data

Threaded Comments

A comment section people enjoy using. Reply to a reply, like the best answers, fix a typo in your own comment and collapse long threads.

Main API
Intl.RelativeTimeFormat
Save
localStorage
Dependencies
None
Your browser
Checking

Join the discussion

Write a comment, reply to someone, like and sort. Your own comments can be edited or deleted. Everything is saved in your browser.

0 / 600

    How it works

    1. Comments are a treeEach comment has a list of replies, which have their own replies. One recursive function draws the whole tree, up to three levels deep.
    2. Friendly timesIntl.RelativeTimeFormat turns timestamps into 5 hours ago or yesterday, in the visitor's language.
    3. Keep threads readableDeleting a comment with replies leaves a placeholder so the conversation still makes sense. Long threads can be collapsed.
    function render(comments, depth = 1) {
      return "<ul>" + comments.map((c) => `
        <li><b>${c.who}</b> <time>${ago(c.time)}</time>
          <p>${escape(c.text)}</p>
          ${depth < 3 ? `<button data-reply="${c.id}">Reply</button>` : ""}
          ${c.replies.length ? render(c.replies, depth + 1) : ""}
        </li>`).join("") + "</ul>";
    }
    const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
    rtf.format(-1, "day"); // "yesterday"