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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With