Archive for the ‘Code’ Category

Prototype + Slideshow

Saturday, September 13th, 2008

Here’s a snippet of code I put together for my animation and interactivity class.  It’s a slideshow that uses Prototype and

View a demo

Here’s the JavaScript that appears in the header:

<script language="JavaScript" type="text/javascript">
var i = 0;
var slide;

function SlideShow() {
$( slide[i] ).fade({ duration:5 });
if (i == slide.length) i = 0;
$( slide[i] ).appear({ duration:5, afterFinish: function () { SlideShow(); } });

document.observe(`dom:loaded`, function () {
$$(`#myslideshow img`).each(function(image){
slide = $(`myslideshow`).childElements();
$( slide[0] ).appear({ duration:1, afterFinish: function () { SlideShow(); } });

Some basic CSS also appears in the header to place the images in the right location on the page:

<style type="text/css">


This basic HTML appears in the body to load the images for the slideshow. Any number of images can be added here:

<div id="myslideshow">
<img src="images/IMG_0350.jpg" width="600" height="450" />
<img src="images/IMG_0351.jpg" width="600" height="450" />
<img src="images/IMG_0352.jpg" width="600" height="450" />
<img src="images/IMG_0353.jpg" width="600" height="450" />
<img src="images/IMG_0354.jpg" width="600" height="450" />

This slideshow uses several Prototype and functions. It uses two basic combination effects, Fade and Appear. Other functions:

$document.observe() keeps the functions from starting until the page has loaded. For instance, if the images haven’t been quite loaded and the scripts start to run, things could go wrong or nothing could happen at all.

document.observe('dom:loaded', function () {
//place scripts here

$(‘element’).childElements() allows us to grab all the items nested inside of an object on the page. In this case we want to grab all the images that are in the “myslideshow” div to use in the slideshow. The items are then stored in an array which we called “slide”.

slide = $('myslideshow').childElements();

afterFinish is used in the appear function in several places. It allows us to call a function after the current slide has faded in. In the SlideShow function notice that in the appear function for afterFinish we actually call the function itself–SlideShow refers to itself. This is what’s called a recursive function. This causes the slideshow to loop.

$( slide[i] ).appear({ duration:5, afterFinish: function () { SlideShow(); } });