Prototype image slider

In my post titled Captions over images I advocate the use of definition lists for captioning images. Earlier today I was asked whether this meaningful markup could be used in conjunction with an "image slider" such as Easy Slider 1.5.

I had a look at the Easy Slider source code and decided to write my own image slider using Prototype rather than hacking someone else's code to pieces. It's a proof of concept rather than a full-blown "plugin", but it demonstrates that such functionality is achievable using elegant, meaningful markup.

Check out the Prototype image slider demo to see the code in action.

Update —

I noticed that the script was failing miserably in Safari, which didn't like the following line:

li: new Element('li', { class: 'prev' }),

Wrapping the word "class" in quotes as per this recommendation by Tobie Langel did the trick!

Usage

First, you'll need to save a copy of prototype-image-slider.js (≈2.7 kB).

To create a new Slider simply call the constructor. The constructor requires one argument, either a DOM node or a string that references a node's ID.

new Slider('slider');

There's nothing to prevent multiple image sliders from appearing on a page. The following code turns each div with class of 'slider' into a Slider object.

$$('div.slider').each(function (e) {
    new Slider(e);
})

Of course, it's a good idea to wait until the page is ready to be manipulated before… er… manipulating the page.

document.observe('dom:loaded', function () {
    $$('div.slider').each(function (e) {
        new Slider(e);
    });
});

To provide a small degree of flexibility, the constructor accepts two optional arguments: a float specifying the duration of each transition, and an integer specifying the number of the slide to be displayed first. The default values are 1.0 and 0 (slides are numbered from zero).

new Slider('slider', 0.5);     // faster transitions
new Slider('slider', 1.0, 3);  // fourth slide displayed first
new Slider('slider', 1.0, -1); // last slide displayed first
new Slider('slider', 1.5, -1); // slower transitions; last slide displayed first

If you find this code useful and would like me to flesh it out, let me know.

Update —

I neglected to mention that this code also requires script.aculo.us.

Comments

is possible to make autoslide. When the page load, the images will slide automaticaly ? Thanks

I'm not sure whether this is the effect you're after, Miroslav, but changing...

$$('div.slider').each(function (e) {
    new Slider(e);
});

to...

$$('div.slider').each(function (e) {
    var slider = new Slider(e);
    slider.next();
});

will result in the first image immediately sliding out of view to be replaced by the second image.

If you want the images to continue to slide automatically, I suggest looking for another solution. While this code could be hacked to achieve continuous sliding, it was not written with this behaviour in mind.

Respond