Random Colors: Easier Than You’d Expect


I recently launched “Random Colors” – an immersive, full page block of randomly-generated-on-the-fly colors with smooth cross-fades. The concept is super easy to implement – using random colors within webpages – so I’m going to walk through the code here. All it takes is some CSS3 and JavaScript (I’m also using jQuery since I’d included it anyway, but subbing this part out is also straightforward). The CSS3 transitions achieve the beautiful cross-fading, but keep in mind that it requires the most modern browsers (including Internet Explorer 10); however, the random colors will still work with older browsers.

The CSS

#selector {
background-color: #ababab;/*default*/
transition: background-color 3s ease; /* future-proof */
-webkit-transition: background-color 3s ease;
-moz-transition: background-color 3s ease;
-o-transition: background-color 3s ease;
-ms-transition: background-color 3s ease;/* IE10+ only */
}

The JavaScript

function randomColor(){
 r = Math.floor(Math.random() * (256));
 g = Math.floor(Math.random() * (256));
 b = Math.floor(Math.random() * (256));
 jQuery('body').css('background-color','rgb('+r+','+g+','+b+')');
}

jQuery(document).ready(function(){ randomColor(); var t = setInterval(randomColor,3000); });

That’s It!

In order to implement random colors, just add the css and javascript, and make sure you’ve included jQuery. Be sure to put in your own selectors, and remember that multiple selectors can be used, or separate random colors can be generated simultaneously. Frequency of color change and crossfade duration are also easily editable.

Happy coding!

One thought on “Random Colors: Easier Than You’d Expect

Comments are closed.