change color of many squares seperatly to different colors by clicking with JavaScript

196 Views Asked by At

I'm new to JavaScript and I'm trying to change the colour of a square by clicking on it, first to yellow, then orange, then green and back to white. So far I managed to do that for one row, but if I want to add a 2nd row, a 3rd, a 4th, till atleast a 100th, it says I can't use the same Id-tag. So what other options do I have?

I tried to work with document.getElementsByTagName ("container"); and document.getElementsByClassName("container"); but for some reason the colour doesn't change anymore after that.

I hope someone can help me. Thanks in advance!

let x = document.getElementById("container");
let y = x.children;
let click = 0;

function myFunction() {
  for (let i = 0; i < y.length; i++) {
    y[i].onclick = function() {
      if (click == 0) {
        y[i].style.backgroundColor = "yellow";
        click = 1;
      } else if (click == 1) {
        y[i].style.backgroundColor = "orange";
        click = 2;
      } else if (click == 2) {
        y[i].style.backgroundColor = "green";
        click = 3;
      } else {
        y[i].style.backgroundColor = "white";
        click = 0;
      }
    }
  }
}
myFunction();
div {
  background-color: white;
  text-align: center;
  float: left;
}

* {
  box-sizing: border-box;
}

.header {
  border: 1px solid gray;
  padding: 15px;
  width: 100%;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

[class*="col-"] {
  float: left;
  padding: 20px;
  height: 15px;
  border: 1px solid grey;
}

.col-1 {
  min-width: 20%;
}

.col-2 {
  min-width: 4%;
}

.col-3 {
  min-width: 4%;
}

.col-4 {
  width: 4%;
}

.col-5 {
  width: 4%;
}

.col-6 {
  width: 4%;
}

.col-7 {
  width: 4%;
}

.col-8 {
  width: 4%;
}

.col-9 {
  width: 4%;
}

.col-10 {
  width: 4%;
}

.col-11 {
  width: 4%;
}

.col-12 {
  width: 4%;
}

.col-13 {
  width: 4%;
}

.col-14 {
  width: 4%;
}

.col-15 {
  width: 4%;
}

.col-16 {
  width: 4%;
}

.col-17 {
  width: 4%;
}

.col-18 {
  width: 4%;
}

.col-19 {
  width: 4%;
}

.col-20 {
  width: 4%;
}

.col-21 {
  width: 4%;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>test</title>
</head>

<body>
  <div class="header">Goals</div>
  <div class="row">
    <div class="col-1">Names:</div>
    <div class="col-2">AA</div>
    <div class="col-3">AA</div>
    <div class="col-4">FA</div>
    <div class="col-5">AA</div>
    <div class="col-6">OB</div>
    <div class="col-7">DB</div>
    <div class="col-8">DG</div>
    <div class="col-9">MK</div>
    <div class="col-10">GM</div>
    <div class="col-11">BM</div>
    <div class="col-12">SM</div>
    <div class="col-13">LN</div>
    <div class="col-14">ER</div>
    <div class="col-15">SR</div>
    <div class="col-16">YS</div>
    <div class="col-17">MT</div>
    <div class="col-18">ST</div>
    <div class="col-19">ST</div>
    <div class="col-20">JV</div>
    <div class="col-21">EZ</div>
  </div>

  <div class="row">
    <div class="col-1">Ik learn how to count till 10.</div>
    <div id="container">
      <div class="col-2"> </div>
      <div class="col-3"> </div>
      <div class="col-4"> </div>
      <div class="col-5"> </div>
      <div class="col-6"> </div>
      <div class="col-7"> </div>
      <div class="col-8"> </div>
      <div class="col-9"> </div>
      <div class="col-10"> </div>
      <div class="col-11"> </div>
      <div class="col-12"> </div>
      <div class="col-13"> </div>
      <div class="col-14"> </div>
      <div class="col-15"> </div>
      <div class="col-16"> </div>
      <div class="col-17"> </div>
      <div class="col-18"> </div>
      <div class="col-19"> </div>
      <div class="col-20"> </div>
    </div>
  </div>

3

There are 3 best solutions below

0
mwave317 On

Give each one of the div's an id and a click event passing in the id.

Ex:

<div id="1" class="col-1" onclick="color()">Names:</div>

Write a method in the javascript that uses the id being passed in as a parameter and change the color:

function color(id) {
  let div = document.querySelector('id');
  if (div.style.backgroundColor === 'blue') {
    div.style.backgroundColor = 'yellow';
  }
  else if (div.style.backgroundColor = 'yellow') {
    div.style.backgroundColor = 'orange';
  }
  else if (div.style.backgroundColor = 'white') {
    div.style.backgroundColor = 'red';
  }
  else {
    div.style.backgroundColor = 'purple';
  }
}
0
danh On

Give the cells you want to target a common class, target them with getElementsByClassName.

I took the liberty of assuming you'd like each cell to sequence through the color states independently of the other, so I dispensed with the shared click variable, and change states based on the current state...

function myFunction() {
  const sequence = ['yellow', 'orange', 'green', 'white'];
  let y = [...document.getElementsByClassName("colorme")];

  for (let el of y) {
    el.onclick = function() {
      let index = sequence.findIndex(c => c === el.style.backgroundColor);
      index = index === sequence.length - 1 ? 0 : index + 1;
      el.style.backgroundColor = sequence[index];
    }
  }
}
myFunction();
div {
  background-color: white;
  text-align: center;
  float: left;
}

* {
  box-sizing: border-box;
}

.header {
  border: 1px solid gray;
  padding: 15px;
  width: 100%;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

[class*="col-"] {
  float: left;
  padding: 20px;
  height: 15px;
  border: 1px solid grey;
}

.col-1 {
  min-width: 20%;
}

.col-2 {
  min-width: 4%;
}

.col-3 {
  min-width: 4%;
}

.col-4 {
  width: 4%;
}

.col-5 {
  width: 4%;
}

.col-6 {
  width: 4%;
}

.col-7 {
  width: 4%;
}

.col-8 {
  width: 4%;
}

.col-9 {
  width: 4%;
}

.col-10 {
  width: 4%;
}

.col-11 {
  width: 4%;
}

.col-12 {
  width: 4%;
}

.col-13 {
  width: 4%;
}

.col-14 {
  width: 4%;
}

.col-15 {
  width: 4%;
}

.col-16 {
  width: 4%;
}

.col-17 {
  width: 4%;
}

.col-18 {
  width: 4%;
}

.col-19 {
  width: 4%;
}

.col-20 {
  width: 4%;
}

.col-21 {
  width: 4%;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>test</title>
</head>

<body>
  <div class="header">Goals</div>
  <div class="row">
    <div class="col-1">Names:</div>
    <div class="col-2">AA</div>
    <div class="col-3">AA</div>
    <div class="col-4">FA</div>
    <div class="col-5">AA</div>
    <div class="col-6">OB</div>
    <div class="col-7">DB</div>
    <div class="col-8">DG</div>
    <div class="col-9">MK</div>
    <div class="col-10">GM</div>
    <div class="col-11">BM</div>
    <div class="col-12">SM</div>
    <div class="col-13">LN</div>
    <div class="col-14">ER</div>
    <div class="col-15">SR</div>
    <div class="col-16">YS</div>
    <div class="col-17">MT</div>
    <div class="col-18">ST</div>
    <div class="col-19">ST</div>
    <div class="col-20">JV</div>
    <div class="col-21">EZ</div>
  </div>

  <div class="row">
    <div class="col-1">ten cols</div>
    <div id="container">
      <div class="colorme col-2"> </div>
      <div class="colorme col-3"> </div>
      <div class="colorme col-4"> </div>
      <div class="colorme col-5"> </div>
      <div class="colorme col-6"> </div>
      <div class="colorme col-7"> </div>
      <div class="colorme col-8"> </div>
      <div class="colorme col-9"> </div>
      <div class="colorme col-10"> </div>
    </div>
  </div>
  <br/>
  <br/>
  <div class="row">
  <p>cells anyplace else in the dom, may get the same behavior, just give them the .colorme class...</p> 
  </div>
  <div class="colorme col-2">click me too!</div>

0
Joacim Norbeck On

I created a kind of row generator that might be of use for you. Not the prettiest but here you go:

    let colors = ["white", "yellow", "orange", "green"];
    function generateRows() {
      let numberOfRows = 4;
      let numberOfSquaresPerRow = 20;
      for (let i = 1; i <= numberOfRows; i++) {
        let row = document.createElement("div");
        row.className = "row";
        let container = document.createElement("div");
        container.className = "container";
        row.appendChild(container);

        for (let j = 1; j <= numberOfSquaresPerRow; j++) {
          let square = document.createElement("div");
          square.className = `col-${j}`;
          square.setAttribute("color", 0);
          square.addEventListener("click", () => {
            let color = parseInt(square.getAttribute("color"));
            let colorToSet = color < colors.length - 1 ? color + 1 : 0;
            square.style.backgroundColor = colors[colorToSet];
            square.setAttribute("color", colorToSet);
          });
          container.appendChild(square);
        }
        document.body.appendChild(row);
      }
    }
    generateRows();