So this is the scenario – you have this text on your website and would like to have a button that would allow the visitor to copy the text into clipboard using one click, without requiring them to select the text manually. Thankfully, there is a clipboard.js library, allowing us to perform different kinds of scenarios easily. Let me show you one of the examples, implemented into WordPress.
If you check the clipboard.js website, it says “No dependencies”. This means that we will not have to add jQuery or any other library for clipboard.js to work (although in WordPress case, this is no big deal because most websites load jQuery anyway, with or without the reason to do so 🙂 ).
So let’s load the main library file:
1 2 3 4 5 6 |
add_action('wp_enqueue_scripts', 'load_clipboard_script'); function load_clipboard_script() { wp_enqueue_script('clipboard', get_stylesheet_directory_uri() . '/js/clipboard.min.js'); } |
The next step is to initialize new object like this:
1 2 3 4 5 6 7 8 9 |
var clipboard = new Clipboard('.copy-letter-button'); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); }); |
I like to keep things in their own script files, so we need to enqueue this one as well:
1 2 3 4 |
function load_clipboard_initialize_script() { wp_enqueue_script( 'clipboard-initialize', get_stylesheet_directory_uri() . '/js/clipboard.footer.js', array(), '1.0.0', true); } add_action( 'wp_enqueue_scripts', 'load_clipboard_initialize_script' ); |
For my own convenience, I set this script to load in footer, hence the “true” keyword.
And now we need some HTML:
1 2 3 4 5 |
<button class="copy-letter-button" data-clipboard-action="copy" data-clipboard-target="#copyme">South Tyrol</button> <div id="copyme"> South Tyrol (occasionally South Tirol) is the term most commonly used in English for the province, and its usage reflects that it was created from a portion of the southern part of the historic County of Tyrol. German and Ladin speakers usually refer to the area as Südtirol; the Italian equivalent Sudtirolo (sometimes spelled Sud Tirolo) is becoming increasingly common </div> |
You can easily recognize .copy-letter-button class, which connects the button with clipboard object, while data-clipboard-target does the rest. As you can see in my example, it needs to match the <div> or any other element with corresponding ID which contains the text you want to have copied into clipboard. Also, data-clipboard-action can be set to either cut or copy, but cut will work only on some form elements <textarea> e.g).
Make sure you check my Codepen example to see this in action.