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

Time:07-17

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 >Goals</div>
  <div >
    <div >Names:</div>
    <div >AA</div>
    <div >AA</div>
    <div >FA</div>
    <div >AA</div>
    <div >OB</div>
    <div >DB</div>
    <div >DG</div>
    <div >MK</div>
    <div >GM</div>
    <div >BM</div>
    <div >SM</div>
    <div >LN</div>
    <div >ER</div>
    <div >SR</div>
    <div >YS</div>
    <div >MT</div>
    <div >ST</div>
    <div >ST</div>
    <div >JV</div>
    <div >EZ</div>
  </div>

  <div >
    <div >Ik learn how to count till 10.</div>
    <div id="container">
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
    </div>
  </div>

CodePudding user response:

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 >Goals</div>
  <div >
    <div >Names:</div>
    <div >AA</div>
    <div >AA</div>
    <div >FA</div>
    <div >AA</div>
    <div >OB</div>
    <div >DB</div>
    <div >DG</div>
    <div >MK</div>
    <div >GM</div>
    <div >BM</div>
    <div >SM</div>
    <div >LN</div>
    <div >ER</div>
    <div >SR</div>
    <div >YS</div>
    <div >MT</div>
    <div >ST</div>
    <div >ST</div>
    <div >JV</div>
    <div >EZ</div>
  </div>

  <div >
    <div >ten cols</div>
    <div id="container">
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
      <div > </div>
    </div>
  </div>
  <br/>
  <br/>
  <div >
  <p>cells anyplace else in the dom, may get the same behavior, just give them the .colorme class...</p> 
  </div>
  <div >click me too!</div>

CodePudding user response:

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

Ex:

<div id="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';
  }
}

CodePudding user response:

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();
  • Related