/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*/
function shuffle(array) {
var m = array.length,
t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
//List of all color code available
var colorCodes = ["fd3331", "3ef626", "3f32f3", "ff32f1", "3ef2f1", "fff232", "fc4c8c", "6cc930", "618cf5", "ce308f", "c47c32", "fa8d38", "9933ba", "45af7f", "cc3232", "bfd832", "426e71", "9e905f", "f6b58b", "3d8ebd", "40d89b", "7f5966", "f2cd7f", "9863f1", "8bb231"];
function applyRandomColors() {
var cloneColorCodes = colorCodes.slice(0);
//Total no. of options add by user
var totalOptions = 7;
//Without round-robin fashion
var availableCode_question = cloneColorCodes.length - totalOptions;
//Pick a random start index
var randomStartIndex = Math.floor(Math.random() * availableCode_question);
/*
* for testing purpose show the order of the colors
* BEGINS
*/
var ele_ordered = document.getElementsByClassName('ordered');
//For verification: Orderly placed colors
for (var i = 0, k = randomStartIndex; i < ele_ordered.length; k++, i++) {
ele_ordered[i].style.background = "#" + cloneColorCodes[k];
}
/*
* ENDS
*/
//Create an array using the random start index
var colorCode_randomStartIndex = cloneColorCodes.splice(randomStartIndex, totalOptions);
//shuffle the color codes within the array using above Fisher-Yates algo
var randomColorCode_question = shuffle(colorCode_randomStartIndex);
var ele_options = document.getElementsByClassName('option');
for (var i = 0; i < ele_options.length; i++) {
ele_options[i].style.background = "#" + randomColorCode_question[i];
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.