Here is my code for when the user clicks on this button:
<button id="button1">Click to copy</button>
How do I copy the text inside this div?
<div id="div1">Text To Copy</div>
Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top. Optionally, repeat step 2 until you've copied all the items you want to use. Tip: After you open the Clipboard, it stores content that you copy or cut from anywhere.
Just add the clipboard. js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.
see jsfiddle where you can enter html segment into the textarea and copy to the clipboard with ctrl+c.
I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work. After trying I got to:
<html> <body> <div id="a" onclick="copyDivToClipboard()"> Click to copy </div> <script> function copyDivToClipboard() { var range = document.createRange(); range.selectNode(document.getElementById("a")); window.getSelection().removeAllRanges(); // clear current selection window.getSelection().addRange(range); // to select text document.execCommand("copy"); window.getSelection().removeAllRanges();// to deselect } </script> </body> </html>
Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)
Update March 27th, 2019.
For some reason document.createRange()
didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0)
.
Both examples work like a charm :)
JAVASCRIPT:
function CopyToClipboard(containerid) { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select().createTextRange(); document.execCommand("copy"); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().addRange(range); document.execCommand("copy"); alert("Text has been copied, now paste in the text-area") } }
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button> <br /><br /> <div id="div1">Text To Copy </div> <br /> <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard
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