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>
Both will works 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 copied")
}}
Also in html,
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<div id="div1" >Text To Copy </div>
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
Here is the snippet.
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 copied, copy in the text-area")
}
}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>
<div id="div1">Text To Copy </div>
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
Just to add to this answer, there is a neat plugin I've used a couple of times that can handle this: clipboardjs.com
1st One Is not Working
Please Tell Me How First Example Would Work
And I Have A Question, Will This Work On All Browser?
I hope it will do. Checked in firefox and chrome.