Cosmochen
Cosmochen

Reputation: 61

Copy to clipboard does not work on several bulks of text

I have a script I use where I click a button and a text is copied to the clipboard. However, this scrips does not seem to work when I have several buttons supposed to work on several pieces of text.

What am I doing wrong? How can I get this to work with two or more buttons/ texts?

var copyBtn = document.querySelector('.js-copybtn');
if (copyBtn) {
    copyBtn.addEventListener('click', function(event) {
        var copyText= document.querySelector('.js-copytext');
        var range = document.createRange();
        range.selectNode(copyText);
        window.getSelection().addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
        } catch(err) {

        }
        window.getSelection().removeAllRanges();
    });
}  
<div class="context">
<span class="js-copytext"><p>Text 1</p></span>
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>
    <div class="context">
    <span class="js-copytext"><p>Text 2</p></span>  
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>

Upvotes: 1

Views: 28

Answers (1)

Naren Murali
Naren Murali

Reputation: 56763

You can get all the buttons and attach the click event, then on the button, we just need to get the previous sibiling, which we can access with the property previousElementSibling after that the logic works fine.

var copyBtns = document.querySelectorAll('.js-copybtn');
if (copyBtns && copyBtns.length) {
copyBtns.forEach((copyBtn) => {
    copyBtn.addEventListener('click', function(event) {
    console.log(copyBtn);
        var copyText= copyBtn.previousElementSibling;
        var range = document.createRange();
        range.selectNode(copyText);
        window.getSelection().addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
        } catch(err) {

        }
        window.getSelection().removeAllRanges();
    });
});
}
<div class="context">
<span class="js-copytext"><p>Text 1</p></span>
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>
    <div class="context">
    <span class="js-copytext"><p>Text 2</p></span>  
    <button class="btn btn-default js-copybtn CP"> Copy </button>
    </div>

Upvotes: 2

Related Questions