Choosing white or black text to contrast with a light or dark background

Today I needed a way to switch to using white text if the background was particularly dark.

24ways.org had a blog post on the topic, which offered this small javascript function.

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}

I made two changes.  First, I realized that my hexcolors often had the “#” at the beginning.  But, this would break the function, causing it to return “white” only.  So, I simply replaced the # if it existed in the input bu changing “hexcolor” to “hexcolor.replace(‘#’, ”)”.

function getContrast50(hexcolor){
    return (parseInt(hexcolor.replace('#', ''), 16) > 0xffffff/2) ? 'black':'white';
}

Next, I found that for the “middle” background colors which would work well with either white or black, I preferred to stick with black.  I only wanted to switch to white if the black text would be unreadable.  This was easy to change by changing the constant I divided by from 2 to 4.

function getContrast50(hexcolor){
     return (parseInt(hexcolor.replace('#', ''), 16) > 0xffffff/4) ? 'black':'white';
}
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s