Home / Copy Button for Code Blocks
Duplicate Snippet

Embed Snippet on Your Site

Copy Button for Code Blocks

Add a button to easily copy to clipboard for code blocks.

<10
Code Preview
html
<script type="text/javascript">
	document.addEventListener( 'DOMContentLoaded', function () {
		document.querySelectorAll( 'pre > code' ).forEach( function ( codeBlock ) {
			var copyButton = document.createElement( 'button' );
			copyButton.textContent = 'Copy';
			copyButton.classList.add( 'copy-button' );
			codeBlock.parentNode.insertBefore( copyButton, codeBlock );
			copyButton.addEventListener( 'click', function () {
				var code = codeBlock.textContent;
				navigator.clipboard.writeText( code ).then( function () {
					copyButton.textContent = 'Copied!';
					setTimeout( function () {
						copyButton.textContent = 'Copy';
					}, 2000 );
				}, function ( err ) {
					console.error( 'Could not copy text: ', err );
					copyButton.textContent = 'Error';
					setTimeout( function () {
						copyButton.textContent = 'Copy';
					}, 2000 );
				} );
			} );
		} );
	} );
</script>
<style>
	.copy-button {
		background-color: #f0f0f0;
		border: 1px solid #ccc;
		border-radius: 4px;
		padding: 5px 10px;
		cursor: pointer;
		font-size: 0.8em;
		position: absolute;
		top: 0.5em;
		right: 0.5em;
	}
	pre {
		position: relative;
	}
</style>

Comments

Add a Comment