Avoiding color blindness penalty programmatically - javascript

I learned as a web developer that if the color contrast on a website is terrible, then I make very little money but I want to change that, however I ran into a problem. I have a section on my site where a user can select a color and the box is filled with that color. Let's say the color is already chosen. The box will then be like this in code for a black box:
<div ID="box" style="background:#000000;width:16px;height:16px">Text?</div>
The thing is the #000000 will change to another value based on the user's selection from running javascript. I feel that to make all CSS processors including google happy, I need to specify a foreground color so that its readable on any background color but I don't know the math behind this.
<script>
var x=(insert chosen color value);
var y=(some calculated value);
document.getElementById('box').style.background='#'+v;
document.getElementById('box').style.color='#'+y;
</script>
How do I determine the formula for foreground color regardless of the background color I choose to use so that the text is always readable?
OR
should I use a different HTML4 element to represent my color box?
and could I get away with this without having to make an image of just color boxes?
More added code
Run this code to get a sample of the strip of colours I use for my colour box.
<div ID="BOX" style="width:100%"></div>
<script>
var body=document.getElementById('BOX');
for (n=0;n<15;n++){
var box=document.createElement('DIV');
box.style.width='20px';
box.style.height='20px';
v=n.toString(16);
box.style.background='#'+v+v+v+v+v+v;
body.appendChild(box);
}
</script>

