0
I’m trying to do an exercise, in which I need to do the following process:
Using the result of the first challenge, every time the user passes the mouse over some square changes its color to a random color generated by the function below:
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();
The solution I found for the first challenge quoted was the following:
var btn = document.querySelector('#criarQuad');
var container = document.querySelector('#app');
btn.onclick = function() {
var quad = document.createElement('div');
quad.style.width = '100px';
quad.style.height = '100px';
quad.style.backgroundColor = '#F00';
return container.appendChild(quad);
console.log(quad);
}
In the above function, every time the user clicks on the indicated button, a new square will be added. So I tried the following solution for the exercise cited at the beginning of the publication:
container.addEventListener('mouseover', function(e) {
e.target.className == 'quadrado' ? e.target.setAttribute('style', 'background-color: ' + newColor) : undefined;
});
However, instead of changing the color of the square as you ask for the exercise, it erases the square that I pass the mouse and all that come in sequence, someone would know to tell me why this happens and how I could solve?
thank you very much, I did not care that the solution was in my face all the time rs, it worked perfectly!
– Mateus Daniel