Note, There may be "bug" at
(Math.random()*0xFFFFFF<<0).toString(16)
where , occasionally , the length
of the string generated may be 5
, instead of 6
, resulting in an element without a background-color
being applied to the elements' style
; i.e.g.,
var arr = [], res = [];
for (i = 0; i < 100; i++) {
arr.push((Math.random()*0xFFFFFF<<0).toString(16));
};
$.each(arr, function(k, v) {
if (v.length < 6) {
res.push(v);
}
});
console.log(res.length);
a quick-fix solution is included within piece below
Try
html
<!--
given each "inner-container" element
within `.post` "outer-container"
has some form of `unique-id` -->
<div class="post">
<span id="a"></span>
<span id="b"></span>
<span id="c"></span>
<span id="d"></span>
<span id="e"></span>
<span id="f"></span>
<span id="g"></span>
<span id="h"></span>
</div>
js
// this piece could actually be run when the "post" ,
// or element , is generated , instead of each occasion
// the document is loaded .
// the `colors` array could be stored at server ,
// as `json` object ,e.g., "colors.json", or other preferred format ,
// updating when new "post" is created / generated .
// the array generated could contain two members :
// the unique "id" of the "post" , and the color
// associated with that `unique-id`
// the data could then be posted to server
// which updates `colors.json` file with
// new entries
var colors = [];
$(".post span").each(function(i, el) {
// `bug` : occasionally returns string having
// `length` of `5` , instead of `6`
var r = ((Math.random()*0xFFFFFF<<0).toString(16));
// _quickix_ : check `length` of `r` string ,
// if `< 6` , generate random "number" between 0-9 ,
// concat to `r`
r = r.length < 6 ? r + (1 + Math.floor(Math.random() * 9)) : r;
var color = "#" + r ;
// apply `color` to `background-color` , here ,
// if desired
// $(el).css("background-color", color);
// push `unique-id , color` pair to `colors` array
colors.push([el.id, color]);
// optional , `POST` new `colors` array to server ,
// adding new entry to `colors.json` ,
// unique for each `unique-id`
// $.post("colors.php", {"data" : colors});
});
// when loading "template" of `html` `.post` "posts" ,
// having unique id's , or , being generated dynamically
// and given `unique-id`'s , apply `color` to each element
// based on `unique-id` and `color` generated for it
// when created
// optional : `$.getJSON("colors.json", function(colors) {});`
// having `$.each()` function at `complete` callback
// reassembly `colors` associated with `unique-id`'s
$.each(colors, function(k, v) {
$(".post span[id="+v[0]+"]").css("background-color", v[1])
});
jsfiddle http://jsfiddle.net/guest271314/f895bh53/