How do I randomly generate HTML hex color codes using JavaScript?
This will generate a random number within the bounds and convert it to hexadecimal. It is then padded with zeros so that it's always a valid six-digit hex code.
'#'+(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0');
Random color generator
Use getRandomColor()
in place of "#0000FF"
:
function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color;}
function setRandomColor() { $("#colorpad").css("background-color", getRandomColor());}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="colorpad" style="width:300px;height:300px;background-color:#000">
</div><button onclick="setRandomColor()">Random Color</button>
JS Replace each HEX color with a new random HEX color
Replace data.replace(/^#[0-9A-F]{6}$/i.test('#AABBCC'), () => '#' + ("000000" + Math.random().toString(16).slice(2, 8).toUpperCase()).slice(-6));
with:
data.replace(/#[0-9A-F]{3,6}/ig, () => `#${Math.floor(Math.random()*16777215).toString(16)}`);
I added global
flag to your regex and found a shorter way to generate a random color from here, besides removing unnecessary .test
and deleting ^
/$
(matches at the start of the string) Create a hexadecimal colour based on a string with JavaScript
Just porting over the Java from Compute hex color code for an arbitrary string to Javascript:
function hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
To convert you would do:intToRGB(hashCode(your_string))
Generate Random Color distinguishable to Humans
You could use a fixed set of colors, such as the ones listed in the jquery.color.js plugin.
List of colors from jquery.color.js plugin:
Colors = {};
Colors.names = {
aqua: "#00ffff",
azure: "#f0ffff",
beige: "#f5f5dc",
black: "#000000",
blue: "#0000ff",
brown: "#a52a2a",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgrey: "#a9a9a9",
darkgreen: "#006400",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkviolet: "#9400d3",
fuchsia: "#ff00ff",
gold: "#ffd700",
green: "#008000",
indigo: "#4b0082",
khaki: "#f0e68c",
lightblue: "#add8e6",
lightcyan: "#e0ffff",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightyellow: "#ffffe0",
lime: "#00ff00",
magenta: "#ff00ff",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
orange: "#ffa500",
pink: "#ffc0cb",
purple: "#800080",
violet: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
white: "#ffffff",
yellow: "#ffff00"
};
The rest is simply picking a random property from a Javascript object.Colors.random = function() {
var result;
var count = 0;
for (var prop in this.names)
if (Math.random() < 1/++count)
result = prop;
return result;
};
Using Colors.random()
might get you a human-readable color. I even powered an example below.(function(){ Colors = {}; Colors.names = { aqua: "#00ffff", azure: "#f0ffff", beige: "#f5f5dc", black: "#000000", blue: "#0000ff", brown: "#a52a2a", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgrey: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkviolet: "#9400d3", fuchsia: "#ff00ff", gold: "#ffd700", green: "#008000", indigo: "#4b0082", khaki: "#f0e68c", lightblue: "#add8e6", lightcyan: "#e0ffff", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightyellow: "#ffffe0", lime: "#00ff00", magenta: "#ff00ff", maroon: "#800000", navy: "#000080", olive: "#808000", orange: "#ffa500", pink: "#ffc0cb", purple: "#800080", violet: "#800080", red: "#ff0000", silver: "#c0c0c0", white: "#ffffff", yellow: "#ffff00" }; Colors.random = function() { var result; var count = 0; for (var prop in this.names) if (Math.random() < 1/++count) result = prop; return { name: result, rgb: this.names[result]}; }; var $placeholder = $(".placeholder"); $placeholder.click(function(){ var color = Colors.random(); $placeholder.css({'background-color': color.rgb}); $("#color").html("It's " + color.name); });})();
.placeholder { width: 150px; height: 150px; border: 1px solid black;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="placeholder"></div><span id="color">Click the square above.</span>
Related Topics
Jquery Smooth Scroll to an Anchor
Understanding JavaScript Immutable Variable
Why Are Es6 Classes Not Hoisted
Why Are Exceptions Used for Rejecting Promises in Js
Why Does a Simple .*? Non-Greedy Regex Greedily Include Additional Characters Before a Match
How to Create a Date Object from String in JavaScript
Typeerror: Cannot Read Property 'Setstate' of Undefined
Why Does Console.Log Say Undefined, and Then the Correct Value
Catching Errors in JavaScript Promises with a First Level Try ... Catch
React Doesn't Reload Component Data on Route Param Change or Query Change
Why "This" Is Undefined Inside a Fat Arrow Function Definition
Understanding JavaScript Promises; Stacks and Chaining
JSON Transfer of Bigint: 12000000000002539 Is Converted to 12000000000002540
Difference Between Obtrusive and Unobtrusive JavaScript
How to Parseint a String with Leading 0
JavaScript Listener, "Keypress" Doesn't Detect Backspace