const body = document.querySelector( `body` );
function getRandomNumber( max ) {
return Math.floor( Math.random() * max )
}
function getRandomRGB() {
const colors = [];
for( let i = 0; i < 3; i++ ) {
const n = getRandomNumber( 100 + 1 );
colors.push( n );
}
return `rgb(${ colors.join( '%,' )}%)`;
}
function changeRGB() {
const divs = body.querySelectorAll( `div` );
for( let i = 0; i < divs.length; i++ ) {
divs[ i ].style.backgroundColor = getRandomRGB();
divs[ i ].style.transitionDuration = `${ getRandomNumber( 10 ) + 1 }s`;
}
}
for( let i = 0; i < 25; i++ ) {
const div = document.createElement( `div` );
div.style.backgroundColor = getRandomRGB();
div.style.transitionDuration = `${ getRandomNumber( 10 ) + 1 }s`;
body.appendChild( div );
}
setInterval( changeRGB, 1000 );
* {
box-sizing: border-box; margin: 0; padding: 0;
}
html, body {
height: 100%;
}
body {
display: flex; flex-wrap: wrap;
filter: saturate( 200% );
}
section {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
backdrop-filter: blur( 5rem );
-webkit-backdrop-filter: blur( 5rem );
}
div {
flex-grow: 1;
min-width: 25%; min-height: 10%; background-color: #222;
transition-property: background-color;
transition-duration: 2s;
}
<section></section>
The function changeRGB():
function changeRGB() {
const divs = body.querySelectorAll( `div` );
for( let i = 0; i < divs.length; i++ ) {
divs[ i ].style.backgroundColor = getRandomRGB();
divs[ i ].style.transitionDuration = `${ getRandomNumber( 10 ) + 1 }s`;
}
}
and the for loop after it:
for( let i = 0; i < 25; i++ ) {
const div = document.createElement( `div` );
div.style.backgroundColor = getRandomRGB();
div.style.transitionDuration = `${ getRandomNumber( 10 ) + 1 }s`;
body.appendChild( div );
}
contain almost identical lines of code:
divs[ i ].style.backgroundColor = getRandomRGB();
divs[ i ].style.transitionDuration = `${ getRandomNumber( 10 ) + 1 }s`;
and
div.style.backgroundColor = getRandomRGB();
div.style.transitionDuration = `${ getRandomNumber( 10 ) + 1 }s`;
respectively.
In changeRGB() we're manipulating div's that already exist and in the for loop we're first creating those div's then manipulating them in the same way. My goal is to refactor this code to make it a little less repetitive.
I need to replace div and divs[ i ] with something dynamic so I can just call one function and input the proper value here. I'm not sure if the loop complicates things more but I've tried window[ variable ].style.backgroundColor etc where variable is a dynamic variable but no luck. Possibly implementing it wrong.
How do I make changeRGB() function and for loop less repetitive and more concise?