An image gallery: Fade out

  1. Animation
  2. An image gallery
  3. Fade in

Create a fade function. This function will fade out until the opacity is zero, and then advance the slide. It will return true or false depending on whether the fade is done or not.

this.fade = function() {

var done = false;

var opacity =;

if (opacity=="") {

opacity = 1;


opacity -= .1;

if (opacity <= 0) {

opacity = 0;

done = true;

} = opacity;

if (opacity == 0) {

this.advance(); = 1;


return done;


This function checks the opacity of the parent DIV, and reduces it by .1 each time. Note that the first time through, the opacity doesn’t exist on the DIV’s style, so we need to check to see if it’s empty. If it is empty, we set it to 1. When opacity drops to zero, we set the “done” variable to true. We also compare “less than or equal to zero” instead of “equal to zero”, just in case the numbers we’re using drop it to below zero. We set opacity to zero to ensure that it never drops below zero.

At the end of the function, if opacity has reached zero, we advance the slide and reset opacity to 1 so that the slide is visible again.

During a fade, the advanceSlide function will use a very small number for the setTimeout method. Once the fade is completed, it will use the normal 5,000 milliseconds.

function advanceSlide() {

if (gallery.fade()) {

window.setTimeout(advanceSlide, 5000);

} else {

window.setTimeout(advanceSlide, 10);



It knows whether or not the fade has completed by whether or not gallery.fade returns true or false.

Fade out: -=

The symbol for “-=” is very similar to the symbol “--” and “++”. Where “--” reduces the variable by 1, “-=” reduces the variable by whatever is after the symbol. Setting “opacity -= .1” means “reduce opacity by .1”. There’s an equivalent for increasing a variable, and that’s “+=”, which we’ll start using when we set the new image to fade in.

Fade out: <=

The comparison “<=” means “less than or equal to”. We’re checking to see if “opacity is less than or equal to zero”.

  1. Animation
  2. An image gallery
  3. Fade in