I am working with a table that contains data from my database:
Here is the ViewModel structure:
function alertViewModel(i) {
var self = this;
self.Id = ko.observable(i.Id);
self.AlertType = ko.observable(i.AlertType);
self.Category = ko.observable(i.Category);
self.Color = ko.observable(i.Color);
self.AlertText = ko.observable(i.AlertText);
self.update = function (data) {
if (typeof (data.AlertType) != 'undefined') self.AlertType(data.AlertType);
if (typeof (data.Category) != 'undefined') self.Category(data.Category);
if (typeof (data.Color) != 'undefined') self.Color(data.Color);
}
};
In the cshtml file, I present the data in this way:
<table class="table" id="alertstable">
<tbody data-bind="foreach: alerts">
<tr data-bind="style: { backgroundColor: Color }">
<td>
<b data-bind="text: AlertText">Message</b>
</td>
</tr>
</tbody>
</table>
Each row of the table can have a different background color, and depending on that color, the text color should change to black or white. Here is a code snippet demonstrating the contrast calculation:
function getContrastYIQ(hexcolor){
var r = parseInt(hexcolor.substr(0,2),16);
var g = parseInt(hexcolor.substr(2,2),16);
var b = parseInt(hexcolor.substr(4,2),16);
var yiq = ((r*299)+(g*587)+(b*114))/1000;
return (yiq >= 128) ? 'black' : 'white';
}
I am looking for a way to dynamically change the text color based on the background color. Any help with implementing this functionality would be greatly appreciated. Thank you!