Skip to content

Instantly share code, notes, and snippets.

@bfontaine
Forked from 140bytes/LICENSE.txt
Last active December 12, 2015 02:19
Show Gist options
  • Save bfontaine/4698384 to your computer and use it in GitHub Desktop.
Save bfontaine/4698384 to your computer and use it in GitHub Desktop.
Random CSS hexadecimal color code generator.
function (
e // placeholder
){
e = (
0 | // shorter than a Math.floor call
Math.random() * 16777216 // random number n, 0 <= n <= 0xFFFFFF
// note that 16777216 = 0xFFFFFF+1
.toString(16); // get the hex representation of n
while( e.length<6 ) e=0+e;// pad with 0s if necessary
return'#'+e
}
function(e){e=(0|Math.random()*16777216).toString(16);while(e.length<6)e=0+e;return'#'+e}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "randomCSSHexColorCode",
"description": "Return a random CSS hexadecimal color code.",
"keywords": [
"random",
"css",
"color"
]
}
@atk
Copy link

atk commented Feb 6, 2013

Smaller function:

function(e){e=2<<23;e+=(0|Math.random()*e);return'#'+e.toString(16).slice(1)}

@subzey
Copy link

subzey commented Feb 14, 2013

@atk, I bet it can be even shorter:

function(){return'#'+(1e8^Math.random()*(1<<24)).toString(16).slice(1)}

@atk
Copy link

atk commented Apr 11, 2013

Even smaller (though potentially erroneous if Math.random ever spews out less than 6 digits after the comma - rather unlikely, but not entirely impossible):

function(){return'#'+(Math.random()).toString(16).slice(-6)}

@atk
Copy link

atk commented Apr 11, 2013

alas, this happens sometimes. Better use:

function (){return'#'+(Math.random()*Math.PI).toString(16).slice(-6)}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment