Quantcast
Channel: Active questions tagged flexbox - Stack Overflow
Viewing all articles
Browse latest Browse all 1318

Change div's background color to random with mouseover and keep divs squre and flex within a container

$
0
0

I am trying to change background color of a div when mouseover. I can do that by assigning class to the div and in CSS assign background color to that class. But when trying to have background change randomly a have to change the background directly and that is where I fail. Function randomColor returns correct hex string but it is not reflected by using target.style.backgroundColor = '${randomColor()}'.

The other issue is with flexbox (I should not use Grid) where I want user set amount of divs to flex within fixed dimension square container and keep square.

When using target.style.backgroundColor = '${randomColor()}' I don't see it change color of the div which is what I expected to happen.

Here is my fiddle

const container = document.querySelector('#container');function addDivStart() {    for (let i=1; i<=289; i++) {        const newDiv = document.createElement('div');        // newDiv.textContent = "x";        newDiv.setAttribute("class", "newDiv");        container.appendChild(newDiv);        newDiv.addEventListener('mouseover', e => e.target.classList.add('my-color-class') );    }}addDivStart();function removeAllChildNodes(parent) {    while (parent.firstChild) {        parent.removeChild(parent.firstChild);    }}let rows;function randomColor (colorHex) {    colorHex =  "#" + (Math.random()    * 0xFFFFFF<<0).toString(16);    console.log(colorHex);    return colorHex;}function addDivSettings() {    for (let i=1; i<=rows; i++) {        const newDiv = document.createElement('div');        // newDiv.textContent = "x";        newDiv.setAttribute("class", "newDiv");        container.appendChild(newDiv);        newDiv.addEventListener('mouseover', e => e.target.style.backgroundColor = '${randomColor()}'); //to have random color        // newDiv.addEventListener('mouseover', e => e.target.classList.add('my-color-class') ); // to change only to red    }}button = document.querySelector('button');button.addEventListener('click', () => {    rows = prompt('Enter desired number of squares per side (max 100):', 17);    rows = rows * rows    console.log(rows);    removeAllChildNodes(container)    addDivSettings();})

Viewing all articles
Browse latest Browse all 1318

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>