GenovSvetoslav

Tiny Highlight.js Addon for Copy-to-Clipboard Functionality

If you use Highlight.js to format code snippets on your site, you’ve probably wished for a simple way to add a “Copy” button to each block. No dependencies, no extra libraries — just a small addon that works instantly after highlighting.

Here’s the entire script:

hljs.addPlugin({
  "after:highlightElement": ({ el: codeElement, text: codeText }) => {

    // Use the <pre> parent as the container
    const preElement = codeElement?.parentElement;

    // Avoid adding multiple buttons
    if (!preElement || preElement.copyButton) return;

    // Ensure the parent is positioned relatively
    preElement.style.position = "relative";

    // Create the copy button
    const copyButton = document.createElement("button");
    preElement.copyButton = copyButton;
    copyButton.textContent = "Copy";
    copyButton.style.cssText = "position:absolute;top:6px;right:6px;z-index:1;padding:4px 8px;border:0;background:#000;color:#fff;cursor:pointer";

    // Copy functionality
    copyButton.onclick = () => {
      navigator.clipboard.writeText(codeText).then(() => {
        copyButton.textContent = "Copied";
        setTimeout(() => (copyButton.textContent = "Copy"), 3000);
      });
    };

    // Append the button to the <pre> block
    preElement.appendChild(copyButton);

  }
});