JavaScript Copy Text in ClipBoard

The Following lets a button click cause text data to be pushed inside the clipboard. This is because direct access to clipboard from JavaScript is not possible for security reasons.

<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML>
   <HEAD>
      <TITLE>
         Copy Command
      </TITLE>
   </HEAD>
   <BODY>
      <script>
         //<![CDATA[
         function copy(){
         	 
         var textarea = document.createElement("textarea");

         var str = 
             ['One,One',
              'Two,Tow',
              'Three,Three',
              'Four,Four',
              'Five,Five',
             ].join('\n');
         
         
         textarea.value=str;
         textarea.setAttribute('id',"t1");
         document.body.appendChild(input);
         var input = document.getElementById("t1");
         input.focus();
         input.select();
         document.execCommand('copy');
         document.body.removeChild(input);
         
         }
         //]]>
      </script> 
      <button onclick="copy();" id="copy">copy</button>
   </BODY>
</HTML>

 

Tested on IE, FF and Chrome.

Please like & share:

Leave a Reply