Solved

Setting Font Color Based on Background Color

Posted on 2014-01-10
3
1,633 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 33

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

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to position items using CSS's three positioning types Create a new HTML document with an internal stylesheet.: Create another div in CSS and name it Absolute : Type "position:absolute;" and "top:10px; left:50p…
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…

809 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