0
Good afternoon, The code below generates a red square every time I click on the "Create Red Square" button. But now I need to change the color of that square every time I hover over it, I tried to do it with the code below, but I couldn’t. Could someone help me?
Create red square<script>
var btnElement = document.querySelector('button.botao');
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(); // #E943F0
btnElement.onclick = function () {
// cria um novo elemento div
var divNova = document.createElement("div");
divNova.style.width = '100px';
divNova.style.height = '100px';
divNova.style.backgroundColor = '#f00';
// adiciona o novo elemento criado e seu conteúdo ao DOM
var divAtual = document.querySelector('app');
document.body.insertBefore(divNova, divAtual);
return divNova;
}
divNova.onmouseover = function () {
var divNovaCor = document.createElement("div");
divNovaCor.style.width = '100px';
divNovaCor.style.height = '100px';
divNovaCor.style.backgroundColor = newColor;
var divNova = document.querySelector('app');
document.body.insertBefore(divNovaCor, divNova);
}
</script>
So, but in case I need to switch to a random color, generated by the getRandomColor() function. How could I do that?
– Renan Monteiro
In this case you will have to register the action
ommouseover
before adding the element to the DOM. I updated the reply, please check.– dfvc