Create style for various dynamically generated elements

Asked

Viewed 45 times

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?

1 answer

3


Danube,

A very simple way to do this event onmousemove work for all blocks, is to pass the this for the function getRandomColor:

element.setAttribute('onmousemove', 'getRandomColor(this)');

And change the getRandomColor function to receive the container per parameter.

function getRandomColor(container){

See your example with these changes:

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(this)');
  box.appendChild(element);
}

function getRandomColor(container){
  let letters = "0123456789ABCDEF";
  let color = "#";

  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }

  container.style.backgroundColor = color;
}
<button onclick="criar()">Criar Quadrado</button>

<div class="box"></div>

  • this in this case refers to the dynamically created div. But how it accesses the Container class?

  • 1

    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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.