1

The current functionality is generating random numbers for RGB and based on which is setting the RGB colour.

function randomColor(){
    r = Math.floor(Math.random() * (256));
    g = Math.floor(Math.random() * (256));
    b = Math.floor(Math.random() * (256));
    jQuery('.bg').css('background-color','rgb('+r+','+g+','+b+')');
    jQuery('#ms-tile-color').attr('content','rgb('+r+','+g+','+b+')');
}

jQuery(document).ready(function(){
    randomColor();
    var t = setInterval(randomColor,5000);
});

function rollBg() {
$('.bg.hidden').css('background', randomColor());
$('.bg').toggleClass('hidden');

}

I would like to create an array something like the array below and pick a random value from this and keep setting the colour.

var colourArray = [
{r: 40, g: 29, b: 45},
{r: 107, g: 107, b: 181},
{r: 78, g: 100 , b: 78}

];

How do I set the values from the array r, g, b

jQuery('.bg').css('background-color','rgb('+r+','+g+','+b+')');
jQuery('#ms-tile-color').attr('content','rgb('+r+','+g+','+b+')');

this is where I am not understanding

Thanks for your help

Dawson
  • 23
  • 6

1 Answers1

0

You can get a random entry from the array and then just reference the fields in the element that you grabbed and put it into the css.

function randomColor() {
  var rand = colourArray[Math.floor(Math.random() * colourArray.length)];
  r = rand.r
  g = rand.g
  b = rand.b
  jQuery('.bg').css('background-color', 'rgb(' + r + ',' + g + ',' + b + ')');
  jQuery('#ms-tile-color').attr('content', 'rgb(' + r + ',' + g + ',' + b + ')');
}

jQuery(document).ready(function() {
  randomColor();
  var t = setInterval(randomColor, 5000);
});

function rollBg() {
  $('.bg.hidden').css('background', randomColor());
  $('.bg').toggleClass('hidden');
}

var colourArray = [{
    r: 40,
    g: 29,
    b: 45
  },
  {
    r: 107,
    g: 107,
    b: 181
  },
  {
    r: 78,
    g: 100,
    b: 78
  }
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ms-tile-color" class="bg" style="height: 100px; width: 100px;"></div>
Joffutt4
  • 1,418
  • 14
  • 15