This is my old function for check and create a color contrast (I use this in a color picker).
This is the line you can change for test the function:
var hexcolor = '#333333'; // <--- change this for test
Fiddle
HTML:
<div id="bckgrd" >
<div id="txt">
TEST CODE
</div>
</div>
THE CSS:
html, body {
background-color:#ff0000;
}
#bckgrd {
display:inline-block;
width:100%;
font-size:18px;
}
THE JAVASCRIPT:
function colorContrast(color) {
var r = hexToRgb(color).r;
var g = hexToRgb(color).g;
var b = hexToRgb(color).b;
var rB = 255, gB = 255, bB = 255;
var rN = 0, gN = 0, bN = 0;
var cB = Math.abs(r - rB) + Math.abs(g - gB) + Math.abs(b - bB);
var br1 = (299*r + 587*g + 114*b);
var br2 = (299*rB + 587*gB + 114*bB);
var dB = Math.abs(br1 - br2);
var cN = Math.abs(r - rN) + Math.abs(g - gN) + Math.abs(b - bN);
br2 = (299*rN + 587*gN + 114*bN);
var dN = Math.abs(br1 - br2);
if ((cB>500) && (dB>125)){
return '#ffffff';
} else if ((cN>500) && (dN>125)){
return '#000000';
} else {
if ( ((0.2*cB) + (0.8*dB)) > ((0.2*cN) + (0.8*dN)) ) {
return '#FFFFFF';
} else {
return '#000000';
}
}
}
function hexToRgb(hex) {
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
var hexcolor = '#333333'; // <--- change this for test
$('#txt').css('color', hexcolor);
$('#bckgrd').css('background-color', colorContrast(hexcolor));

Related

Create a localstorage for my background color

I have a button that randomly generates a background color every time you click it. I want to make it a localstorage function so that every time I close or reload the page my last clicked background color remains on the webpage.
var link = document.getElementById("bglink");
var output = document.getElementById("output");
link.addEventListener("click", getRandom);
function getRandom(){
var newColor = '#'+Math.floor(Math.random()*16777215).toString(16);
var rgbColor = newColor.replace('#','');
var r = parseInt(rgbColor.substring(0,2), 16);
var g = parseInt(rgbColor.substring(2,4), 16);
var b = parseInt(rgbColor.substring(4,6), 16);
var result = 'rgba(' + r + ',' + g + ',' + b + ')';
document.body.style.backgroundColor = newColor;
output.textContent = newColor + " - " + result;
}
$("#bglink").click(function () {
var bgcolor = document.body.style.backgroundColor;
localStorage.setItem("bgcolor", document.body.style.backgroundColor);
alert('Background colour ' + bgcolor + ' saved in localStorage');
});
On reload, the page should be set to last color that was set when clicking the button.
You just have to add this to check if bgColor is set when the document is ready and set the background color.
This should be all you need:
$(function() {
let bgColor = localStorage.getItem('bgcolor');
if (bgColor) {
document.body.style.backgroundColor = bgColor;
}
});
Hope that helps,
Just add this at the top of your file:
document.body.style.backgroundColor = localStorage.getItem("bgcolor") || "#FFF";
//White is default color if no saved color
Here is a very simple way to save background color to local storage.
HTML
<input type="color" id="colorID" oninput="changeColor()">
JavaScript
function changeColor() {
var userColor = document.getElementById('colorID').value;
localStorage.setItem('storedValue', document.body.style.backgroundColor = userColor);
}
if(localStorage.storedValue) {
document.getElementById('colorID').value = localStorage.storedValue;
document.body.style.backgroundColor = localStorage.storedValue;
}
CodePen Demo
https://codepen.io/joshstovall/pen/PrJveQ

How to set a background color with respect to near in jquery

I have got a task to set background color for each div with slightly different color of near.
The div is generating dynamically.So how can i set the background color with this div?
For eg: I have a starting color of #fdecbb
I need a related color of the above. May be I need 10 or less.
var x =parseInt($('#colorNo').val());
var y = $('#colorCode').val();
for(var i =1;i<x;i++)
{
$('#hai').append($('<div class="colorcode">'+i+'</div>'));
}
The CSS
.colorcode
{
background-color:#86173e;
width:100px;
height:100px;
margin-top:10px;
}
The HTML
<div id="hai"><input type="text" value="5" id="colorNo"/><input type="text" value="#fdecbb" id="colorCode"/></div>
Demo :Fiddle
Find the closest / nearest HEX color of a small set of colours
The JavaScript
$(document).ready(function() {
function getSimilarColors (color) {
var base_colors=["660000","990000","cc0000","cc3333","ea4c88","993399","663399","333399","0066cc","0099cc","66cccc","77cc33","669900","336600","666600","999900","cccc33","ffff00","ffcc33","ff9900","ff6600","cc6633","996633","663300","000000","999999","cccccc","ffffff"];
//Convert to RGB, then R, G, B
var color_rgb = hex2rgb(color);
var color_r = color_rgb.split(',')[0];
var color_g = color_rgb.split(',')[1];
var color_b = color_rgb.split(',')[2];
//Create an emtyp array for the difference betwwen the colors
var differenceArray=[];
//Function to find the smallest value in an array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
//Convert the HEX color in the array to RGB colors, split them up to R-G-B, then find out the difference between the "color" and the colors in the array
$.each(base_colors, function(index, value) {
var base_color_rgb = hex2rgb(value);
var base_colors_r = base_color_rgb.split(',')[0];
var base_colors_g = base_color_rgb.split(',')[1];
var base_colors_b = base_color_rgb.split(',')[2];
//Add the difference to the differenceArray
differenceArray.push(Math.sqrt((color_r-base_colors_r)*(color_r-base_colors_r)+(color_g-base_colors_g)*(color_g-base_colors_g)+(color_b-base_colors_b)*(color_b-base_colors_b)));
});
//Get the lowest number from the differenceArray
var lowest = Array.min(differenceArray);
//Get the index for that lowest number
var index = differenceArray.indexOf(lowest);
//Function to convert HEX to RGB
function hex2rgb( colour ) {
var r,g,b;
if ( colour.charAt(0) == '#' ) {
colour = colour.substr(1);
}
r = colour.charAt(0) + colour.charAt(1);
g = colour.charAt(2) + colour.charAt(3);
b = colour.charAt(4) + colour.charAt(5);
r = parseInt( r,16 );
g = parseInt( g,16 );
b = parseInt( b ,16);
return r+','+g+','+b;
}
//Return the HEX code
return base_colors[index];
}
//Just for the demo
$('button').click(function(){
$('.base_color').css('backgroundColor',$('input').val());
$('.nearest_color').css('backgroundColor','#'+getSimilarColors($('input').val()));
return false;
});
});
The HTML
Get the closest color
<p>Base color:</p>
<div class="base_color"></div>
<p>Closest color:</p>
<div class="nearest_color"></div>
The CSS
div {
width:50px;
height:50px;
margin:0 0 0 20px;
}
p {
margin:20px;
}
Fiddle
I tried something like this:
From a rgb code, I randomly choose R,G or B value, and I randomly add or substract a value (here defined in step variable, so as you can change it the way you want).
$(function(){
var step = 10;
$('#new').on('click',function(){
$lastDiv = $('#wrapper > div:last');
nearColor = $lastDiv.css('backgroundColor');
nearColor = nearColor.replace('rgb(','').replace(')','').split(', ');
rgb = Math.floor(Math.random() * (3));
plusminus = Math.floor(Math.random() * (2)) + 1;
colorToChange = nearColor[rgb];
if(1 === plusminus){
colorToChange = (255 == colorToChange) ? 255-step : Math.min(parseInt(colorToChange)+step,255);
}
else {
colorToChange = (0 == colorToChange) ? step :Math.max(parseInt(colorToChange)- step,0);
}
nearColor[rgb] = colorToChange;
$lastDiv.after('<div style="background:rgb('+nearColor.join()+')" ></div>');
});
});
You can check the fiddle: here

My (simple) javascript works in every browser but Firefox - Why?

For universoty we had to "build" a xmas tree (svg) and use javascript to make the stars (ger stern(e)) rotate and the balls (ger (kugel(n)) change colors - one star had to be a shooting star. Everything work full points... but one penalty point as it doesn't work in Firefox
Does anyone has any idea why not?
The SVG is down below.
https://www.dropbox.com/s/vi4lxgortgyeq3f/uebung4.svg
Thanks in advance... and please keep in mind it's my very first time to use javascript :D
<script type="text/javascript">
function farbe()
{
var a = "#ff0000";
var b = "#007f00";
if (document.getElementById("kugeln").style.fill == a)
{
document.getElementById("kugeln").style.setProperty('fill', b);
}
else
{
document.getElementById("kugeln").style.setProperty('fill', a);
}
}
var initialTheta = 0;
var thetaDelta = 0.3;
var delay = 10;
var stern;
var timer;
function drehen()
{
stern = document.getElementById("stern_1");
stern.currentTheta = initialTheta;
timer = setInterval(Animation, delay);
stern_2 = document.getElementById("stern_2");
stern_3 = document.getElementById("stern_3");
stern_4 = document.getElementById("stern_4");
}
function stop()
{
clearInterval(timer);
return;
}
function Animation()
{
stern.setAttribute("transform", "rotate(" + stern.currentTheta + " 50,50)");
stern.currentTheta += thetaDelta;
stern_2.setAttribute("transform", "rotate(" + stern.currentTheta + " 50,50)");
stern.currentTheta += thetaDelta;
stern_3.setAttribute("transform", "rotate(" + stern.currentTheta + " 50,50)");
stern.currentTheta += thetaDelta;
stern_4.setAttribute("transform", "rotate(" + stern.currentTheta + " 0,2000)");
stern.currentTheta += thetaDelta;
}
The drehen function gets called two times in a row for each mouse over, so you are calling two times setInterval but recording only the last return value. You should call clearInterval before setting the new one.
Try something like
if(timer != undefined){
clearInterval(timer);
}
timer = setInterval(Animation, delay);
You are comparing colours against hex values
var a = "#ff0000";
if (document.getElementById("kugeln").style.fill == a)
UAs don't have to return colours as hex values and in fact Firefox does not. It will convert your colour to an rgb or rgba representation. If you add an alert
alert(document.getElementById("kugeln").style.fill);
you'll see Firefox returns rgb(255, 0, 0) as the colour which is the same as #ff0000 expressed in a different way. So you could add a check for this kind of colour format or...
A more robust solution would be to have a visiblity:hidden element with the colour you want to compare to and then check against the fill property of that.

Generating a random color not working

I was working on a simple project, to have the background of a webpage change every time you click on it. I succeeded in such, tested it a few times, save, tested again, and then left.
I go home and load it.. And it no longer works. I am using the same browser, I have no idea how anything could have changed.. I must have messed up a few ways almost impossible it feels like.. But alas, I'm sitting here dumb-founded..
Could anyone take a look at my simple program and tell me what is wrong? (Again, the program purpose is to change the webpage's background color to a random color whenever you click on the page.)
Here is the code:
<!DOCTYPE HTML PUBLIC>
<html>
<head>
<title>Random Colors</title>
<script language="javascript">
function randomColor() {
var h0 = Math.floor(Math.random()*99);
var h1 = Math.floor(Math.random()*99);
var h2 = Math.floor(Math.random()*99);
var h3 = Math.floor(Math.random()*99);
var h4 = Math.floor(Math.random()*99);
var h5 = Math.floor(Math.random()*99);
return '#'.toString(16)+h0.toString(16)+h1.toString(16)+h2.toString(16);+h3.toString(16)+h4.toString(16)+h5.toString(16);
}
</script>
</head>
<body onclick="document.bgColor=randomColor();">
</body>
</html>
Thanks in advance if anyone can help.
Having '#'.toString(16) makes no sense, the string '#' can't be converted to a string in hexadecimal form...
You have an extra semicolon after h2.toString(16).
return '#'+h0.toString(16)+h1.toString(16)+h2.toString(16)+h3.toString(16)+h4.toString(16)+h5.toString(16);
I think that you want to keep each digit in the range 0-15 instead of 0-98:
var h0 = Math.floor(Math.random()*16);
Try this out. Built off of what #Guffa did
function randomColor() {
var h0 = Math.floor(Math.random()*16);
var h1 = Math.floor(Math.random()*16);
var h2 = Math.floor(Math.random()*16);
var h3 = Math.floor(Math.random()*16);
var h4 = Math.floor(Math.random()*16);
var h5 = Math.floor(Math.random()*16);
return '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
}
Here's the fiddle --> http://jsfiddle.net/Jh5ms/1/
Is there a reason you're using Math.random so many times?
function pad6(s) {
s = '' + s;
return '000000'.slice(s.length) + s;
}
function randomColor() {
var rand = Math.floor(Math.random() * 0x1000000);
return '#' + pad6(rand.toString(16)).toUpperCase();
}
randomColor(); // "#7EE83D"
randomColor(); // "#19E771"
As pointed out by Guffa, your first error was attempting to convert '#' to a hexadecimal representation.
This should do the trick:
function randomColor() {
var ret = Math.floor(Math.random() * (0xFFFFFF + 1)).toString(16);
return ('#' + new Array((6 - ret.length) + 1).join('0') + ret);
}
window.onload = function() {
document.querySelector('button').onclick = function() {
document.querySelector('body').style.backgroundColor = randomColor();
};
};
Here is a demonstration.
Here is another demonstration showing how you could implement it into your current page. I also took the liberty of changing your event handler to be unobtrusive.
Adding to Guffa fixing the Math.random()*99 problem, I would put all this in a loop like this:
var theColor = "#";
for (var i = 0; i < 6; i++) {
theColor += Math.floor(Math.random() * 16).toString(16);
}
return theColor;
Here's a jsFiddle
another answer in your format - pass this to whatever you want to change backgroundcolor
http://jsfiddle.net/FpLKW/2/
<div onclick="test(this);">
</div>
function test (ele) {
var h0 = Math.floor(Math.random()*10);
var h1 = Math.floor(Math.random()*10);
var h2 = Math.floor(Math.random()*10);
var h3 = Math.floor(Math.random()*10);
var h4 = Math.floor(Math.random()*10);
var h5 = Math.floor(Math.random()*10);
var x = '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
ele.style.backgroundColor=x;
}

JavaScript -Change CSS color for 5 seconds - How to add easing effect?

With the reference to this question:-
JavaScript -Change CSS color for 5 seconds
Working demo of the answer:-
http://jsfiddle.net/maniator/dG2ks/
I need to know how i can add an easing effect to it, so that slowly and slowly color get 100% opaque and similarly get 100% transperent.
Code
function makeRGBStr(obj) {
if (obj.a == null) return "rgb(" + obj.r + "," + obj.g + "," + obj.b + ")";
else return "rgba(" + obj.r + "," + obj.g + "," + obj.b + "," + obj.a + ")";
}
window["highlight"] = function(obj, color) {
var highlightColor = color || {
"r": 255,
"g": 0,
"b": 0
};
var orig = obj.style.backgroundColor;
var curAlpha = 1;
obj.style.backgroundColor = makeRGBStr(highlightColor);
setTimeout(function() {
curAlpha -= 0.1;
var newColor = highlightColor;
newColor.a = curAlpha;
obj.style.backgroundColor = makeRGBStr(newColor);
if (curAlpha <= 0) {
obj.style.backgroundColor = orig;
}
else {
setTimeout(arguments.callee, 100);
}
});
}
jsFiddle: http://jsfiddle.net/dG2ks/32/
Some examples
Highlight if specific $_GET variable is present:
Code: http://jsfiddle.net/dG2ks/36/, see it in action: http://jsfiddle.net/dG2ks/36/show/?someVar=there
Highlight table cell: http://jsfiddle.net/dG2ks/38/
Highlight all table cells with different colors: http://jsfiddle.net/dG2ks/40/
You can add the jquery library, combined with jquery ui - if you don't use it already - and use the switchClass method.
All info here : http://jqueryui.com/demos/switchClass/
It will only take 5 lines to do what you want :
Place jquery en jquery ui in the head section of your page (2 lines of code).
These are the remotely hosted files, you can copy/paste the code 'as is'.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>
And then, at the end of the body, place a script that contains these three lines of code :
$(".yourbutton".click(function() {
switchClass('.currentclass','.redclass',500)
// transition from .currentclass to .redclass in 500 milliseconds
});

Categories