← All examples

JavaScript Productivity stackoverflow.com

Stack Overflow: add a copy-code button

Adds a small "Copy" button to every code block that copies the whole content to the clipboard in one click.

Code to copy

/* Add a "Copy" button to every code block */
(function () {
  function addButtons() {
    document.querySelectorAll('.s-prose pre, .js-post-body pre').forEach(function (pre) {
      if (pre.dataset.sofCopy) return;
      pre.dataset.sofCopy = '1';
      pre.style.position = 'relative';
      var btn = document.createElement('button');
      btn.textContent = 'Copy';
      btn.style.cssText = 'position:absolute;top:6px;right:6px;font-size:11px;padding:2px 8px;cursor:pointer;border:1px solid #aaa;border-radius:4px;background:#fff;z-index:5;';
      btn.addEventListener('click', function () {
        var code = pre.querySelector('code') || pre;
        navigator.clipboard.writeText(code.innerText).then(function () {
          btn.textContent = 'Copied!';
          setTimeout(function () { btn.textContent = 'Copy'; }, 1500);
        });
      });
      pre.appendChild(btn);
    });
  }
  addButtons();
  new MutationObserver(addButtons).observe(document.body, { childList: true, subtree: true });
})();

How to use this example

  1. Copy the code with the button above.
  2. Install JustZix (2 minutes) and open the extension on the target page.
  3. Add a new rule matching that page.
  4. Paste the code into the rule's JavaScript panel and save — it runs on every page visit.

Rate this example

No ratings yet — be the first.

Does this example work?

Snippets are useless without somewhere to paste them.

JustZix takes 2 minutes to install and runs your code on every matching page. No account, no payment.

Download free See use cases