Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 768
Luis Gallego Avatar asked Apr 13 '14 21:04

Luis Gallego


People also ask

How do I transfer data to clipboard?

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.

How do you copy text from an element?

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.


1 Answers

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

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!

like image 167
Hani Avatar answered Sep 20 '22 02:09

Hani