rgb(a) to hex

by Mottie

HTML

Convert RGB/RGBA to 6 or <a href="https://css-tricks.com/8-digit-hex-codes/">8 digit hex</a>:
<br>
<input type="text" value="rgba(34, 34, 34, .5)">
<button>Convert</button>
<br>
<br> Results:
<div class="results">
<ul class="result"></ul>
</div>

CSS

/* See http://wowmotty.blogspot.com/2017/05/convert-rgba-output-to-hex-color.html */

body {
  padding: 20px;
  background: #222;
  color: #ddd;
}
a, a:visited {
  color: #ddd;
}
.results {
 max-height: 120px;
 overflow-y: auto;
}

JavaScript

// Function to convert hex format to a rgb color
function rgb2hex(orig) {
  var a, isPercent,
    rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
    alpha = (rgb && rgb[4] || "").trim(),
    hex = rgb ? "#" +
    (rgb[1] | 1 << 8).toString(16).slice(1) +
    (rgb[2] | 1 << 8).toString(16).slice(1) +
    (rgb[3] | 1 << 8).toString(16).slice(1) : orig;
  if (alpha !== "") {
    isPercent = alpha.indexOf("%") > -1;
    a = parseFloat(alpha);
    if (!isPercent && a >= 0 && a <= 1) {
      a = Math.round(255 * a);
    } else if (isPercent && a >= 0 && a <= 100) {
      a = Math.round(255 * a / 100)
    } else {
      a = "";
    }
  }
  if (a) {
    hex += (a | 1 << 8).toString(16).slice(1);
  }
  return hex;
}

function convert() {
  var li = rgb = $('input').val(),
    hex = rgb2hex(rgb),
    $results = $('.results');
  if (rgb !== hex) {
    $('.result').append(`<li>${rgb} &rarr; ${hex}</li>`);
    $results.scrollTop($results[0].scrollHeight - $results.height());
  }
}

$('button').click(convert);
$('input').on('keyup', function(e) {
  if (e.key === "Enter") {
    convert();
  }
});