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.
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>
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.
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>
Whether it is a sample of code or it is the User's own information, we can create a copy button to copy data to the clipboard using the navigator. clipboard. writeText() function. This function writes the data fed to it as a parameter into the clipboard.
To paste the HTML source in rich content fields, click in the rich content toolbar to open the Source Code window. Paste the HTML source in the Source Code window and then click Save. Verify that the source code is clean before you paste it in the Source Code window.
With modern browsers, if you want copy rich text only, there is a very easy solution without using any packages. See http://jsfiddle.net/jdhenckel/km7prgv4/3
Here is the source code from the fiddle
<button onclick="copyToClip(document.getElementById('foo').innerHTML)"> Copy the stuff </button> <div id=foo style="display:none"> This is some data that is not visible. You can write some JS to generate this data. It can contain rich stuff. <b> test </b> me <i> also </i> <span style="font: 12px consolas; color: green;">Hello world</span> 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>
the function
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); };
⚠️ ClipboardEvent.clipboardData is experimental technology. Check the browser compatibility table in MDN (05-03-21)
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