how to fix copy to clipboard bug in javascript?

Viewed 552

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

3 Answers

I think as you add href to your <a> the window does not clear all selected strings, and so it copies both values. I'm not sure how to fix this but here is a hack to it (add this code in the top of your CopyToClipboard(containerid) function):

if (window.getSelection().empty) {  // Chrome
  window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) {  // Firefox
  window.getSelection().removeAllRanges();
}

which as you know clear all text selections base on this link

Hope it helps.

I find the anyone's answer here

<script>

window.onload = function () {

    var copyTextareaBtn = document.querySelectorAll('.js-textareacopybtn');

    copyTextareaBtn.forEach(function(btn){
        btn.addEventListener('click', function (event) {
        var copyTextarea = document.getElementById(this.dataset.txtid);
        copyTextarea.select();

        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
                alert('Copying text command was ' + msg);
            } catch (err) {
                alert('Whoops, unable to copy');
            }
        })

    });
}

</script>

<p>Test #1 </p>

<div>
<textarea id="txta1" class="js-copytextarea" readonly="readonly" style="width:20%;" 
rows="5">Hello. This is textarea test bed #1</textarea>
<button data-txtid="txta1" class="js-textareacopybtn">Copy Text (works)</button>

<p>Test #2:</p>

<textarea id="txta2" class="js-copytextarea" readonly="readonly" style="width:20%;" 
rows="5">Hi! Welcome to textarea test bed #2 </textarea>
<button data-txtid="txta2" class="js-textareacopybtn">Copy Text</button>

</div>
Related