jonmrich
jonmrich

Reputation: 4333

Script to generate CSS properties with random colors

I need to create a bunch (800) CSS properties each with a different color in this format:

#mydiv[terr="T368"] {
  polygon-fill: #F11810;
}

I found this handy script to generate random HEX colors (http://www.paulirish.com/2009/random-hex-color-code-snippets/):

Math.floor(Math.random()*16777215).toString(16);

I'm a bit new to javascript and can't put together a loop that does the following:

The number next to the "T" needs to be incremented from 1 to 800 with each TXXX having a unique color. It's fine if there are duplicates of colors throughout the 800, I can go back and fix that by hand. No need to add a function that ensures there are duplicates.

What I'm looking for is a script that generates 800 css properties like this:

#mydiv[terr="T100"] {
  polygon-fill: #F11810;
}
#mydiv[terr="T101"] {
  polygon-fill: #e2e2e2;
}
#mydiv[terr="T102"] {
  polygon-fill: #6A3D9A;
}
...etc, etc.

Yes, the #mydiv remains the same. This is specific CSS for CartoDB, so the formatting is specific to that.

I just need the 800 CSS properties to generate so I can copy and paste them into CartoDB.

PS: Bonus points for handling the case of all Ts before 100, which are formatted like this, for example: T001 and T050.

EDIT: Got very close on my own, but could use help on my "bonus" question above. H

for (rep = 1; rep <= 800; rep++) {
  var color = Math.floor(Math.random()*16777215).toString(16);  
    document.write('#mydiv[territory="T' + rep + '"] {<br> polygon-fill:#'   +color+';<br>}<br>');
}

Upvotes: 0

Views: 329

Answers (2)

kasper Taeymans
kasper Taeymans

Reputation: 7026

Here is a simple script that will generate the stuff you want. You can copy the formatted css from the textarea.

JSFiddle demo

HTML:

<textarea id="output"></textarea>

JS:

var output = $("#output");
for (var i = 0; i < 801; i++) {
    var color = '#' + Math.floor(Math.random() * 16777215).toString(16);
    var css = "#mydiv[terr='T" + i + "']{\n polygon-fill: " + color + ";\n}\n";
    output.append(css);
}

Upvotes: 2

jonmrich
jonmrich

Reputation: 4333

Finally got it all (including my bonus question). Of note, occasionally, this random color generator creates a HEX with 5 characters that's invalid, but I can't quite figure out why, so I had to go through each one by hand to find them, but not a big issue for my challenge.

for (rep = 1; rep <= 800; rep++) {
  var color = Math.floor(Math.random()*16777215).toString(16);
  if (rep < 10)  {
    document.write('#mydiv[territory="T00' + rep + '"] {<br> polygon-fill:#' +color+';<br>}<br>');
  }
  if (rep >=10 && rep <100)
  {
    document.write('#mydiv[territory="T0' + rep + '"] {<br> polygon-fill:#' +color+';<br>}<br>');
}
if (rep >= 100)  {
    document.write('#mydiv[territory="T' + rep + '"] {<br> polygon-fill:#' +color+';<br>}<br>');
}
}

Upvotes: 0

Related Questions