Home > Net >  Copy to clipboard does not work on several bulks of text
Copy to clipboard does not work on several bulks of text

Time:08-26

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 >
<span ><p>Text 1</p></span>
    <button > Copy </button>
    </div>
    <div >
    <span ><p>Text 2</p></span>  
    <button > Copy </button>
    </div>

CodePudding user response:

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 >
<span ><p>Text 1</p></span>
    <button > Copy </button>
    </div>
    <div >
    <span ><p>Text 2</p></span>  
    <button > Copy </button>
    </div>

  • Related