Copy code from a code box to Clipboard with a button just using Javascript

January 17, 2018 January 19, 2018


A button to Copy code from a code box to the Clipboard is very useful for your blog. You can copy code just with one simple step.

DEMO

Fearture

- Pure lightweight Javascript ( without Jquery Library)
- No need to replace published post
- Very easy to install and use

Install

Attent that your code in blog post should be put between tag:
<pre><code>
Your code here...
</code></pre>

1. Add CSS

<style type='text/css'>
.tncodebox{padding-top:11px;position:relative;border: 1px solid #ddd;margin: 10px 0;}
#resultcopied{position:fixed;top:30%;left:45%;z-index:2;background:#00ad62;color:#fff;padding:10px}
.tnbtn{position:absolute;top:0;right:0;padding:2px 5px;;border-style:none;border-radius:2px;cursor:pointer;outline:none}
.resultshow{-o-transition:opacity .5s;-moz-transition:opacity .5s;-webkit-transition:opacity .5s;transition:opacity .5s;opacity:1}
.resulthide{opacity:0}
pre{overflow:auto;max-height: 400px;margin-top:15px;border-top: 1px solid #ddd;background:#eee;}
pre,code {font-family: consolas,Monaco,'Andale Mono',monospace;}
code {background: #eee;padding: 2px 6px;}
        </style>

2. Add Javscript

Put following code before </body>:

<b:if cond='data:view.isSingleItem'>
<script>
//<![CDATA[ 
var str=document.body.innerHTML;document.body.innerHTML=str.replace(/(\<pre\>)/gi,"<div class='tncodebox'><pre class='tncode'>").replace(/(\<\/pre\>)/gi,"$1<span class='tnbtn'>Copy</span></div>");var list=document.getElementsByClassName("tncode");for(var i=0;i<list.length;i++){list[i].id="box"+(i+1)}var list2=document.getElementsByClassName("tnbtn");for(var j=0;j<list.length;j++){list2[j].id="display(simplecopy(document.getElementById('box"+(j+1)+"').innerHTML));blogazwin()"}var str2=document.body.innerHTML;document.body.innerHTML=str2.replace(/span\sclass\=\"tnbtn\"\sid/gi,"span class='tnbtn' onclick");var simplecopy=function(){var d=document,b,cs,ss,f=false,n=d.createElement("DIV"),s=n.style;s.position="fixed";s.color="rgba(0,0,0,0)";function sc(t){if(!b){b=d.body};n.innerHTML=t;b.appendChild(n);ss=x(n);cs=d.execCommand("copy",f,null);b.removeChild(n);return ss&&cs};function x(n){var r,s,w=window.getSelection,c=b.createTextRange;if(c){r=c();r.moveToElementText(n);r.select();return!f}else if(w){s=w();r=d.createRange();r.selectNodeContents(n);s.removeAllRanges();s.addRange(r);return!f}else{return f}}return sc}();function display(result){};var result11div=document.createElement('div');result11div.id='resultcopied';result11div.className='resulthide';document.getElementsByTagName('body')[0].appendChild(result11div);result11div.innerHTML="Copied!";function blogazwin(){var div2=document.getElementById("resultcopied");div2.className="resultshow";setTimeout(function(){div2.className='resulthide'},500)};
//]]>
</script>
</b:if>
Done!

0 comments for Copy code from a code box to Clipboard with a button just using Javascript