Use copy to clipboard button in Ghost

When reading posts about technical features it is nice if you are able to follow along and experiment. Copy to clipboard button for snippets is a useful feature that helps following along.

In the official Ghost blog it is suggested to use PrismJS.

In order to use the copy to clipboard button we need to load both the core plugin and the clipboard add-on. Since I was looking for simply using the clipboard function it seemed unreasonable to load both.

So after checking how it actually works we do not need the PrismJS at all. We can use clipboard.js directly.

You can use this unofficial repository with CDN to find the appropriate library. Next you can initialize the script by adding the following snippet:

    jQuery(document).ready(function() {
        if(ClipboardJS !== "undefined") {
            new ClipboardJS('.btn', {
                target: function(trigger) {
                    return trigger.nextElementSibling;
                }
            });
        }
    }

After you have included the library and initialized the script you can use the copy to clipboard functionality by simply adding the data-clipboard-text attribute with any value to the element.

    

Sample text that will be copied to clipboard after clicking the below!

Copy!

Try clicking on Copy and you will copy the above text into clipboard. We have 2 elements. The first paragraph is the text we want to copy. The second element is trigger element. Once you click on the trigger element there are 2 data attributes in action:

  • data-clipboard-target - this will know which element to copy
  • data-clipboard-action - this will initiate the copy action

Everything else is handled in clipboard.js library. This is quite handy and can be used in lots of ways.

In the following articles we will inspect how to style this properly and dynamically apply the button to your code snippets. Additionally we will explore how to add code blocks and proper highlighting into your posts.

p.s.

You will notice that after clicking on copy the text turns to Copied and then back to Copy. This can be achieved by clipboard events. We are listing to success event and changing the text, then after 2 seconds we change it back.

clipboard.on('success', function(e) {
        jQuery(e.trigger).text("Copied!");
        e.clearSelection();
        setTimeout(function() {
          $(e.trigger).text("Copy");
        }, 2000);
});