Skip to content
Advertisement

How can I copy rich text contents to the clipboard with JavaScript?

Premise

I need help copying rich text to the clipboard using JavaScript. I have searched around and haven’t found anything to suit my specific needs.

Code

function ctrlA1(corp) {
  with(corp) {}
  if (document.all) {
    txt = corp.createTextRange()
    txt.execCommand("Copy")
  } else
    setTimeout("window.status=''", 5000)
}
<div id="sc1">hello <br> <b> world </b> </div>
<button onclick="ctrlA1(document.getElementById('sc1') )"></button>

Problem

The aforementioned code isn’t working and is resulting in an object expected error. Any help is appreciated! I have seen a library out there called zeroclipboard, but would prefer to write my own function.


Edit:

I now have this function to select text on the page. is it possible to write a formula to copy the selected range as is?

function containerSelect(id) {
  containerUnselect();
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(id);
    range.select();
  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(id);
    window.getSelection().addRange(range);
  }
}
<label onclick="containerSelect(this); select_all()">
  <p>hello world</p>
  <img src="imagepath.png">
</label>

Advertisement

Answer

i searched for a week now and finally found my answer!!! for those of you looking to copy rich text to the clipboard with javascript, then use the function at the link below, works like a charm. no need of flash and other stuff suggested 🙂

Copying an image to clipboard using JavaScript/jquery

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement