mercredi 18 novembre 2015

Randomize five colors and assign them to nine elements' background. Make sure all five colors are used

I have an array of five colors:

var colors = ['#ff988a', '#51caf3', '#7ddb7f', '#ffce6e', '#bdb3f6'];

And nine elements - let's call them bubbles:

var bubbles = document.querySelectorAll('.bubble');

I need to randomly define a background color for each bubble, and make sure all five colors are used - meaning there can't be only three or four colors for nine bubbles.

The function that generates random colors is:

function getRandomColor(colors) {
  return colors[Math.floor(Math.random() * colors.length)];
}

And I have another function that assigns background colors for the bubbles, yet not able to make sure all the colors are used:

function changeColors(elements, colors) {
  var randomColors = [];
  for (var i=0; i<elements.length; i++) {
    var randomColor = getRandomColor(colors);
    elements[i].style.backgroundColor = randomColor;
  }
}

Bear in mind that: the bubbles are absolutely positioned so there will not be apparent orders, which means determining the color of sibling bubbles in HTML orders makes no sense, I guess.




Aucun commentaire:

Enregistrer un commentaire