Create a Div Element dynamically in pure JS and assign a random Bg color to it

Asked

Viewed 62 times

1

I’m solving an exercise that consists of generating a div100px 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>

1 answer

2

Lacked little, example:

/// 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;
}

function addNewSquare(){
    let divElement = document.createElement('div')//
    divElement.setAttribute("onclick", "changeBg(this)")
    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(obj) {
    obj.style.background = getRandomColor();
}
div{
    width: 100px;
    height: 100px;
    margin:20px ;
    border: 3px solid slateblue;
}
 <button onclick="addNewSquare()">Clique aqui</button>

Added the this in the function of changeBg(this) to know which element will undergo the change and in the function was called the other function getRandomColor() to always generate the new color.

  • 1

    Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.