JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://fb.me/JSXTransformer-0.11.1.js"></script>
<script src="http://fb.me/react-with-addons-0.11.1.js"></script>
<p><strong>Demonstration of <a target="_blank"
href="http://stackoverflow.com/a/3943023/1404185"
> computing contrasting text color</a></strong></p>
<p>Clicking in box below brings up a color picker on <a href="http://caniuse.com/#feat=input-color" target="_blank"> Firefox or Chrome</a>, or enter a hex color value in the text input field.</p>
<div id="app"></div>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
JavaScript 1.7
/** @jsx React.DOM */
var computeTextColor= function(color, simple) {
var r = hexToR(color);
var g = hexToG(color);
var b = hexToB(color);
if (simple) {
return ((r * 0.299 + g * 0.587 + b * 0.114) > 186) ?
'#000000' : '#ffffff';
} // else complex formula
var uicolors = [r / 255, g / 255, b / 255];
var c = uicolors.map((c) => {
if (c <= 0.03928) {
return c / 12.92;
} else {
return Math.pow((c + 0.055) / 1.055,2.4);
}
});
var L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
//console.log(L);
return (L > 0.179) ? '#000000' : '#ffffff';
};
/* Hex to RGB conversion:
* http://www.javascripter.net/faq/hextorgb.htm
*/
var cutHex= function(h) {
return (h.charAt(0) == "#") ? h.substring(1, 7) : h
};
var hexToR= function(h) {
return parseInt((cutHex(h)).substring(0, 2),16)
};
var hexToG= function(h) {
return parseInt((cutHex(h)).substring(2, 4),16)
};
var hexToB= function(h) {
return parseInt((cutHex(h)).substring(4, 6),16)
};
var Application = React.createClass({
componentWillMount: function() {
this.changeColor("#fda228")
},
render: function() {
return (
<div>
<div>
<input type="color"
value={this.state.color}
onChange={this.changeColorText}/>
<p/>
<input type="text"
value={this.state.color}
onChange={this.changeColorText}
style={{marginBottom: 20}}/>
</div>
<p/>
<span style={{backgroundColor: this.state.color,
height: 140,
fontSize: 45,
textAlign: 'center',
padding: 15,
color: this.state.complexColor,
marginRight: 20}}>
Complex
</span>
<span style={{backgroundColor: this.state.color,
...