?
Solved

Setting Font Color Based on Background Color

Posted on 2014-01-10
3
Medium Priority
?
1,834 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 25

Assisted Solution

by:Lee Savidge
Lee Savidge earned 1600 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 400 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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

So you have coded your own WordPress plugin and now you want to allow users to upload images to a folder in the plugin folder rather than the default media location? Follow along and this article will show you how to do just that!
This article discusses how to create an extensible mechanism for linked drop downs.
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 receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Suggested Courses

770 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