I am just learning Javascript and looking for some help with having a
series of quotes that will fade in and out of the website.
The easiest and most portable is to just change the color of the text
to match the background. If the background isn't a solid color, you'll
have to fade the text to transparent, which is not as widely supported
(it's not part of the current CSS standard, but will probably be in the
next one, many years from now).
To fade text from one color to the next, we'll need a function to
calculate the intermediate steps. For this I'll construct a Color-
object contructor with appropriate methods:
----
/** r,g,b must be integers in range [0,255] for toString to work */
function Color(r,g,b) {
this.r = r;
this.g = g;
this.b = b;
}
/** otherColor is a Color, degree is number in range [0..1] */
Color.prototype.blend = function blend(otherColor, degree) {
var invDegree = 1 - degree;
return new Color(Math.round(otherColor.r * degree + this.r * invDegree),
Math.round(otherColor.g * degree + this.g * invDegree),
Math.round(otherColor.b * degree + this.b * invDegree));
};
Color.prototype.toString = function toString() {
return "rgb(" + this.r + "," + this.g + "," + this.b + ")";
};
// then the animator
/**
* elem : element to apply style to
* styleProp: style property to assign color to (e.g. "color"
* or "backgroundColor")
* color1: starting color;
* color2: ending color
* steps : number of intermediate steps
* delay : number of milliseconds between steps (approx.)
* callback: optional function called when fading is complete.
* called with elem, styleProp and color2 as arguments.
*/
function fade(elem, styleProp, color1, color2, steps, delay, callback) {
var step = 0;
var id = setInterval(function() {
step++;
var newColor = color1.blend(color2, step/steps);
elem.style[styleProp] = newColor.toString();
if (step >= steps) {
clearInterval(id);
if (callback) {
callback(elem, styleProp, color2);
}
}
}, delay);
return id;
}
// then just use it: fade from black-on-white to orange-on-black in 0.5sec
fade(document.body, "color", new Color(0,0,0), new Color(0xff, 0x80, 0),
50, 10);
fade(document.body, "backgroundColor", new Color(255,255,255),
new Color(0, 0, 0), 50, 10);
---
You can the fade your quote in and out with this (assume the background is
white):
---
<blockquote id="myQuote" style="background:white;color:black;">
This is a quote
</blockquote>
<script type="text/javascript">
var quoteBlock = document.getElementById("myQuote");
var black = new Color(0,0,0);
var white = new Color(255,255,255);
var quotes = [
"This is a quote",
"This is NOT a quote",
"This is a puppy",
"Lorem ipsum etc"];
function gotoQuote(i) {
fade(quoteBlock,"color", black, white, 50, 20, function() {
quoteBlock.innerHTML = quotes
; // or however it's changed;
fade(quoteBlock, "color", white, black, 50, 20, function() {
setTimeout(function() {
gotoQuote((i+1)%quotes.length);
}, 5000); // next quote after 5 sec.
})
});
}
gotoQuote(1);
</script>