Color Saving

by Ashish Kasama

HTML

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<div style="color:rgb(255, 0, 0, 0.5)" id="original">
  Hello
</div>
<div style="" id="new">
  Hello
</div>

JavaScript

function rgb2hex(rgb){
    rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgb && rgb.length === 4) ? "#" +
      ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
      ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
      ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
  }
  function hextorgba(hex,opacity){
    hex = hex.replace('#','');
    r = parseInt(hex.substring(0,2), 16);
    g = parseInt(hex.substring(2,4), 16);
    b = parseInt(hex.substring(4,6), 16);
    result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
    return result;
  }
  function getopacity(rgba){
  	return rgba.replace(/^.*,(.+)\)/,'$1');
  }
  
  function ColorLuminance(rgba, lum) {

    var hex = rgb2hex(rgba);
    
	// validate hex string
	hex = String(hex).replace(/[^0-9a-f]/gi, '');
	if (hex.length < 6) {
		hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
	}
	lum = lum || 0;

	// convert to decimal and change luminosity
	var rgb = "#", c, i;
	for (i = 0; i < 3; i++) {
		c = parseInt(hex.substr(i*2,2), 16);
		c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
		rgb += ("00"+c).substr(c.length);
	}
    
    var opacity = getopacity(rgba);
    
    var finalrgba = hextorgba(rgb, opacity);

	return finalrgba;
}
var color = $('#original').css('color');
color = ColorLuminance(color, 1);
$('#new').css('color', color);