I have managed to create divs (I use css to make them blue circles) dynamically and add unique id attributes dynamically too, I'd like to also add unique onclick events also but I am struggling to manage it. Here is my JavaScript code followed by the HTML I'm working with:
var i = 0;
function addCircles(click) {
var numberOfCircles = document.getElementById('setSize').value;
var startFromOne = numberOfCircles + 1 - 81;
document.getElementById('debug').innerHTML = numberOfCircles;
for (i = 1; i < startFromOne; i++) {
var element = document.createElement('div');
element.id = "circle" + i;
element.className = "circle";
// element.onclick = attack(key);
document.getElementById('gamecanvas').appendChild(element);
document.getElementById("circle" + i).innerHTML = i;
}
}
function attack(key) {
if (key === 1) {
document.getElementById('circle1').style.backgroundColor = purple;
}
/* This is a tester, if circle1 turns purple onclick I'm good to go. */
}
I want to be able to click the divs (blue circles) and change their colour.
keyfrom? Also if you writeattack(key), it will execute the function, rather than binding it to an event handler.getElementsByClassName('circle')which creates a NodeList that you can loop through and attach a click event to.