Add a "Copy" button to every code block in your posts, so readers can copy code with one click.
document.addEventListener( 'DOMContentLoaded', () => {
document.querySelectorAll( 'pre > code' ).forEach( ( code ) => {
const pre = code.parentElement;
if ( pre.querySelector( '.nahnu-copy' ) ) {
return;
}
const button = document.createElement( 'button' );
button.type = 'button';
button.className = 'nahnu-copy';
button.textContent = 'Copy';
button.style.cssText = 'position:absolute;top:8px;right:8px;padding:4px 10px;border:0;border-radius:6px;background:#6F58CA;color:#fff;font:600 12px/1.4 system-ui,sans-serif;cursor:pointer';
button.addEventListener( 'click', async () => {
try {
await navigator.clipboard.writeText( code.innerText );
button.textContent = 'Copied!';
} catch ( error ) {
button.textContent = 'Press Ctrl+C';
}
setTimeout( () => {
button.textContent = 'Copy';
}, 2000 );
} );
pre.style.position = 'relative';
pre.appendChild( button );
} );
} );
Selecting code by hand is fiddly and often misses a line or grabs extra text. A copy button on each code block makes tutorials much easier to follow.
The script finds every <code> inside a <pre>, which is how the Code block, the Preformatted block and most syntax highlighters mark up code. It adds a small button in the top-right corner of each one.
Clicking copies the code’s text with the Clipboard API and shows “Copied!” for two seconds. If the browser blocks clipboard access, the button tells the reader to use Ctrl+C instead.
Add a Code block to a post and view it. A Copy button should appear in its corner; clicking it should copy the code.