I've used this method to copy rich text from an html element. The problem is that if styles are not inlined in the html, but come from css, this method doesn't work. The existing code breaks the formatting and doesn't take the styles into account. Here's the code.
HTML
<button onclick="copyToClip(document.getElementById('foo').innerHTML)">
Copy the stuff
</button>
<div id=foo>
You can write some JS to generate this data.
It can contain rich stuff.
<b> test </b> me <i> also </i>
<div class="green">Hello world</div> You can use setData to put TWO COPIES into the same clipboard, one that is plain and one that is rich. That way your users can paste into either a
<ul>
<li>plain text editor</li>
<li>or into a rich text editor</li>
</ul>
</div>
CSS
.green {
display: inline;
color: green;
}
JavaScript
function copyToClip(str) {
function listener(e) {
e.clipboardData.setData("text/html", str);
e.clipboardData.setData("text/plain", str);
e.preventDefault();
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
};
The example in Codepen.