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 ?
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?
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 ).
.value
<div>
<p>
<span>
.innerHTML
But I use this trick for this:
<textarea>
innerHTML
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!