Reputation: 69
Basically I want to get the color from an CSS element (in our case #button)* and use it to another CSS element (in our case #output)* but with opacity . I want the output in rgba so I can set the opacity from rgba. My solution seems it doesn't want to work ...
function hex2rgb(hex, opacity) {
var h=hex.replace('#', '');
h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));
for(var i=0; i<h.length; i++)
h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);
if (typeof opacity != 'undefined') h.push(opacity);
return 'rgba('+h.join(',')+')';
}
var getcolor = $("#button").css("color");
var colour = hex2rgb(getcolor,0.3);
$(function() {
$("#output").css("backgroundColor",colour);
});
*see JSFiddle
Upvotes: 1
Views: 991
Reputation: 310
Doesn't look like your code works at all. If I've understood your requirement, something like this would work:
$.fn.extend({
stealColor : function(target, opacity)
{
$(this).css('background-color', $(target).css('background-color') )
.css('opacity', opacity );
}
});
$('#output').stealColor('#button', 0.8);
Or if you want to steal the text color:
$(this).css('background-color', $(target).css('color') )
.css('opacity', opacity );
See fiddle.
Your original function hex2rgb takes an rgb() parameter and produces an rgba() value.
So, to fix your code:
function rgb2rgba(rgb, opacity) {
return 'rgba' + rgb.substring(3, rgb.length-1) + ', ' + opacity + ')';
}
var getcolor = $("#button").css("color");
var colour = rgb2rgba(getcolor, 0.3);
$("#output").css("background-color", colour);
See fiddle.
Upvotes: 1
Reputation: 43156
Instead of trying to modify the rgb
, you can use the opacity
property as shown below:
function change(source, target, alpha) {
var color = source.css("color");
var sub = color.slice(0,-1).replace("rgb","rgba");
color = sub+ ", "+alpha+")";
target.css("background-color", color);
}
$(function () {
change($("#button"),$("#output"), 0.5)
});
#output {
border:1px solid black;
width:400px;
height:400px;
background:#ff0; /* This needs to be replaced with #button color to rgba */
}
#button {
color:#F54C54;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
<br>
<div id="button">Get color from this text</div>
Upvotes: 1