Use onmouseover to change the color of created Ivs with createelement

Asked

Viewed 176 times

-2

the goal of this code is that whenever the user clicks the button, appears on the screen, a div in the form of a square, and when he hovers over one of the created squares, his background-color is changed to a random color. However, I’m not managing to change the color of the squares. HTML:

<body>
<div id="app">
    <button id="btn">Criar quadrado</button>
</div>
</body>

Code to create square Ivs:

    btnElement = document.querySelector('button#btn');

    btnElement.onclick = function () {
        var quadradoElement = document.createElement('div');
        quadradoElement.setAttribute('class', 'box')
        quadradoElement.style.width = '100px';
        quadradoElement.style.height = '100px';
        quadradoElement.style.backgroundColor = '#060621';

        var divElement = document.querySelector('div#app');
        divElement.appendChild(quadradoElement);
    }

Function to generate random color:

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

    var newColor = getRandomColor();

Code q is not working, it would change the color of the Divs when overwriting the mouse:

var quadradoCriado=document.getElementsByClassName('box');
        quadradoCriado.onmouseover= function(){
            quadradoCriado.style.backgroundColor=newColor;
        }

https://jsfiddle.net/omd9kpw4/1/

  • Edit your question to synchronize the code that is in the fiddle with what is in the question. Some parts that are there are missing here... Read this guide to learn more.

1 answer

0


Inside the Button, add the click event this way "onclick="creatDiv();".

<script>


     function criarDiv() { 
        var quadradoElement = document.createElement('div');
        quadradoElement.setAttribute('class', 'box')
        quadradoElement.setAttribute('onmouseover', 'trocarCorFundoDiv(this);')//Adicionar o evento do mouse passando a div que esta sendo criado.
        quadradoElement.style.width = '100px';
        quadradoElement.style.height = '100px';
        quadradoElement.style.backgroundColor = '#1ccdda';

        var divElement = document.getElementById("app");
        divElement.appendChild(quadradoElement);


        }
    function trocarCorFundoDiv(quadradoCriado){  
         quadradoCriado.style.backgroundColor  = getRandomColor();//mudar a cor de fundo da div passada por parametro
    }


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

</script>

Browser other questions tagged

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