Skip to content

Instantly share code, notes, and snippets.

@cdl
Last active December 30, 2015 16:09
Show Gist options
  • Save cdl/7853060 to your computer and use it in GitHub Desktop.
Save cdl/7853060 to your computer and use it in GitHub Desktop.
// colorjs.js
// @description An implementation of how I did the color changing background
// on my site. Essentially, I'm using the HSLA color space because
// it makes it really easy to control the general lightness of a
// color and maintain it throughout a bunch of hues. For instance:
// take a look at http://cl.ly/SrT1. Notice how all the colors
// have the same contrast? That's because all that's changed between
// them is the hue values. That's what we're replicating here.
//
// @requirements jQuery –– http://jquery.com/
// jquery-color –– https://github.com/jquery/jquery-color
function randomHue() {
// Generate a random number between 0 and 360 – this will be our hue.
var hue = Math.floor(Math.random()*360);
return hue;
}
// Set our colour values – see how we're keeping saturation and lightness
// constant? Alpha is just opacity, and we're not changing that either for
// this. The numbers will be the directly put into the hsla() CSS attribute,
// so be sure to have them be on a scale from 0 to 1.
var hue = randomHue();
var saturation = 0.74;
var lightness = 0.69;
var alpha = 1;
// Instatiate the colour as a jQuery.Color object
var color = jQuery.Color({ hue: hue, saturation: saturation, lightness: lightness, alpha: 1.0 });
// We want this colour to fade in, so copy the desired colour to a new object, but set the
// lightness to something brighter.
var firstColor = color.lightness(0.13);
$(window).load(function(){
// On load, set the background colour to that first (lightened colour)
$('body').css('background-color', 'hsl('+hue+','+0.13+','+lightness+')');
$('body').animate({
// Animate the backgroundColor to the generated color
backgroundColor: color
}, 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment