-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;
}
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.
– Luiz Felipe