Changing the color of HTML Elements that do not yet exist

Asked

Viewed 79 times

1

I need the backgroundcolor of div elements to be changed when passing the mouse over, but these elements do not exist yet, will be created by pressing a button, I’ve tried for a few hours to think of some solution, but nothing comes to mind.

obs. I can create the div elements, I just can’t change the color by hovering over.

follows the JS code

var boxContainer = document.querySelector('#box');
var btnElement = document.querySelector('button');
var getBox = document.getElementsByClassName('createBox');

btnElement.onclick = function creatingBoxes(){

    var boxCreator = document.createElement('div');

    boxCreator.setAttribute('class', 'createBox');
    boxCreator.style.width = "100px";
    boxCreator.style.height = "100px";
    boxCreator.style.backgroundColor = '#f00';
    boxContainer.insertBefore(boxCreator, btnElement);
}

getBox.onmouseover = function changingColorOfBoxes() {
    
    var newColor = getRandomColor(); // #E943F0
    getBox.style.backgroundColor = newColor;
    
}

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

  • 1

    I did this example: https://repl.it/repls/AnotherVacantPostscript which uses the CSS Paint API to generate a custom fill CSS function (random colors) that is applied via stylesheet to all elements whose attribute class="createBox" whether it is or not. I didn’t publish it as an answer because the question seems to be very specific about javascript, so I’m curious.

2 answers

5


You have already understood that the problem is to try to access an element when it does not yet exist. So why not simply leave to assign mouseover treatment at the time of creation? So:

var boxContainer = document.querySelector('#box');
var btnElement = document.querySelector('button');

btnElement.onclick = function creatingBoxes(){

    var boxCreator = document.createElement('div');

    boxCreator.setAttribute('class', 'createBox');
    boxCreator.style.width = "100px";
    boxCreator.style.height = "100px";
    boxCreator.style.backgroundColor = '#f00';
    boxContainer.appendChild(boxCreator);
    
    boxCreator.onmouseover = function changingColorOfBoxes() {   
        var newColor = getRandomColor(); // #E943F0
        this.style.backgroundColor = newColor;

    }
}


function getRandomColor(){
    var letters = "0123456789ABCDEF";  
    var color = "#";  
    for (var i = 0; i < 6; i++) {   
         color += letters[Math.floor(Math.random() * 16)];  
    } 
    return color; 
} 
<button type="button">
Novo box
</button>

<div id="box">

</div>

0

Friend, perfect your solution, dps a few hours thinking had come up with something very close to your code, but it has not yet broken hehe. Man if you can help me understand why the brownser says that the variable "CHANGE" of the function "changingColorOfBoxes" has the value as undefined I would thank, breaking my head with this.

ps. your solution is better than my hehe mainly pq ta working, but I feel that to Prox to achieve using my logic, just needed to understand pq the variable change ta not being able to fetch the tags by the class.

var boxContainer = document.querySelector('#box');
var btnElement = document.querySelector('button');
var count=1;

/*
    Esta função cria as caixas usando as tags <p> e define o nome da class de cada tag
    e também define o atributo do mouseover 

*/

btnElement.onclick = function creatingBoxes(){

    var boxCreator = document.createElement('p');

    boxContainer.insertBefore(boxCreator, btnElement);
    boxCreator.setAttribute('class', ''+count+'');
    boxCreator.style.width = "100px";
    boxCreator.style.height = "100px";
    boxCreator.style.backgroundColor = '#f00';
    boxCreator.setAttribute('onmouseover', 'changingColorOfBoxes('+count+')');

    count++;
}


//Esta funçao pega o nome da classe e altera o seu background-color

function changingColorOfBoxes(count) {
    
    var newColor = getRandomColor();
    var change = document.getElementsByClassName(""+count+"");

    change.style.backgroundColor = newColor;
}

//Esta função gera um valor de cor aleatória

function getRandomColor(){
    var letters = "0123456789ABCDEF";  
    var color = "#";  
    for (var i = 0; i < 6; i++) {   
         color += letters[Math.floor(Math.random() * 16)];  
    } 
    return color; 
} 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div id="box">
            <button class="btn">Adicionar nova caixa</button>
        </div>
        <script src="changingColor.js"></script>
    </body>
</html>

Browser other questions tagged

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