JSFiddle - React, Tailwind, and code Playground

by huppen

HTML

<div id="colors">
  <input id="hex" placeholder="HEX" maxlength="7">
  <br>
  <input id="rgb" placeholder="RGB" maxlength="11">
</div>
<div class="info">
  <span class="hex"></span>
  <span class="rgb"></span>
</div>
<div class="item">
</div>

CSS

body {
  font-size: 12px;
  font-family: Monaco;
}

#colors,
.item,
.info {
  float: left;
  margin-right: 20px;
}

#hex {
  text-transform: uppercase;
}

.item {
  position: relative;
  width: 30px;
  height: 30px;
  display: inline-block;
  border-radius: 50%;
}

.info .rgb {
  display: block;
}

JavaScript

/* Color HEX to RGB */

var $hex = $('#hex');
var $rgb = $('#rgb');

function rgbToHex(a) {
  a = a.replace(/[^\d,]/g, "").split(",");
  return ((1 << 24) + (+a[0] << 16) + (+a[1] << 8) + (+a[2])).toString(16).slice(1)
}

function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

$hex.bind('blur keyup', function(e) {
  color = hexToRgb($('#hex').val());


  if (color) {
    $('#rgb').val(color.r + "," + color.g + "," + color.b);
    $('.item').css('background', 'rgb(' + $("#rgb").val() + ')');
    $('.info .hex').html("<span>background-color: " + $("#hex").val() + ";</span>");
    $('.info .rgb').html("<span>background-color: rgb(" + $("#rgb").val() + ");</span>");
  } else {
    $('#rgb').val('');
    $('.item').css('background', '#FFFFFF');
  }

  if (e.keyCode == 13) {
    $rgb.select();
  }
});

$rgb.bind('blur keyup', function(e) {
  color = "#" + rgbToHex($('#rgb').val());
  console.log(color);

  if (color !== "#aN") {
    $('#hex').val(color);
    $('.item').css('background', color);
    $('.info .hex').html("<span>background-color: " + $("#hex").val() + ";</span>");
    $('.info .rgb').html("<span>background-color: rgb(" + $("#rgb").val() + ");</span>");
  } else {
    $('#hex').val('');
    $('.item').css('background', '#FFFFFF');
  }


  if (e.keyCode == 13) {
    $hex.select();
  }
});