Event onmouseover random colors

2

Speak Devs, I'm with the js code below briefly the idea is that when the user clicks the button creates a new screen element in the form of a square, every time the user moves the mouse over the square change his color for a random color generated by the function, but it is not switching to the random colors. Can anyone help?

var btnElement = document.querySelector('button.btn');
var boxElement = document.querySelector('.box');

btnElement.onclick = function() { 
    boxElement.style.width = '100px';
    boxElement.style.height = '100px';
    boxElement.style.marginTop = '50px';
    boxElement.style.backgroundColor = '#f00';
}

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
        
console.log(newColor);
<div class="container">
  <div id="app">
    <button type="button" class="btn btn-success">Success</button>
    <div class="box" id="box" onmouseover="getRandomColor()"></div>
  </div>
</div>
    
asked by anonymous 15.11.2018 / 23:42

2 answers

3

You are not setting the new color anywhere, you can do it by simply changing the style in the function instead of trying to give the return

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    boxElement.style.backgroundColor = color;
}
    
16.11.2018 / 00:08
2

var btnElement = document.querySelector('button.btn');
let count = 1;

btnElement.onclick = function() {
  // Cria um novo elemento box
  let boxElement = document.createElement("div");
  boxElement.className = "box";
  boxElement.id = "box-" + count;
  boxElement.style.width = '100px';
  boxElement.style.height = '100px';
  boxElement.style.marginTop = '50px';
  boxElement.style.backgroundColor = '#f00';

  boxElement.addEventListener("mouseover", () => {
    let newColor = getRandomColor();

    console.log(boxElement.id + ": " + newColor);
    boxElement.style.backgroundColor = newColor;
  });
  
  // Adiciona um novo elemento box para app
  document.getElementById('app').appendChild(boxElement);
  count++;
}

function getRandomColor() {
  var color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16);
  return color;
}
<div class="container">
  <div id="app">
    <button type="button" class="btn btn-success">Success</button>
  </div>
</div>
    
16.11.2018 / 00:28