I have an HTML element whose background colour is set with rgba()
T
I had do this too but ended up writing something a little more specific. I put it in a jQuery plugin that accepts a min and max opacity:
$.fn.setAlpha = function ( options ) {
var settings = $.extend({
alpha: 0.5,
min: 0,
max: 1
}, options );
return this.each(function() {
var color = $(this).css('background-color');
if (color.substring(0,4) === 'rgba') {
var a;
if (settings.alpha <= settings.min) {
a = settings.min;
} else if (settings.alpha >= settings.max) {
a = settings.max;
} else {
a = settings.alpha;
}
var rgba = color.replace(/[^,]+(?=\))/, a);
$(this).css('background-color', rgba);
}
});
}
$.fn.getAlpha = function () {
var color = this.css('background-color');
if (color.substring(0,4) === 'rgba') {
var alpha = color.split(',');
alpha = alpha[alpha.length - 1].trim();
alpha = alpha.substring(0, alpha.indexOf(")"));
return alpha;
} else {
return 1;
}
}
then you use them to do something like this to set a div to transparent and fade it to its original opacity as you scroll down:
//get original opacity
var originalOpacity = $('#myDiv').getAlpha();
//set new opacity
//it will be 0 at the top of the page
var newOpacity = $(window).scrollTop()/500;
$('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
//on scroll fade new opacity to originalOpacity at 500px down
$(window).scroll( function() {
var newOpacity = $(window).scrollTop()/500;
$('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
}
Does this help?
http://www.phpied.com/rgb-color-parser-in-javascript/
This may help in addition.
Convert RGBA color to RGB
After some playing around, and the discovery of getComputedStyle, I have put together this.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#element {
background-color: rgb(10,10,10);
background-color: rgba(10,10,10,1);
}
</style>
<script type="text/javascript">
HTMLElement.prototype.alpha = function(a) {
current_color = getComputedStyle(this).getPropertyValue("background-color");
match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color)
a = a > 1 ? (a / 100) : a;
this.style.backgroundColor = "rgba(" + [match[1],match[2],match[3],a].join(',') +")";
}
</script>
</head>
<body>
<div id="element">
This is some content.
</div>
<script type="text/javascript">
e = document.getElementById('element');
e.alpha(20);
</script>
</body>
</html>
You could also use elem.style.opacity=0.5
or in html style="opacity:0.5"
. It is important to note that the child nodes will fade too.
You got the string, replace whatever
'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')