Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

“Copy” button on code blocks

Code blocks in your posts get a small Copy button that copies the code to the clipboard. Great for tutorial sites.

  • Type JavaScript
  • Runs Public site, before </body>
  • Category Design
  • Tested with WordPress 7.1
JavaScript
document.querySelectorAll( '.entry-content pre, .wp-block-post-content pre, pre.wp-block-code' ).forEach( function ( pre ) {
	if ( pre.dataset.snipfireCopy || ! navigator.clipboard ) {
		return;
	}
	pre.dataset.snipfireCopy = '1';
	pre.style.position = 'relative';
	var button = document.createElement( 'button' );
	button.type = 'button';
	button.textContent = 'Copy';
	button.setAttribute( 'style', 'position:absolute;top:6px;right:6px;font:12px/1.2 system-ui,sans-serif;padding:4px 8px;border:1px solid currentColor;border-radius:4px;background:transparent;color:inherit;opacity:.75;cursor:pointer' );
	button.addEventListener( 'click', function () {
		navigator.clipboard.writeText( pre.innerText.replace( /\nCopy$|\nCopied$/, '' ) ).then( function () {
			button.textContent = 'Copied';
			setTimeout( function () { button.textContent = 'Copy'; }, 1500 );
		} );
	} );
	pre.appendChild( button );
} );

Good to know

Translate “Copy” and “Copied” if your site isn’t in English.

In these packs

  • Design touches: Small front-end touches: a reading progress bar, an announcement bar, a WhatsApp button, accessibility fixes.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.