1

I have a simple question but that has not been answered before :

I have an option that allow visitors to change background-color, and I would like that my script change the font color to white when the background-color is dark and vice-versa.

Is there any simple way to do that in php or javascript/jquery ?

Maybe something like (the concept):

 #1599FF == 15 + 99 + 255 == 369;

369/((255*3)/2) == 369/382.5 == bright;
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
TOPKAT
  • 6,667
  • 2
  • 44
  • 72
  • background color of body? – Flatlineato Mar 30 '16 at 10:03
  • 1
    `#1599FF == 429` ! try `parseInt(colorString.substring(1,3), 16) + parseInt(colorString.substring(3,5), 16) + parseInt(colorString.substring(5,7), 16)` (because `hex 99 == dec 153`) – Meiko Rachimow Mar 30 '16 at 10:12
  • 1
    I think you could do it with CSS 3 and forget about JS, an example here http://stackoverflow.com/questions/16981763/invert-css-font-color-depending-on-background-color – cralfaro Mar 30 '16 at 10:16
  • @cralfaro : thanks nearly perfect i'll use it for the moment but the inconvenient is that is not cross browser..atMeiko thanks, you can edit the answer or i'll do it later ;) ; atFlatlineato yes body; – TOPKAT Mar 30 '16 at 10:50

1 Answers1

2

I do agree with gavgrif answer its one of the easiest way for static bgcolor ,Hence if user is going pick dynamic color as an background then its better to change text color according to

In below JS Fiddle on page load i am getting bg value of an background i.e rgb(220,110,140) taking its average and comparing with 127.5(average of i.e(255,255,255)) if its greater i am making text color has black else text color has white

https://jsfiddle.net/swaminathang/ezg47hag/2/

<div id="bgblock" >
<h1 id="textColor">
Hello world
</h1>

</div>

#bgblock{
 width:400px;
  height:200px;
  background-color:#000000;
}

$( document ).ready(function() {
var bgColorString , hexvalue,hexvalue1,hexvalue2,hexvalue3
bgColorString = $("#bgblock").css('backgroundColor').toString();
hexvalue = bgColorString.split("(")[1].split(")")[0]

hexvalue1 = parseInt(hexvalue.split(",")[0]) ;
hexvalue2 = parseInt(hexvalue.split(",")[1]) ;
hexvalue3 = parseInt(hexvalue.split(",")[2]) ;

var coloravg = (hexvalue1 + hexvalue2+hexvalue3)/3;
if(coloravg > 127.5){
$("#textColor").css("color","black");
}else{
$("#textColor").css("color","white");
 }


});
  • Yess perfect !! Your answer is goog, why not to copy paste it to the fiddle, because the fiddle seems not have been updated ? – TOPKAT Apr 01 '16 at 10:19