Copy to Clipboard in pure javascript

copy to clipboard helps a user to quickly copy some particular text clicking on a button. Nowadays It’s a good user experience to avoid CTRL + C or right click open context menu and click copy.

Earlier we had to use some flash plugin to use this feature into a web app. The accessing clipboard was not enabled due to security reason. Now some modern browser supports document.execCommand() key method. In this tutorial, we’ll implement copy to the clipboard using few lines of pure javascript code, no jQuery, no flash .

<div class="item">
  <p class="copy-area">Hello You can copy this area.</p>
  <button class="btn-copy">Copy to clipboard</button>
<div class="item">
  <textarea rows="10" cols="25" class="copy-area">Hello You can copy this text.</textarea>
  <button class="btn-copy">Copy to clipboard</button>

First we are selecting each item using document.querySelectorAll(‘.item’) , looping through each items and calling a function copyToClipBoard( — ) sending element object.

clicking on the button we are fetching copy text and selecting.

var copyArea = item.querySelector('.copy-area');
var range = document.createRange(); 

for selecting each chracter we have used javascript Range api (Check MDN reference).

Now execute copy command with javascript and Boom!

var copyStatus = document.execCommand('copy');  // copy/paste/cut

Done, Now you can paste this text to anywhere. make sure after copy deselects the text using

Now here is consolidated javascript code. This code has been tested in Chrome 50, IE 11 and Firefox 46.

var items = document.querySelectorAll('.item'), i;   //selecting all container has class .item
for (i = 0; i < items.length; ++i) {  // loop through each item and calling copyToClipBoard  function
function copyToClipBoard(item) {
  var btnCopy = item.querySelector('.btn-copy');   // selecting copy button for this item
  btnCopy.addEventListener('click', function(event) {  // attaching click event
    var copyArea = item.querySelector('.copy-area');  // selecting copy area for this item
    var range = document.createRange(); 
    window.getSelection().addRange(range);  // select the text
    try { 
      // execute the copy command  on selected the text in copy area
      var copyStatus = document.execCommand('copy'); 
      var msg = copyStatus ? 'copied' : 'failed'; 
      console.log(msg);  // console the copy status
    } catch(error) { 
      console.log('Oops!, unable to copy'); 
    window.getSelection().removeAllRanges();  // remove the selection


  • Indira Agarwal

    Can you please release as a standalone javascript plugin?