Skip to content

Code Blocks with Highlighting: Copy to Clipboard

Posted in Plugin Development, and WP Plugins

Welcome back to our Code Block with Highlighting series, where we are creating a plugin to allow for custom code blocks with syntax highlighting via PrismJS. If you have not already read and completed the first article in our series, you will want to finish that first before coming here. If you’ve already completed the first article, then you’re ready to begin!

Using:

Adding a Copy To Clipboard Button

We will be using ClipboardJS today, along with some custom jQuery script to add a copy to clipboard button to every post. This does not use any Flash hacks, as these are no longer reliable.

Step 1: Grab your copy of ClipboardJS

We’ll start by grabbing a copy of the ClipboardJS library. Just head over to their site, and download the official zip file via their Github page. Once you extract this file, navigate to the dist folder, and copy clipboard.min.js to your plugin’s /js/ folder.

Step 2: Build Custom jQuery to add a “Copy” button to each code snippet.

Create a new JS file called clipboard-setup.js.

jQuery('pre.copytoclipboard').each(function () {
            $this = jQuery(this);
            $button = jQuery('<button class="copytoclipboard-button"></button>');
            $this.wrap('<div/>').removeClass('copytoclipboard');
            $wrapper = $this.parent();
            $wrapper.addClass('copytoclipboard-wrapper').css({position: 'relative', padding: 20});
            $button.css({position: 'absolute', top: 0, right: 0}).appendTo($wrapper).addClass('copytoclipboard btn btn-default');
            var copyContentsToClipboard = new Clipboard('button.copytoclipboard', {
                target: function (trigger) {
                    return trigger.previousElementSibling;
                }
            });
            copyContentsToClipboard.on('success', function (event) {
                event.clearSelection();
                event.trigger.textContent = '✓';
                window.setTimeout(function () {
                    event.trigger.textContent = '';
                }, 2000);
            });
            copyContentsToClipboard.on('error', function (event) {
                event.trigger.textContent = 'Press "Ctrl + C" to copy';
                window.setTimeout(function () {
                    event.trigger.textContent = '';
                }, 2000);
            });
        });

Let’s break this down:

  • Lines 2-14 look for every <pre> element with a class of copytoclipboard, and then create an instance of the Clipboard object from ClipboardJS. This is then used to create a button that floats in the top right corner of your codeblock.
  • The remainder of the lines handle the message on the button, including both success and failures. The timeout functions return the text to the initial message: Copy.

Step 3: Update prism-js.php

Once you’ve copied both clipboard.min.js and clipboard-setup.js to your js folder, it’s time to update prism-js.php with your new file enqueues.

The highlighted lines, 20-21 are the ones that have changed, under our function prism_js_enque_script():

<?php
/**
* Plugin Name: Prism JS Loader
* Plugin URI: https://www.wptechguides.com
* Description: A Custom Code Syntax Highlighter
* Version: 0.1
* Author: Dan D
* Author URI: https://www.convexcode.com
**/


//enqueues all css files needed
function prism_js_enqueue_style() {
	wp_enqueue_style( 'prism-style', plugin_dir_url( __FILE__ ) . 'css/prism.css', false ); 
}

//enqueues all js files needed
function prism_js_enqueue_script() {
	wp_enqueue_script( 'prism-js', plugin_dir_url( __FILE__ ) . 'js/prism.min.js', false ); 
	wp_enqueue_script( 'clipboard-js', plugin_dir_url( __FILE__ ) . 'js/clipboard.min.js', false ); 
	wp_enqueue_script( 'clipboard-setup-js', plugin_dir_url( __FILE__ ) . 'js/clipboard-setup.js', '','',true ); 
}
add_action( 'wp_enqueue_scripts', 'prism_js_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'prism_js_enqueue_script' );

Step 4: Custom Styling

You may want to do some custom styling of your copy button. I’ve included my modifications here. These affect the color, padding, positioning, background, hover, etc. When the button is created, the class copytoclipboard is moved to the button, and we’ve added a custom class copytoclipboard-button, so that is what we’ll be targeting. I chose to add these to my prism.css file, but you could always enqueue these as a separate file.

.copytoclipboard-button {
	
	background: url('https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-copy-outline-32.png'); 
	background-size: cover;
	background-color: lightgreen;
	border: none;
    color: black;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    
	margin-left:20px;
	margin-right:20px;
	border-top-left-radius:0.6em;
	border-top-right-radius:0.6em;
	font-weight:bold;
	min-width:30px;
	min-height:30px;
    cursor: pointer;	
}

.copytoclipboard-button:hover{

	background-color: orange;

}

Current Plugin Tree:

prism-js/
|-- css
|	|-- index.php
|	`-- prism.css
|-- index.php
|-- js
|	|-- clipboard.min.js
|	|-- clipboard-setup.js
|	|-- index.php
|	`-- prism.min.js
`-- prism-js.php

 

Step 5: Testing and Other Considerations

Everything should be ready to go! Time to give it a spin! To test, just add the class copytoclipboard to the <pre> element of any existing code block.

Note: If you use Autoptimize (or similar plugin) to combine Javascript files, you may need to manually exclude clipboard.min.js to to allow the copy to clipboard functionality to work.

That’s all for this time! Next time, we’ll take a look at adding custom shortcodes so you don’t have to write out your pre and code tags each time.

Source(s): 

Next in Series: Code Blocks with Highlighting: Adding Custom Shortcodes (Optional)