Create a Simple Slideshow Using MooTools

Christina Ricci

One excellent way to add dynamism to any website is to implement a slideshow featuring images or sliding content. Of course there are numerous slideshow plugins available but many of them can be overkill if you want to do simple slideshow without controls or events. We're going to create a simple slideshow from which we'll build on.

The HTML

<div id="slideshow-container">
	<img src="slideshow/cricci1.jpg" alt="Christina Ricci" />
	<img src="slideshow/cricci2.jpg" alt="Christina Ricci" />
	<img src="slideshow/cricci3.jpg" alt="Christina Ricci" />
	<img src="slideshow/cricci4.jpg" alt="Christina Ricci" />
	<img src="slideshow/cricci5.jpg" alt="Christina Ricci" />
</div>

The HTML is as simple as it can be -- one slideshow container DIV and the images that will be part of the show. This slideshow doesn't require that you use images -- you could just as easily use DIVs instead.

The CSS

#slideshow-container	{ width:512px; height:384px; position:relative; }
#slideshow-container img { display:block; position:absolute; top:0; left:0; z-index:1; }

It's important that the slideshow container receive a set height and width as well as its position set to relative. Slideshow items must have an absolute position with top and left set to 0.

The MooTools JavaScript

window.addEvent('domready',function() {
	/* settings */
	var showDuration = 3000;
	var container = $('slideshow-container');
	var images = container.getElements('img');
	var currentIndex = 0;
	var interval;
	/* opacity and fade */
	images.each(function(img,i){ 
		if(i > 0) {
			img.set('opacity',0);
		}
	});
	/* worker */
	var show = function() {
		images[currentIndex].fade('out');
		images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0].fade('in');
	};
	/* start once the page is finished loading */
	window.addEvent('load',function(){
		interval = show.periodical(showDuration);
	});
});

The first step in the slideshow creation process is to define the show duration, grab the container and slideshow items, etc. Then we cycle through each image/slide to set its opacity to 0 if it's not in the first position. Next we create the function that fades out the current image and fades in the next image. The last step is directing the slideshow to start when the page has completed loading. Simple!

More to Come

This post will be the first of many with regard to improving upon this simple slideshow. In future posts, we'll be adding start/stop/pause controls, table of contents, and making this simple slideshow a MooTools class with loads of options. In the mean time, enjoy this simple slideshow!


