Solved

Setting Font Color Based on Background Color

Posted on 2014-01-10
3
1,557 Views
Last Modified: 2014-01-10
This isn't anything pressing, just a shot at an enhancement that would be pretty darn cool if I could get it to work right.  We have an application that allows its users to set the background color of a content area.  The text is black, so if you select a dark color, there are major contrast issues.  Up until now, we've asked the users to manually set the font color via the inline editor to correct the contrast issue.  On a whim, I threw something together that I thought would rightly handle the contrast issue on the fly.  For the most part, it works, but there are exceptions.  Basically, what I am doing is checking the NaN of the first character of the hex value that the user chooses for the background.  If it's a number, of if it is 'f', I set the font color to black.  Otherwise, I set the font color to white.  Has anyone done something like this and worked out all of the 'exceptions'?  The boss doesn't feel like we should spend any more time on it, since we have other more pressing issues, but I'd sure like to see it work.  :)

Here's my code:
$('#contentCallBack').jPicker(
	{},
	function(color, context){
		var all = color.val('all');
		$('#layoutBG').attr('bgcolor',(all && '#' + all.hex));
		$('#sideBarGBG').attr('bgcolor',(all && '#' + all.hex));
		var positionOne = all.hex.substring(0,1);
		if(isNaN(positionOne) == false || positionOne == 'f'){
			$('#layoutBG').css({
				color: '#ffffff'
			});
		} else {
			$('#layoutBG').css({
				color: '#000000'
			});
		}
	},
	function(color, context){
		if (context == layoutBGCallbackButton.get(0)) alert('Color set from button');
		var hex = color.val('hex');
		layoutBGCallbackElement.css({
			backgroundColor: hex && '#' + hex || 'transparent'
		});
	},
	function(color, context){
		//alert('"Cancel" Button Clicked');
	}
);

Open in new window

0
Comment
Question by:brianmfalls
3 Comments
 
LVL 25

Assisted Solution

by:Lee Savidge
Lee Savidge earned 400 total points
ID: 39771086
If you have a function that decides if a colour is "dark" then you can set a "light" text colour.

I've not personally done it myself but I've seen this used with some success:

stackoverflow.com/questions/6750695/jquery-change-text-color-based-on-containing-elements-background-color

Basically it determines if the colour is a dark one and if so it sets the text as white, otherwise it uses black.

I had some code a while ago which I wrote which altered the text color based on a background colour in a windows application by XORing the values. Can't find it now. It works for most colours. Some don't work, some look awful but do work but then it wasn't me that had to look at the colours a user had chosen for themselves.
0
 
LVL 32

Accepted Solution

by:
Big Monty earned 100 total points
ID: 39771358
taken from stackoverflow.com/questions/9600295/automatically-change-text-color-to-assure-readability, this may give you what you're looking for:

function invertColor(hexTripletColor) {
    var color = hexTripletColor;
    color = color.substring(1);           // remove #
    color = parseInt(color, 16);          // convert to integer
    color = 0xFFFFFF ^ color;             // invert three bytes
    color = color.toString(16);           // convert to hex
    color = ("000000" + color).slice(-6); // pad with leading zeros
    color = "#" + color;                  // prepend #
    return color;
}
$("h1")
    .css("background-color", "#FFCC00")
    .css("color", invertColor("#FFCC00"));

Open in new window

0
 
LVL 1

Author Closing Comment

by:brianmfalls
ID: 39771863
Thanks for the help friends.  Here's the finished product, all cleaned up, dynamically looped, and so on...

	<script type="text/javascript">
		$(document).ready( function() {
			
				function isDark(color) {
					var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
					return parseFloat(match[1])
						 + parseFloat(match[2])
						 + parseFloat(match[3])
						   < 3 * 256 / 2; // r+g+b should be less than half of max (3 * 256)
				}
			
				<cfoutput query="gto">

					$('###gto.containerID#').attr('bgcolor','###gto.value#');
					$('###gto.containerID#').css({
						backgroundColor: '###gto.value#'
					});
					<cfif len(gto.supportContainerID)>
						$('###gto.supportContainerID#').attr('bgcolor','###gto.value#');
						$('###gto.supportContainerID#').css({
							backgroundColor: '###gto.value#'
						});
					</cfif>
					
					var #gto.fieldID#CallbackElement = $('###gto.containerID#')
					$('###gto.fieldID#').jPicker(
						{},
						function(color, context){
							var all = color.val('all');
							var hex = color.val('hex');
							$('###gto.containerID#').attr('bgcolor',(all && '##' + all.hex));
							$('###gto.containerID#').css({
								backgroundColor: hex && '##' + hex || 'transparent'
							});
							<cfif len(gto.supportContainerID)>
								$('###gto.supportContainerID#').attr('bgcolor',(all && '##' + all.hex));
								$('###gto.supportContainerID#').css({
									backgroundColor: hex && '##' + hex || 'transparent'
								});
							</cfif>
							$('###gto.containerID#').css("color", isDark($(this).css("background-color")) ? 'white' : 'black');
							var emailID = '#session.emailID#'
							var fieldID = '#gto.fieldID#'
							$('##templateOptionBlock').load('http://#cgi.server_name#/admin/#application.module#/act/act.template.options.cfm',{'emailID': emailID, 'fieldID': fieldID, 'value': hex}, function() {
								//alert('#gto.title# Saved');
							});
						}
					);
				</cfoutput>
					
			});
	</script>

Open in new window

0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

This is a how to build your own CSS3 slideshow and when I say CSS3 I mean just CSS with no javascript in sight! There a few examples online of how to do this but most just show you an example without any explanation, others make it more complicat…
Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now