rgb(a) to hex

by ramesh valasa

HTML

Convert RGB/RGBA to hex:<br>
(opacity of rgba is ignored)<br>
<input type="text" value="rgba(15, 114, 189, 0.07)"> <button>Convert</button><br>
<br>
Result <span class="result"></span>

CSS

body { padding: 20px; background: #222; color: #ddd; }

JavaScript

//Function to convert hex format to a rgb color
function rgb2hex($fore, $back){
   $ored: ((1 - alpha($fore)) * red($back) ) + (alpha($fore) * red($fore));
  $ogreen: ((1 - alpha($fore)) * green($back) ) + (alpha($fore) * green($fore));
  $oblue: ((1 - alpha($fore)) * blue($back) ) + (alpha($fore) * blue($fore));
  @return rgb($ored, $ogreen, $oblue);
}

$('button').click(function(){
    var hex = rgb2hex( $('input').val() );
    $('.result').html( hex );
});