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>