0
I can only make the change of color only once when you hover the mouse, and when you create a new element, it is always the same color as the previous one, thus staying in a pattern.
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Exercicio 7</title>
</head>
<body>
<div id="app">
<button class="botao">Adicionar um elemento aleatório</button>
</div>
</body>
<script>
function getRandomColor() {
var letters = "0123456789ABCDEFG";
var color = "#";
for(var i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16 )];
}
return color;
}
var newColor = getRandomColor();
var app = document.querySelector("#app");
var button = document.querySelector("#app button");
button.onclick = function() {
var box = document.createElement('div');
box.style.width = 100;
box.style.height = 100;
box.style.backgroundColor = "#f00";
box.onmouseover = function(){
box.style.backgroundColor = newColor;
}
app.appendChild(box);
}
</script>
</html>
So I made a comparison with this code and I saw that it has small differences, but which one is generating the conflict?
The expected result was that when you hovered over the box, it would then change color, regardless of how many times you passed.
So Sergio, the expected result is almost this, however when I passed again the mouse in the color of the element, it would change color again, could highlight what was the logic error in my code? I’m sorry if I wasn’t very specific in the description of the problem.
– user152996
@Rodrigopires in this case the
var newColor = getRandomColor();
must be inside theonmouseover
... its the same logic I explained above. I changed in the answer, now test.– Sergio