EagL EagL - 3 months ago 9
Javascript Question

Toggling background color of div

Title, my only problem is that when I've created all elements on my page, and clicked all of them, my page looks like a chess board.

I can only "toggle" the background color of half too. So it's not only that they don't change color on the first click, they don't change at all.

This is my Javascript:

for (var i = 0; i < 10; i++) {
var itemContainer = document.createElement("div" + i);
itemContainer.id = "div" + i;
itemContainer.className = "item";
itemContainer.innerHTML = "Hello!";

for (let i = 0; i < 10; i++) {
$('div' + i).click(function() {
if (this.className == "item") {
this.className = "itemselected";
} else {
this.className = "item";
}
});
}

document.getElementById("page").appendChild(itemContainer);
}


I made a JSFiddle for you who want it.

I've seen a few other questions about how to toggle the color of backgrounds, but none of them have the same problem as me.

Answer

You inserted your second loop into the first one, every second i got skipped. And probably was able to change your divs up to i=18

JSFiddle

for (var i = 0; i < 10; i++) {
    var itemContainer = document.createElement("div" + i);
    itemContainer.id = "div" + i;
    itemContainer.className = "item";
    itemContainer.innerHTML = "Hello!";

    document.getElementById("page").appendChild(itemContainer);
}

for (let i = 0; i < 10; i++) {
    $('div' + i).click(function() {
        if (this.className == "item") {
            this.className = "itemselected";
        } else {
            this.className = "item";
        }
    });
}

Edit: You could simply put the content of your second loop into the first loop, to simplify your code a bit.