Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the color of a square with onmouseover

Tags:

javascript

I started to learn js and now i'm make a list of exercise. In this list i need to make a button that every time i click, a new red square appear on the screen, and always i pass the mouse over of any square the color must to changes for an aleatory one. but i only can change the color of the first square.

Why this happens?

how i can fix this?

let btn = document.querySelector("#btn");

btn.onclick = function createSquare() {
  let divSquare = document.createElement("div");
  divSquare.setAttribute("class", "square");
  divSquare.setAttribute("onmouseover", "mouseOver()");

  let container = document.querySelector("#container");
  container.appendChild(divSquare);
};

function mouseOver() {
  function getRandomColor() {
    let letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
    }
  return color;
  }
let newColor = getRandomColor();
        
return document.querySelector('.square').style.backgroundColor = newColor;
}
#container {
  display: flex;
  width: 100%;
  height: 100%;
  flex-wrap: wrap;
}
.square {
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 1px;
}
<button id="btn">Click here for create a new square</button>
<div id="container"></div>

i need to use JS to solve this problem

like image 328
Bruno Rocha Avatar asked Oct 24 '19 17:10

Bruno Rocha


Video Answer


1 Answers

Add an event parameter (e) to your mouseOver func and use e.target to get the box to set the background on

function getRandomColor() {
    let letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function mouseOver(e) {
  let newColor = getRandomColor();
  return e.target.style.backgroundColor = newColor;
}
like image 100
ControlAltDel Avatar answered Oct 01 '22 14:10

ControlAltDel