trying to set up random backgroundcolors with eventlistener whilst hovering over grid-cells with js

23 Views Asked by At

this is my first question here - i'm learning alone.

So I set up a grid and it works kind of like the etch a sketch game, you can draw by hovering. It worked fine just for the black background, but I want to go further and have each cell change the background when hovering over it.

now it does not even paint it black anymore since I inserted the randomBgColor function.

this is the code:

  document.addEventListener("DOMContentLoaded", function() {
  const button = document.createElement("button");
  document.body.appendChild(button);
  document.body.prepend(button);

  button.textContent = "press me to set grid size";
  const myGrid = document.querySelector("#myGrid");
  let customGrid = "";

  button.addEventListener("click", () => {
    customGrid = parseInt(prompt("insert a number between 0 & 100"));
    for (let i = 0; i < customGrid; i++) {
      const column = document.createElement("div");
      column.classList.add("column");
      myGrid.appendChild(column);
      for (let j = 0; j< customGrid; j++) {
        const cell = document.createElement("div");
        cell.classList.add("cell");
        cell.classList.add("hover");
        column.appendChild(cell);
      }
      function randomBgColor() {
        var x = Math.floor(Math.random() * 256);
        var y = Math.floor(Math.random() * 256);
        var z = Math.floor(Math.random() * 256);
        var bgColor = "rgb(" + x + "," + y + "," + z + ")";
        console.log(bgColor);
      }
      randomBgColor();

      const hover = document.querySelectorAll(".hover");
      hover.forEach((element) => {
        element.addEventListener("mouseover", (event) => {
          element.style.backgroundColor = randomBgColor();
        });
      });
    }
  });
});

I added the randomBgColor() function with googles' help and it returns numeric random values, but it does not change the color of each cell.

I expected it to change each cells color as I replaced the "black" at element.style.backgroundColor = "black";

with

    element.style.backgroundColor = randomBgColor();

but it does not do anyhting, in fact it stopped working completely.

Console in devtools says nothing just random rgb number indications...

can someone help?

0

There are 0 best solutions below