Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Setting Font Color Based on Background Color

Posted on 2014-01-10
3
Medium Priority
?
1,899 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 34

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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
This article discusses how to create an extensible mechanism for linked drop downs.
In this tutorial viewers will learn how add a full-size background image to a webpage using CSS3. Create a new HTML document with an internal stylesheet.: In CSS, define the html element to have a background image. Use a high resolution image.: In t…
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…

609 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