lundi 17 août 2020

Javascript random color change

I am trying to select random divs and change background-color. Only 8 items should be visible at a time, If there are more colors in array, it shows randomly.

Sometimes same div repeats. How can I make it more random?

var c = ["123abc", "12abc3", "abc123", "1dcb23", "1876c3", "a34523", "165423", "1dcb23", "E53E3E", "7B341E", "D69E2E", "48BB78", "38B2AC", "ED64A6"];
var sub;
var shuffled;
var l = document.getElementsByClassName('item');
function disp(){
  var i = 0;
  var s = setInterval(function(){
var ran = Math.floor(Math.random() * l.length);
l[ran].style.backgroundColor = '#' + sub[i];
var opacity = 0;
function MyFadeFunction() {
   if (opacity<1) {
      opacity += .1;
      setTimeout(function(){MyFadeFunction()},50);
   }
   l[ran].style.opacity = opacity;
}
MyFadeFunction();
i++;
if(i == sub.length){
  i = 0;
  clearTimeout(s);
  shufflearray();
}
  }, 1500);
}
function shufflearray(){
  var a = [];
  shuffled = c.sort(() => Math.random() - 0.5);
  sub = shuffled.slice(8, shuffled.length - 1);
  disp();
}
shufflearray();
.item{
  width: 50px; height: 50px; float: left; margin: 10px;
}
<div class="wrap">
  <div class="item" style="background-color:#123abc"></div>
  <div class="item" style="background-color:#12abc3"></div>
  <div class="item" style="background-color:#abc123"></div>
  <div class="item" style="background-color:#1dcb23"></div>
  <div class="item" style="background-color:#12098c"></div>
  <div class="item" style="background-color:#1876c3"></div>
  <div class="item" style="background-color:#a34523"></div>
  <div class="item" style="background-color:#165423"></div>
</div>

Codepen - https://codepen.io/felixaj/pen/LYNZbZY





Aucun commentaire:

Enregistrer un commentaire