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?
Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.
The function copies the visible text of the element to the clipboard. This works as if you had selected the text and copied it with ctrl+c. Use the parameter "id" to select the element you want to 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 createdfunction 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With