Skip to content

Commit 9cb8d0f

Browse files
Fulliganrecurser
authored andcommitted
Added adaptive text color
Added two functions. The name of the color now appears either in black or in white, depending of the brightness of the choosen color. Especially for very bright colors, you can't read a text with 'color: #FFFFFF'
1 parent 0b047de commit 9cb8d0f

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

jquery.simple-color.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* Licensed under the MIT license:
88
* http://www.opensource.org/licenses/mit-license.php
99
*
10-
* Version: 1.2.1 (Sat, 19 Aug 2017 07:42:40 GMT)
10+
* Version: 1.2.2 (Mon, 19 May 2014 20:22:47 GMT)
1111
*/
1212
(function($) {
1313
/**
@@ -236,6 +236,9 @@
236236
displayBox.css('background-color', displayBox.data('color'));
237237
if (options.displayColorCode) {
238238
displayBox.text(displayBox.data('color'));
239+
displayBox.css({
240+
'color': getTextColor(displayBox.data('color')),
241+
});
239242
}
240243
}
241244
// Execute onClose callback whenever the color chooser is closed.
@@ -300,6 +303,9 @@
300303
// If 'displayColorCode' is turned on, display the currently selected color code as text inside the button.
301304
if (options.displayColorCode) {
302305
event.data.displayBox.text(color);
306+
event.data.displayBox.css({
307+
'color': getTextColor(displayBox.data('color'))
308+
});
303309
}
304310

305311
// If an onSelect callback function is defined then excecute it.
@@ -361,3 +367,24 @@
361367
};
362368

363369
})(jQuery);
370+
371+
function getTextColor(color){
372+
373+
rgbColor = hexToRgb(color);
374+
textColor =
375+
0.213 * rgbColor.r/255 +
376+
0.715 * rgbColor.g/255 +
377+
0.072 * rgbColor.b/255
378+
< 0.5 ? '#FFFFFF' : '#000000';
379+
380+
return textColor;
381+
}
382+
383+
function hexToRgb(hex) {
384+
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
385+
return result ? {
386+
r: parseInt(result[1], 16),
387+
g: parseInt(result[2], 16),
388+
b: parseInt(result[3], 16)
389+
} : null;
390+
}

0 commit comments

Comments
 (0)