Friday, June 29, 2007

A simple JvaScript way to change element color

function gradient(id, start, end, speed, prop, callback){
var style = id.style || document.getElementById(id).style,
i = setInterval(function(){
for(var j = 0; j < 3; j++)
start[j] = gradient.run(start[j], end[j], speed);
style[prop] = gradient.color(start);
if(String(start) === String(end)) {
clearInterval(i);
if(typeof callback === "function")
callback(id);
}
}, 20);
start = gradient.rgb(start);
end = gradient.rgb(end);
speed = speed || 10;
prop = prop || "color";
return i;
};
gradient.color = function(c){return "#".concat(gradient.hex(c[0]), gradient.hex(c[1]), gradient.hex(c[2]))};
gradient.hex = function(rgb, c){return (c = rgb.toString(16)).length === 1 ? "0".concat(c) : c};
gradient.norm = function(c){return (c = c.substring(1)).length < 6 ? "".concat(c, c) : c};
gradient.rgb = function(c){return [parseInt((c = gradient.norm(c)).substr(0,2), 16), parseInt(c.substr(2,2), 16), parseInt(c.substr(4,2), 16)]};
gradient.run = function(x, y, speed) {return x < y ? Math.min(x + speed, y) : Math.max(x - speed, y)};


It's bytefx style and it could be used, for example in these ways:
onload = function(){
var div = document.createElement("div");
div.id = "test";
div.appendChild(document.createTextNode("Hello Gradient !"));
document.body.appendChild(div);
gradient("test", "#000000", "#FFFFFF", 10, "color", function(id){
gradient(id, "#FFFFFF", "#000000", 20, "backgroundColor", function(id){
gradient(id, "#FFFFFF", "#676767", 5)
})
});
};


... or in a Flash RollOver/Out style:
onload = function(){
var div = document.createElement("div");
div.id = "test";
div.appendChild(document.createTextNode("Hello Gradient !"));
document.body.appendChild(div);
div.colors = ["#000000", "#ABABAB"];
div.bgcolors = ["#FFFFFF", "#000000"];
div.newGradient = function(gradients){
if(this.gradients) {
clearInterval(this.gradients[0]);
clearInterval(this.gradients[1]);
};
this.gradients = [gradient.apply(null, gradients[0]), gradient.apply(null, gradients[1])];
};
div.onmouseover = function(){
this.newGradient([
[this.id, this.colors[0], this.colors[1]],
[this.id, this.bgcolors[0], this.bgcolors[1], 10, "backgroundColor"]
])
};
div.onmouseout = function(){
this.newGradient([
[this.id, this.colors[1], this.colors[0]],
[this.id, this.bgcolors[1], this.bgcolors[0], 10, "backgroundColor"]
])
};
};

Have fun with grandients and colors :-)

No comments:

Post a Comment