JSFiddle - React, Tailwind, and code Playground
by kpowz
HTML
<script src="https://rawgit.com/brehaut/color-js/master/color.js"></script>
<h1>
Sort CSS Hex Colors
</h1>
<form id="formy">
<fieldset>
<label>list of hex colors to sort</label>
<textarea rows="4" cols="50" placeholder='["7A6E9B", "796C9B","7A6F9B", "796C9B","6F72AC", "796D9B", "856C8C", "796E9B", "796C9B", "796C9B", "6F72AC", "78699A", "796B9A", "786A9A" ]'></textarea>
</fieldset>
<input type="submit"/>
</form>
<h2>RESULT</h2>
<p>
hover over color swatch to see underlying value
</p>
<section name="results">
<h3>
By Base10
</h3>
<ol id='resultBase10'>
</ol>
</section>
<section>
<h3>
By Hue
</h3>
<ol id='resultHue'>
</ol>
</section>
<template id="list-item-template">
<li>
<div class="li-color"></div>
</li>
</template>
CSS
.li-color {
width: 150px;
height: 50px;
}
section {
display: inline-table;
}
JavaScript
var form_el = document.getElementById("formy"),
Color = net.brehaut.Color;
const defaultLegendColors = ["7A6E9B", "796C9B","7A6F9B", "796C9B","6F72AC", "796D9B", "856C8C", "796E9B", "796C9B", "796C9B", "6F72AC", "78699A", "796B9A", "786A9A" ];
const hexCharMapping = [{A: 10}, {B: 11}, {C: 12}, {D: 13}, {E: 14}, {F: 15}];
function sortByAttr(){
}
function toBaseTen(color, index, array) {
const multiplier = 16;
let charNum, matches, exponent, explodedColor = color.split(''), base10 = 0;
explodedColor.forEach(function(c, charIndex, charArray){
matches = hexCharMapping.filter(function(o){ return o[c] != undefined; } );
charNum = matches.length === 1 ? matches[0][c] : c;
exponent = (charArray.length - 1) - charIndex;
base10 += Number(charNum) * (Math.pow(multiplier, exponent));
});
return { base10: base10, base16: '#' + color };
}
function sortByHex(hexies) {
let base10AndBase16Vals, vals = hexies;
base10AndBase16Vals = vals.map(toBaseTen);
base10AndBase16Vals.sort(function(a,b) { return (a.base10 < b.base10) ? 1 : ((b.base10 < a.base10) ? -1 : 0);});
console.log(base10AndBase16Vals);
return base10AndBase16Vals;
}
function toHue(hexie) {
return { hue: Color("#" + hexie).getHue(), base16: '#' + hexie };
}
function sortByHue(hexies){
let huesAndBase16Vals = hexies.map(toHue).sort(function(a,b) { return (a.hue < b.hue) ? 1 : ((b.hue < a.hue) ? -1 : 0);});
return huesAndBase16Vals;
}
form_el.addEventListener("submit", function(evt) {
evt.preventDefault();
let colorEle,
targetEle = document.getElementById("resultBase10"),
targetEle2 = document.getElementById("resultHue"),
listItemTempalte = document.querySelector('#list-item-template'),
inputHexies = document.getElementsByTagName("textarea")[0].value || defaultLegendColors;
colorEle = listItemTempalte.content.querySelector('div');
sortByHex(inputHexies).forEach(function(v) {
colorEle.setAttribute("style", "background:" +...