Sunday, July 28, 2019

How to set up copy code buttons in the blog

One of the quick answer is using Clipboard.js


Step 1: Call the online library directly. Type the following line before </head> in the Theme HTML,

<script src='https://cdn.staticfile.org/clipboard.js/1.5.15/clipboard.min.js' type='text/javascript'/>

One way to test whether the online library still work or not, just type in the address in search engine. 

step 2: Initialize the clipboard. Type the following line before </body>  in the Theme HTML

 style="background-color: whitesmoke; border-radius: 4px; border: 1px solid rgb(204, 204, 204); box-sizing: border-box; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; line-height: 1.42857; margin-bottom: 10px; overflow-wrap: break-word; overflow: auto; padding: 9.5px; word-break: break-all;"><script>
    var clipboard = new Clipboard('.btn');
    clipboard.on('success', function(e) {
        console.log(e);
    });
    clipboard.on('error', function(e) {
        console.log(e);
    });
</script>

Now move to the post HTML,

Step 3: Place the code to be copied between <div1> and  </div1> in the post HTML

Step 4: Set up the copy button by the following line,

<button class="btn" data-clipboard-action="copy" data-clipboard-target="div1">copy code</button>

Done.
A good resource can be found here,

http://www.webkaka.com/blog/archives/clipboard-no-flash.html

No comments:

Post a Comment