I have this CLICK TO COPY code that would help you copy a text to clipboard. How do I create multiple instances of this different CLICK TO COPY on same page.
Here is the code I have already.
<p><strong>NOTE:</strong> Ensure you properly copy text:</p>
<input type="text" value="12sDKsfHXYFKKshjBQZEVmQo4EBmDBvzY7" id="myInput" readonly><br><br>
<div class="tooltip">
<button onclick="myFunction()" onmouseout="outFunc()">
<span class="tooltiptext" id="myTooltip">Copy to clipboard</span>
Copy Address
</button>
</div>
<script>
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
var tooltip = document.getElementById("myTooltip");
//tooltip.innerHTML = "Copied: " + copyText.value;//
tooltip.innerHTML = "Copied: ";
}
function outFunc() {
var tooltip = document.getElementById("myTooltip");
tooltip.innerHTML = "Copy to clipboard";
}
</script>
I try to add in more instances of the code to be able to create more CLICK TO COPY buttons on the same page by changing the text value But it keeps selecting only the first text.
If you remove the ID attributes and assign a common parent to the elements shown here you can use other DOM navigation techniques to identify pieces of code quite easily.
The HTML from the original is wrapped in a span - the span will not affect presentation but allows use to access the parentNode property of an element and from there other selections can be made.
document.querySelectorAll('.tooltip button').forEach(bttn=>bttn.addEventListener('click',function(e){
/* within this function `this` refers to the button */
let input=this.parentNode.parentNode.querySelector('input');
input.select();
input.setSelectionRange(0, input.value.length);
document.execCommand('copy');
this.parentNode.innerHTML="Copied: " + input.value;
}))
div.copy{
display:inline;
}
<div class='copy'>
<p><strong>NOTE:</strong> Ensure you properly copy text:</p>
<input type="text" value="12sDKsfHXYFKKshjBQZEVmQo4EBmDBvzY7" readonly />
<div class="tooltip">
<button>
<span class="tooltiptext">Copy to clipboard</span>
</button>
</div>
</div>
<div class='copy'>
<p><strong>NOTE:</strong> Ensure you properly copy text:</p>
<input type="text" value="12sDKsfsdfsdfHXghjghjVmQo4EBmDBvzY7" readonly />
<div class="tooltip">
<button>
<span class="tooltiptext">Copy to clipboard</span>
</button>
</div>
</div>
<div class='copy'>
<p><strong>NOTE:</strong> Ensure you properly copy text:</p>
<input type="text" value="1xxxswerHXYFKKshj56fgh8Qo4EBmDBvzY7" readonly />
<div class="tooltip">
<button>
<span class="tooltiptext">Copy to clipboard</span>
</button>
</div>
</div>