Skip to content

Instantly share code, notes, and snippets.

@joeegan
Created February 8, 2011 20:51
Show Gist options
  • Select an option

  • Save joeegan/817209 to your computer and use it in GitHub Desktop.

Select an option

Save joeegan/817209 to your computer and use it in GitHub Desktop.
randomHexCodeBgCycle.js
Egan.randomHexCodeCycle = function () {
function rgbToHex(rgb) {
var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(rgb),
red = parseInt(digits[2]),
green = parseInt(digits[3]),
blue = parseInt(digits[4]),
rgb = blue | (green << 8) | (red << 16);
return digits[1] + '#' + rgb.toString(16);
}
function randomHexCode (possibleHexChars,element,cssProperty) {
var newCodeArr = [];
var existingBg = element.style.getPropertyValue(cssProperty);
if (existingBg) var existingHexCode = rgbToHex(existingBg);
(function createNewHexArray(){
for(i=0; i<possibleHexChars.length; i++) {
newCodeArr.push(possibleHexChars[Math.floor(Math.random()*possibleHexChars.length)]);
}
}());
var newHexCode = "#"+newCodeArr.join("");
if (newHexCode !== existingHexCode)
return newHexCode;
else createNewHexArray();
}
function appendCss (element, cssProperty, startingHex, speed){
var cssTemplate = '\
$1 { \
$2: $3; \
-webkit-transition: $2 $4s ease-in; \
-moz-transition: $2 $4s ease-in; \
transition: $2 $4s ease-in; \
} ';
var cssMarkup = cssTemplate.replace(/\$1/g, '#'+element.id)
.replace(/\$2/g, cssProperty)
.replace(/\$3/g,'#'+ startingHex.join(''))
.replace(/\$4/g,speed/1000);
function injectCss (css) {
var head = document.getElementsByTagName('head')[0];
var styleTag = document.createElement('style');
styleTag.innerHTML = css;
head.appendChild(styleTag);
}
injectCss(cssMarkup);
}
return {
init : function (config) {
var element = config.element || document.body,
possibleHexChars = config.hexArray || ['a','b','c'],
initialHexChars = config.initialHexArray || ['a','b','c'],
interval = config.speed || 1000,
cssProperty = config.cssProperty || 'background';
appendCss(element, cssProperty, initialHexChars, interval);
var i=0;
if (i==0) element.style.setProperty(cssProperty, randomHexCode(possibleHexChars,element,cssProperty));
setInterval(function(){
element.style.setProperty(cssProperty, randomHexCode(possibleHexChars, element, cssProperty));
},interval)
}
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment