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.
- It hooks into Highlight.js using the after:highlightElement plugin event.
- For each highlighted code block, it adds a small button in the top right corner.
- Clicking the button copies the code to your clipboard and briefly changes the label to “Copied.”
- No extra CSS or HTML markup.
- Automatically attaches to any code block Highlight.js processes.
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);
}
});