Comments

  1. Nickolas Simard

    Nice script, I’ll use that in a “class” manner. I have been using xFade (http://slayeroffice.com/code/imageCrossFade/xfade2.html) before, some experiment I found on the web a few years ago. I hadn’t the time to rewrite a Mootools version, and you did the job for me…

    Good work! ^^

  2. Davi Ferreira

    Hey David,

    just to say nice touch with the textmate/coda snippet buttons. Love your posts, keep it up!

  3. Nickolas Simard

    @Alex: You really writes touching stuff!

  4. René

    I Prefer a Class for this stuff to. But props. Never use periodical but just the function again with delay.

  5. David Walsh

    @René: Making the slideshow into a class will be the 3rd or fourth article of the series.

  6. Nickolas Simard

    @David Walsh: Indeed, that’s actually what I finally notice upon re-reading the article… Right below “More to Come”…
    Gee, I should read better! :D

  7. Ben

    @David Walsh: You need threaded comments :)

  8. xrado

    i did something similar some time ago http://xrado.hopto.org/post/moofader2

    greetings

  9. Tom

    Awesome, this is just what I need. I can’t wait for the next post to learn more.

  10. Adriaan

    Nice tut David, keep ‘em coming. I’m looking forward to the completed class…

  11. Ryan Florence

    I can already tell this is going to be … hmm … what’s the word? Gripping comes to mind.

  12. Kelvin

    Actually a slideshow exactly like this was my very first own created Mootools class :) still using it on alot of new projects

  13. George Dawson

    Thanks for sharing your slide show. You are half my age and three times farther along – and I am happy for you.

  14. George Dawson

    What I’d really like to know is how you get the banner menu to stay fixed.

  15. Rasmus

    You can use modulus (%) to shorten the code even more:

    images[currentIndex++].fade(‘out’);
    images[currentIndex %= images.length].fade(‘in’);

  16. Kael

    @Rasmus: Awesome, really tricky~~

  17. Dave Ladner

    David-

    Thanks! Exactly what I was looking for. Is there any way to set the fade time, to make the fade process longer or shorter?

  18. Pepua

    Hi there! My jQuery, Moo tools slideshow stopped working suddenly and I have no idea why since I haven’t touched in several weeks. It just doesn’t slide anymore and the images are spread on top of my posts.Can you check it up? I don’t know where to look for help. My blog is http://pepua.blogspot.com/

  19. Daryl

    Thanks for this article!

    Is there a way to make the fade transition last longer?

  20. Ryan Florence

    @Daryl: http://davidwalsh.name/create-a-simple-slideshow-iii

    It becomes a class in the last part of the series, where there’s a slideDuration option.

  21. anidexlu

    Thank you very much! I needed this and you made it absolutely simple.

  22. Zac

    I have no experience using Mootools at all. That said, am I the only one getting a strange start-up from the images? Right as the page loads each one of the images flashes befores it settles in on the first image to display. Also about 1/5 times it doesnt ever transition onto the next image. Im just wondering if Im doing something wrong.

  23. Zac

    In case anyone knows what I was talking about and gets the same effect I was, it can just be fixed by loading the js last at the end of the DOM. Works for me anyway.

  24. Robbie

    David, thanks a lot. This saved me a huge amount of time. Great work.

  25. Tony

    Thanks for this script. I’ve got it working in all browsers except for IE. In IE I don’t get any errors, but the images don’t change.

    I don’t know why it’s not working.

    http://www.theresessions.co.uk

  26. Christian

    @Tony: The issue of images not changing in IE comes from putting window.addEvent(“load”) + the call to the show function inside the initial domready-event.

    See this example:
    http://jsfiddle.net/kHBUD/

    @Daryl: You can do
    currentImage.set(“tween”, { duration: 2000 }).tween(“opacity”, 0);

    via http://net.tutsplus.com/tutorials/javascript-ajax/make-your-mootools-code-shorter-faster-and-stronger/

    @Ryan: I haven’t read to the end of this series yet but I couldn’t spot a slideDuration option in the solutions given there(?)

    @David: Thanks for sharing this code with us!

  27. Didier

    @David

    Hey David,
    just to say always a very nice work and thanks sharing this code with us !

    A question/idea : How do you imagine the best way to make thumnails of websites and incorporate them then into this slideshow (thumbnails like thoses you find in Chrome for example ) ?

  28. Tony

    @Christian Your a legend! Thanks for helping sort that out. I’m not too good at using js, so would have never got it working otherwise.

  29. Brian

    Excellent.
    I try to deploy it in my blogger site and it works in Chrome and FF.
    However, when I use IE to open the site, after I change the page, it freezes the IE. Do you have any solution for that?

    Thanks!

  30. DavePic

    Great work!! This was very simple to implement and looks great!! Thanks!

  31. Colin

    I really like this basic slideshow. The only thing that I would like to change would be the fade duration. Any ideas on how to do it?

  32. Conal

    Hi, I have just implemented this on my site and it looks great. However I am also using a mootools accordian on another page and it stops working. I take the slideshow stuff away and it works again. I include the mootools-1.2.4-core file first.
    Any ideas?
    Thanks

  33. Rob

    Love the script, works great in FF however does not transition in IE8… any fixes?

  34. Chris

    I’m with rob – this works great in FF, but doesn’t seem to work in IE8. I was able to get it to work in IE8 … but only if I include at least 1 of the original pictures in the array. (very weird). As soon as I replace the img src links with localized pics, it breaks. But if at least one points to the Christina Ricci photos, it works fine. Any help would be appreciated!!!

  35. Atea Webdiensten

    Thank you. I took your example and extended it with controls:

    HTML:


    1
    2

    CSS:

    #slideshow {position:relative; height: 170px; width: 760px; overflow: hidden;}
    #slideshow ul { margin: 0; padding: 0; }
    #slideshow .slides li { opacity: 0; position: absolute; top: 0; left: 0; }
    #slideshow .slides li.first { opacity: 1; }

    #slideshow .controls { position: absolute; bottom: 4px; right:4px}
    #slideshow .controls a {float: left; margin: 0 0 0 6px; padding: 1px 7px; background: #fff; list-style: none; }
    #slideshow .controls a.active {background: #c0c0c0; }

    MooTools JS:

    /* Custom Mootools Slider */
    window.addEvent('domready',function() {

    /* settings */
    var showDuration = 6000;
    var wrap = $('slideshow');
    var slides = wrap.getElements('ul.slides li');
    var controls = wrap.getElements('div.controls a');
    var currentIndex = 0;
    var interval;

    /* hide all but first slide */
    slides.each(function(li,i){
    if(i > 0) {
    li.set('opacity',0);
    }
    });

    /* updates controls */
    var updateControls = function() {
    if (controls !== false) {
    //reset controls
    controls.each(function(el){
    el.removeClass('active');
    });

    controls.getParent().getElement('[rel=' + currentIndex + ']').addClass('active');
    }
    }

    /* worker */
    var show = function(index) {

    slides[currentIndex].fade('out');

    // show next slide automaticly or show selected slide
    if(index == undefined){
    slides[currentIndex = currentIndex < slides.length - 1 ? currentIndex+1 : 0].fade('in');
    } else{
    $clear(interval);

    slides[index].fade('in');
    currentIndex = index;

    interval = show.periodical(showDuration);
    }

    updateControls();
    };

    /* start once the page is finished loading */
    window.addEvent('load',function(){

    interval = show.periodical(showDuration);

    /* controls */
    controls.addEvent('click', function(){
    var rel = parseInt(this.rel,10);
    show(rel);
    return false;
    });

    updateControls();
    });
    });

  36. Mugen

    I was having trouble with this in IE… And I have a solution that works fine :

    var duration = 4000,
    container = $(“slideshow”),
    images = container.getElements(“img”),
    currentIndex = 0,
    interval;
    images.each(function(img, i) {
    if (i > 0) {
    img.set(“opacity”, 0);
    }
    });

    var show = function() {
    images[currentIndex++].set(“tween”, {
    duration: 2000
    }).tween(“opacity”, 0);
    images[currentIndex %= images.length].set(“tween”, {
    duration: 2000
    }).tween(“opacity”, 1);
    }
    show.periodical(duration);
    }

    Big up !

  37. Mizpah

    Hi Folks,

    I am trying to rewrite a simple version of this to support transitioning divs. This is sitting in Joomla 1.5 .22 (Using mootools. 1.2), and the divs in question are autogenerated via:

    quote; ?>

    name . ', '; ?>company; ?>

    This is what I have:
    (I have also tried var quotes = container.getElements(‘div.testimonial’);)


    window.addEvent('domready',function() {
    /* settings */
    var showDuration = 3000;
    var container = $('testimonial-slideshow');
    var quotes = container.getElements('div');
    var currentIndex = 0;
    var interval;
    /* opacity and fade */
    quotes.each(function(div,i){
    if(i > 0) {
    div.set('opacity',0);
    }
    });
    /* worker */
    var show = function() {
    quotes[currentIndex].fade('out');
    quotes[currentIndex = currentIndex < quotes.length - 1 ? currentIndex+1 : 0].fade('in');
    };
    /* start once the page is finished loading */
    window.addEvent('load',function(){
    interval = show.periodical(showDuration);
    });
    });

    Yet I get mootools.js error on line 38 , or with div.testimonial (as above) I get

    return result;},getStyles:function(){r…hild);return this.appendText(text);}}

    Can anyone see any obvious errors ? This is the very last part of a given task and I havent used mootols prior!

    Cheer :)

  38. Martin Frönmark

    I’m a little late here, given that this was posted like a year and a half ago, but I was just wondering how you would go about a PNG fix for (old, crappy) IE when using this one.
    Thanks!

  39. Peter

    Hi!
    I like your simple script!
    But I need to change the duration of the fade/change effect.
    The default duration of fade(‘out’) and fade(‘in’) is to fast.

    I don`t know mootools well, so can anyone help me to change the duration of the effect?

    Thanks in advance!

  40. Frederick Lim

    How I can add an URL in the image?

  41. Garethsoul

    Very nice info!!! i used it for a web with joomla 1.7 and it run perfectly!

  42. bob

    I love the simplicity of this slideshow. Unfortunately it does not work properly with the new ‘mootools 1.4.4-core.js’. The slides no longer fade out slowly i.e instantly disappear. They fade in fine. Is this a bug in the new core ? Or does the program need alteration ? I would be very grateful if you could look into this.

    Thanks for this and your great blog!

  43. Richard Bolwell

    I have got this working very easily on a test page with just the slideshow on it. Great I though, so i tried to add to an existing page http://www.bolwellsgigreviews.co.uk/reviews/gigreviews.shtml.

    No joy, the first image loads then just fades away, nothing else happens.

    it appears to be a problem with the

    when I remove this it works perfectly but the rest of the page is all over the shop

    any ideas?


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: