clipboard.js in hugo

a modern approach to copy text to clipboard in hugo

1 minute read Published:


Clipboard.js in hugo

clipboard.js lets you easily copy text to the clipboard. With no need for Flash, it’s a great lightweight way to allow your visitors to copy code snippets on your site.

It’s a perfectly combination with a syntax highlighting library like rainbows or highlightjs.

In this short tuto i implemented clipboard.js in my template bulma for hugo.

Installation for hugo project

Get the package from a third-party CDN provider and place the clipboard.min.js file manually in your static js folder. Then include the JavaScript file in any of your layouts files :

<script async type="text/javascript" 
src="{{ .Site.BaseURL }}/js/clipboard.min.js"></script>

Finally, you’ll want to instantiate it. It this example we’re instantiating all pre elements :

 /* * clipboard
for hugo * clip.js */ 

(function(document, Clipboard) {

    var $codes = document.querySelectorAll('pre');

    function addCopy(element) {
        var copy = document.createElement("button");
        copy.className = "copy button is-pulled-right";
        copy.textContent = "copy";
        element.append(copy);
    }

    for (var i = 0, len = $codes.length; i < len; i++) {
        addCopy($codes[i]);
    }


    new Clipboard('.copy', {
        target: function(trigger) {
            return trigger.previousElementSibling;
        }
    });
})(document, Clipboard);

See how it look :

Published by in js and tagged clipboard, hugo and javascript using 179 words.

comments powered by Disqus