Skip to content

Add copy-to-clipboard button on all code blocks #10

Description

@sridhar-3009

Feature request

Several topic pages have inline <code> and block <pre><code> snippets (SQL, schemas, commands). Add a small "Copy" button that copies the code to the clipboard.

Behavior

  • Button appears in the top-right corner of each <pre> block on hover
  • On click: copies text to clipboard via navigator.clipboard.writeText()
  • Button label changes to "Copied!" for 1.5 seconds, then resets
  • Fallback for browsers without Clipboard API: select the text with document.createRange()

Implementation (add to js/main.js)

document.querySelectorAll('pre').forEach(function(pre) {
  const btn = document.createElement('button');
  btn.className = 'copy-btn';
  btn.textContent = 'Copy';
  pre.style.position = 'relative';
  pre.appendChild(btn);
  btn.addEventListener('click', function() {
    navigator.clipboard.writeText(pre.querySelector('code').innerText).then(function() {
      btn.textContent = 'Copied!';
      setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
    });
  });
});

CSS (add to css/style.css)

.copy-btn {
  position: absolute; top: 8px; right: 8px;
  font-size: 11px; padding: 2px 8px; border-radius: 4px;
  background: var(--surface-3); border: 1px solid var(--border);
  color: var(--text-soft); cursor: pointer; opacity: 0;
  transition: opacity 0.2s;
}
pre:hover .copy-btn { opacity: 1; }

Difficulty: Beginner — DOM manipulation + Clipboard API

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions