I am trying to change the color based on the background color to make the text more readable.
During my search I found this:
var rgb = $('.external-event').css('background-color');
var c = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
var o = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) + (parseInt(rgb[2]) * 114)) / 1000);
//console.log(o);
if (o > 125) {
$('.external-event').css('color', 'black');
} else {
$('.external-event').css('color', 'white');
}
$('.external-event').css('background-color', c);
var r = Math.round(Math.random() * 255);
var g = Math.round(Math.random() * 255);
var b = Math.round(Math.random() * 255);
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
The problem is that it's only displaying white color and not changing to black.
What am I doing wrong here?
Here is a JSFiddle.
for some reason this example is doing the opposite then my actual development environment and keeping the text in black even with a black background.
EDIT: I forgot to add I am dynamically displaying multiple background colors with the same class .external-event
and it seems to be only getting the rgb value of the first element.
With the help of Sam Onela's answer I was able to figure it out.
Here is what I did:
$('.external-event').each(function() {
var rgb = $(this).css('background-color');
var pattern = /rgb\((\d+),\s?(\d+),\s?(\d+)\)/;
var matches = rgb.match(pattern);
var o = Math.round(((parseInt(matches[1]) * 299) + (parseInt(matches[2]) * 587) + (parseInt(matches[3]) * 114)) /1000);
//console.log(o);
if(o > 125) {
$(this).css('color', '#444444');
}else{
$(this).css('color', 'white');
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments