Click here to Skip to main content
15,302,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to change the button that is clicked to 'COPIED!'. However, only the 1st button works. The other buttons don't change to 'COPIED!' after clicking.

The issue lies in the last part of the code. However, I can't seem to get around it.

Any help is appreciated.

Code:

HTML
<pre><div id="test"></div>


JavaScript
const alphabet1 = ["Λ", "B", "C", "D", "E"];

let txt2 = "ΛΛ";
let final = "";

// loop to add all the possible version of writing the word consisting ΛΛ ('_ΛΛ_ _')
for (let i = 0; i < alphabet1.length; i++) {
  for (let j = 0; j < alphabet1.length; j++) {
    for (let k = 0; k < alphabet1.length; k++) {
      final += "<button onclick=\"copy(this)\"><span id=\"copied\">" + alphabet1[i] + txt2 + alphabet1[j] + alphabet1[k] + "</span></button>";
    }
  }
}
document.getElementById("test").innerHTML = final;

// copies text to clipboard
function copy(that) {
  var inp = document.createElement("input");
  document.body.appendChild(inp)
  inp.value = that.textContent
  inp.select();
  document.execCommand("copy", false);
  inp.remove();
}

// changes the text to COPIED! on click for 1000ms
document.getElementById("copied").addEventListener("click", function(clicked) {
  return function() {
    if (!clicked) {
      var last = this.innerHTML;
      this.innerHTML = "COPIED!";
      clicked = true;
      setTimeout(function() {
        this.innerHTML = last;
        clicked = false;
      }.bind(this), 1000);
    }
  };
}(false), this);


What I have tried:

JavaScript
document.getElementById("copied").addEventListener("click", function (clicked) {
            return function () {
                if (!clicked) {
                    var last = this.innerHTML;
                    this.innerHTML = "COPIED!";
                    clicked = true;
                    setTimeout(function () {
                        this.innerHTML = last;
                        clicked = false;
                    }.bind(this), 1000);
                }
            };
        }(false), this);
Posted
Comments
Peter_in_2780 6-Jul-21 19:01pm
   
You have multiple elements with id copied.
getElementByID() is defined to return the FIRST element with that id.
Cyka Blyat 7-Jul-21 15:22pm
   
I tested with
`document.querySelectorAll("#copied").addEventListener("click", function (clicked) {`
and it doesn't seem to work. Can you show me what else needs to be changed cause I am stuck for real here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900