colour.js is a small (4KB minified and gzipped) JavaScript library which can parse any CSS colour definition, convert the results between RGB and HSL, and perform various transformations.
For a page which makes extensive use of colour.js, have a look at The Colour Toy.
Download the zipball or tarball, put colour.min.js in your project, and link to it in in your HTML:
<head>
...
<script type="text/javascript" src="path/to/colour.min.js"></script>
...
</head>
You knew that already, right?
Full API documentation is in the README.
var colourString = "hotpink", // maybe this came from a user preference or something
baseColour = new Colour(colourString), // create colour object for hotpink
shaded = baseColour.darken(0.5), // looks like this
textColour = baseColour.contrast(); // is #111
// using jQuery syntax here, but could apply to anything:
$(".customized").css({
"background-color": baseColour.toString(), // "#ff69b4"
"border-color": shaded.toString(), // "#b30059"
"color": textColor.toString() // "#111111"
});
Notice how each operation returns a new Colour object, leaving baseColour untouched.
Copyright (c) 2010, Neil de Carteret
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name "Neil de Carteret" nor the names of any contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY NEIL DE CARTERET ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL NEIL DE CARTERET BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Neil de Carteret (n3dst4@gmail.com)
You can download this project in either zip or tar formats.
You can also clone the project with Git by running:
$ git clone git://github.com/n3dst4/colour.js