skip to Main Content

Trying to generate a button for each letter of the alphabet and then toggle the color from white to black on click.

function LoopTest() {
    var i = 0;
    var stop = 5;
    for (i = 65;i < 91;i++) {  
     var v = document.createElement('input');
     v.type="button";
     v.value= String.fromCharCode(i);
     v.id = i;
     v.style.color = "black";
     v.onClick = "changeColor(this.id)";
     document.getElementById('test').appendChild(v);
    }
}
function changeColor(_this){
    var pp = document.getElementById(_this);
    if(pp.style.color == "black"){
        pp.style.color = "white";
    }else{
        pp.style.color = "black";
    }
}

Generates the buttons fine by does nothing on click.

2

Answers


  1. Try to do: v.addEventListener(“click”, function() {changeColor(this.id)}); This should trigger the function when your button is clicked.

    Login or Signup to reply.
  2. Instead of setting an onClick property to a string of code, use addEventListener to add the click event. For example:

    function LoopTest() {
      var i = 0;
      var stop = 5;
      for (i = 65; i < 91; i++) {
        var v = document.createElement('input');
        v.type="button";
        v.value= String.fromCharCode(i);
        v.id = i;
        v.style.color = "black";
         
        // Here:
        //v.onClick = "changeColor(this.id)";
        v.addEventListener('click', function () {
          changeColor(this.id);
        });
    
        document.getElementById('test').appendChild(v);
      }
    }
    
    function changeColor(_this) {
      var pp = document.getElementById(_this);
      if (pp.style.color == "black") {
        pp.style.color = "white";
      } else {
        pp.style.color = "black";
      }
    }
    
    LoopTest();
    <div id="test"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search