Solved

Setting Font Color Based on Background Color

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Problem in javascript 17 58
sort Multi-dimensional array 6 44
allow link tag to be submit like form 15 60
Leaflet map example works but I want to make a change to it 5 27
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to style different bullet points for unordered lists in CSS. Begin with a normal unordered list; the default bullet point is a solid circle: In the CSS, create a defined class of unordered list by typing "ul.S…
In this tutorial viewers will learn how to style a decorative dropcap for the first letter in a paragraph using CSS. In CSS, create a new paragraph class by typing "p.fancy": Then, to style only the first letter of the first sentence, include the ps…

734 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