Using the following code I have a function that copies a specified elements text range, however if I have multiple on the same page and try to use both buttons to copy different elements it always only pastes the first one you clicked.
Not sure if I explained that well so here's an example:
A = abc
B = xyz
Button1 = CopyToClipboard('A')
Button2 = CopyToClipboard('B')
//If I clicked button1 then button2 I would get the contents of button1 (abc).
Both buttons work but after you click one you can't copy another.
HTML:
<div>
<a id="A">abc</a>
</div>
<div>
<a href="javascript:void(0);" onclick="CopyToClipboard('A')">COPY</a>
</div>
<div>
<a id="B">xyz</a>
</div>
<div>
<a href="javascript:void(0);" onclick="CopyToClipboard('B')">COPY</a>
</div>
JS:
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");
}
}
Edit: Link to code snippet: https://plnkr.co/edit/z5bCymHPgEdTQhYShlMR?p=preview