I use this code to copy the text from ‘div1’ id to clipboard. It works but when i select other text in the page and tap the copy the text button it copies the selected text and not the div1 id text. I need every time to copy the div1 id text. What is wrong?
<?php
echo <div id="div2">
'<button class="btn-light" id="button1" onclick="CopyToClipboard(\'div1\')"
data-toggle="tooltip" title="Copy">Copy the text</button>
<div id="div1" > ';
echo "copy it";
echo '</div>';
echo '</div>';
?>
<script type='text/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("Copied")
</script>