I have a situation where my script works perfectly fine when I click a single button to copy text to the clipboard. However, when I try to implement multiple buttons for copying different pieces of text, it doesn't seem to work as intended.
Can someone please help me figure out what is causing this issue? How can I modify my script to allow for functionality with more than one button and text?
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>