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 ?
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:
<textarea>
innerHTML
from <div>
to the newly created <textarea>
.value
of <textarea>
to clipboard<textarea>
element we just created function CopyToClipboard (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 clipboard const selector = document.querySelector('#temp_element') 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>
Little late but hope that helps!
The same without id:
function copyClipboard(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!
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/execCommand http://caniuse.com/#search=command
Javascript is not allowed to use the clipboard, but other plugins like flash do have access.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.