1
I need the backgroundcolor of div elements to be changed when passing the mouse over, but these elements do not exist yet, will be created by pressing a button, I’ve tried for a few hours to think of some solution, but nothing comes to mind.
obs. I can create the div elements, I just can’t change the color by hovering over.
follows the JS code
var boxContainer = document.querySelector('#box');
var btnElement = document.querySelector('button');
var getBox = document.getElementsByClassName('createBox');
btnElement.onclick = function creatingBoxes(){
var boxCreator = document.createElement('div');
boxCreator.setAttribute('class', 'createBox');
boxCreator.style.width = "100px";
boxCreator.style.height = "100px";
boxCreator.style.backgroundColor = '#f00';
boxContainer.insertBefore(boxCreator, btnElement);
}
getBox.onmouseover = function changingColorOfBoxes() {
var newColor = getRandomColor(); // #E943F0
getBox.style.backgroundColor = newColor;
}
function getRandomColor(){
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
I did this example: https://repl.it/repls/AnotherVacantPostscript which uses the CSS Paint API to generate a custom fill CSS function (random colors) that is applied via stylesheet to all elements whose attribute
class="createBox"
whether it is or not. I didn’t publish it as an answer because the question seems to be very specific about javascript, so I’m curious.– Augusto Vasques