I’m trying to create a number of buttons on my site to copy respective texts to clipboard, but all the buttons seem to be copying the last text.
I used a different id
attribute for each text to be copied and a matching id
attribute in the JavaScript getElementById()
area for that text.
I’m thinking maybe I need to use unique onclick()
functions for each of them instead of copyClipboard()
for all of them.
P.S: I’m not a programmer, I’m more of a script kiddie.
Here is the code I used…
(Both buttons end up copying the second text. I want each button to copy its respective text.)
<script>
function copyClipboard() {
var copyText = document.getElementById("one").innerHTML;
var input = document.createElement("input");
input.value = copyText;
document.body.appendChild(input);
input.select();
document.execCommand("copy");
document.body.removeChild(input);
}</script>
<button onclick="copyClipboard()">copy</button>
<p id="one">first</p>
<script>
function copyClipboard() {
var copyText = document.getElementById("two").innerHTML;
var input = document.createElement("input");
input.value = copyText;
document.body.appendChild(input);
input.select();
document.execCommand("copy");
document.body.removeChild(input);
}</script>
<button onclick="copyClipboard()">copy</button>
<p id="two">second</p>
2
Answers
The following will copy text to the clipboard – hope it helps.
First,
addEventListener
should be preferred over the old inline event handler method. You could apply event delegation by listening for click events on the document (or the closest static ancestor of all the buttons you need to handle) and checking for a button that is followed by a paragraph element.navigator.clipboard.writeText
can be used for simpler copying.The snippet below is a simple implementation of this idea. Note that it does not work here because of the Stack Snippets permissions policy.