How to copy div contents to clipboard without flash

What is it :) I have a div with id #toCopy and a button with id #copy . What is the best way to copy the contents of #toCopy to the clipboard when pressing #copy ?

+8
javascript jquery html copy
source share
2 answers

UPDATED Javascript RESPONSE was limited to using the clipboard at an early stage. but it currently supports copy / paste commands. See the documentation for mozilla and caniuse.com.

document.execCommand('paste') 

make sure you support browsers that don't.

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

Javascript does not allow the use of the clipboard, but other plugins, such as flash, have access.

How to copy to clipboard in javascript?

-3
source share

You can copy to the buffer in almost any browser only from input elements (elements with the .value property), but you cannot use elements such as <div> , <p> , <span> ... (elements that have the property .innerHTML ).

But I use this trick for this:

  • Create a temporary input element, say <textarea>
  • Copy innerHTML from <div> to the newly created <textarea>
  • Copy .value from <textarea> to the clipboard
  • Delete the temporary <textarea> element that we just created.

 function CopyToClipboard(containerid) { // Create a new textarea element and give it id='t' let textarea = document.createElement('textarea') textarea.id = 't' // 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 clipboard let selector = document.querySelector('#t') selector.select() document.execCommand('copy') // Remove the textarea document.body.removeChild(textarea) } 
 <div id="to-copy"> This text will be copied to your clipboard when you click the button! </div> <button onClick='CopyToClipboard("to-copy")'>Copy</button> 

A bit late, but hope this helps!

+26
source share

All Articles