Monochromatic colors
by Kieran Dang
HTML
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.1/clipboard.js" crossorigin="anonymous"></script>
<div class="color" style="height: 100px; width: calc(10% - 5px); display: inline-block;"></div>
<div class="color" style="height: 100px; width: calc(10% - 5px); display: inline-block;"></div>
<div class="color" style="height: 100px; width: calc(10% - 5px); display: inline-block;"></div>
<div class="color" style="height: 100px; width: calc(10% - 5px); display: inline-block;"></div>
<div class="color" style="height: 100px; width: calc(10% - 5px); display: inline-block;"></div>
CSS
.color {
cursor: pointer;
}
JavaScript
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function randomNumber(min, max) {
const r = Math.random() * (max - min + 1) + min;
if (r > 100) {
return 100;
}
return r;
}
const rgb2hex = (rgb) => `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1).map(n => parseInt(n, 10).toString(16).padStart(2, '0')).join('')}`;
const colorize = () => {
const items = $('div');
let hue;
let saturation;
let lightness = randomNumber(50, 100);
let copy = new ClipboardJS('.color');
for (let i = 0; i < items.length; i++) {
if (i % 5 === 0) {
hue = randomNumber(0, 360);
saturation = randomNumber(0, 100);
lightness = randomNumber(50, 100);
const clr = 'hsl(' + hue + ', ' + saturation.toFixed(2) + '%, ' + lightness.toFixed(2) + '%)';
$(items[i]).css('background-color', clr);
}
else {
lightness -= randomNumber(0, 10);
hue -= randomNumber(-5, 5);
if(hue < 0) {
hue += 360;
}
const clr = 'hsl(' + hue + ', ' + saturation.toFixed(2) + '%, ' + lightness.toFixed(2) + '%)';
$(items[i]).css('background-color', clr);
}
$(items[i]).click(function() {
$(this).attr("data-clipboard-text", rgb2hex($(this).css('background-color')));
});
}
};
colorize();