1
I’m solving an exercise that consists of generating a div
100px X 100px and when the user clicks on one of these squares the color of the BG should change to a randomly generated color, I was able to generate the square div, more when created the function
that changes her BG, but she doesn’t know
I don’t know about the scope or anything.
follows the code:
/// FUNÇÃO QUE GERA UMA COR ALEATÓRIA
function getRandomColor() {
let letters = "0123456789ABCDEF";
let color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// VARIÁVEL QUE GUARDA A COR ALEATÓRIA
var newColor = getRandomColor();
// FNÇÃO QUE CRIA QUADROS NOVOS AO CLICAR NO BOTÃO
function addNewSquare(){
let divElement = document.createElement('div')//
divElement.setAttribute("onclick", "changeBg()")
divElement.setAttribute("class","box")
document.body.appendChild(divElement)
}
//FUNÇÃO PARA MUDAR A COR DE FUNCO DA DIV PARA UMA COR ALEATÓRIA
function changeBg() {
divElement.style.background(color)
}
div{
width: 100px;
height: 100px;
margin:20px ;
border: 3px solid slateblue;
}
<button onclick="addNewSquare()">Clique aqui</button>
Thank you very much!
– João Divino