1
I have the following function, which creates blocks dynamically:
function criar(){
let box = document.querySelector('.box');
box.style.display = 'flex'
let element = document.createElement('div')
element.style.width = '100px';
element.style.height = '100px';
element.style.background = '#f00';
element.style.marginRight = '6px';
element.className = 'container';
element.setAttribute('onmousemove', 'getRandomColor()')
box.appendChild(element)
}
function getRandomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
let container = document.querySelector('.container');
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
container.style.backgroundColor = color;
return color;
}
<button onclick="criar()">Criar Quadrado</button>
<div class="box">
</div>
The function getRandomColor()
generates random colors for the created block. The problem is that this only works for the first block created, others receive the mouse event but do not undergo the change. I tried to use the querySelectorAll()
to select more than one element, but the console returns error. Someone knows how to make it work?
this in this case refers to the dynamically created div. But how it accesses the Container class?
– Danúbio Vieira Lima
this is the DIV element created in the create() function, container is only the name given to the parameter, it could be any other name, in this context, the container is actually a div element of the DOM that the mouse is currently positioned.
– Daniel Mendes