Skip to content Skip to sidebar Skip to footer

How To Copy A Div's Content To Clipboard Without Flash

That's it :) I have a div with the id #toCopy, and a button with the id #copy. What's the best way to copy #toCopy content to clipboard when pressing #copy?

Solution 1:

You can copy to clipboard almost in any browser from input elements only (elements that has .value property), but you can't from elements like <div>, <p>, <span>... (elements that has .innerHTML property).

But I use this trick to do so:

  1. Create a temporary input element, say <textarea>
  2. Copy innerHTML from <div> to the newly created <textarea>
  3. Copy .value of <textarea> to clipboard
  4. Remove the temporary <textarea> element we just created

functionCopyToClipboard (containerid) {
  // Create a new textarea element and give it id='temp_element'const textarea = document.createElement('textarea')
  textarea.id = 'temp_element'// Optional step to make less noise on the page, if any!
  textarea.style.height = 0// Now append it to your page somewhere, I chose <body>document.body.appendChild(textarea)
  // Give our textarea a value of whatever inside the div of id=containerid
  textarea.value = document.getElementById(containerid).innerText// Now copy whatever inside the textarea to clipboardconst selector = document.querySelector('#temp_element')
  selector.select()
  document.execCommand('copy')
  // Remove the textareadocument.body.removeChild(textarea)
}
<divid="to-copy">
  This text will be copied to your clipboard when you click the button!
</div><buttononClick="CopyToClipboard('to-copy')">Copy</button>

Little late but hope that helps!

Solution 2:

The same without id:

functioncopyClipboard(el, win){
   var textarea,
       parent;

   if(!win || (win !== win.self) || (win !== win.window))
      win = window;
   textarea = document.createElement('textarea');
   textarea.style.height = 0;
   if(el.parentElement)
      parent = el.parentElement;
   else
      parent = win.document;
   parent.appendChild(textarea);
   textarea.value = el.innerText;
   textarea.select();
   win.document.execCommand('copy');
   parent.removeChild(textarea);
}

I didn't tested for different windows (iframes) though!

Solution 3:

UPDATED ANSWER Javascript was restricted from using the clipboard, early on. but nowadays it supports copy/paste commands. See documentation of mozilla and caniuse.com.

document.execCommand('paste')

make sure that you support browsers that don't.

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommandhttp://caniuse.com/#search=command

Javascript is not allowed to use the clipboard, but other plugins like flash do have access.

How do I copy to the clipboard in JavaScript?

Post a Comment for "How To Copy A Div's Content To Clipboard Without Flash"