blob: a18bf6cf5b82762fe3fca88634694b6d55bacc61 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
// copy-code.js
(function() {
// Add copy button to all code blocks
const codeBlocks = document.querySelectorAll('pre, .highlight');
codeBlocks.forEach(block => {
// Create copy button
const btn = document.createElement('button');
btn.className = 'code-copy-btn';
btn.textContent = 'copy';
btn.type = 'button';
btn.setAttribute('aria-label', 'Copy code');
// Get code text
const code = block.querySelector('code');
const text = code ? code.textContent : block.textContent;
// Copy on click
btn.addEventListener('click', async function() {
try {
await navigator.clipboard.writeText(text);
// Show feedback
const originalText = btn.textContent;
btn.textContent = 'copied!';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = originalText;
btn.classList.remove('copied');
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
btn.textContent = 'error';
}
});
// Add button to block
block.style.position = 'relative';
block.appendChild(btn);
});
})();
|