Skip to content

Instantly share code, notes, and snippets.

@garystorey
Last active December 17, 2015 10:09
Show Gist options
  • Select an option

  • Save garystorey/5592910 to your computer and use it in GitHub Desktop.

Select an option

Save garystorey/5592910 to your computer and use it in GitHub Desktop.
Generate Random Hex Color Example: http://codepen.io/garystorey/pen/ugtza
var randomColors = {
init : function () {
this.elems = document.querySelectorAll("div");
this.update();
document.querySelector('#updateColors').addEventListener('click', function() {
randomColors.update();
});
},
update : function () {
var b, c, i = 0, el;
for (; el = this.elems[i]; i++) {
b = this.randomColor();
c = this.useBlackOrWhite( b );
el.style.color = '#' + c;
el.style.backgroundColor = '#' + b;
el.style.borderColor = '#' + c;
document.getElementById( 'bg' + i ).value = '#' + b;
}
},
randomColor : function () {
var vals = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'],
len = vals.length, r = 0, color = new Array(5);
for (; r < 6; r++) { color[r] = vals[ this.randomNumber( len ) ]; }
return color.join('');
},
randomNumber : function ( len ) { return Math.floor(Math.random()*len); },
useBlackOrWhite : function ( hexcolor) { /* from 24 Ways */
var r = parseInt( hexcolor.substr(0,2), 16 ),
g = parseInt( hexcolor.substr(2,2), 16),
b = parseInt( hexcolor.substr(4,2), 16),
yiq = (( r*299 )+( g*587 )+( b*114 )) / 1000;
return (yiq >= 128) ? '111' : 'eee';
}
};
randomColors.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment