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
Try to do:
v.addEventListener(“click”, function() {changeColor(this.id)});
This should trigger the function when your button is clicked.Instead of setting an
onClick
property to a string of code, useaddEventListener
to add the click event. For example: