Create a Simple Slideshow Using MooTools

By  on  
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!

Recent Features

Incredible Demos

  • By
    Smooth Scrolling with MooTools Fx.SmoothScroll

    I get quite a few support requests for my previous MooTools SmoothScroll article and the issue usually boils down to the fact that SmoothScroll has become Fx.SmoothScroll. Here's a simple usage of Fx.SmoothScroll. The HTML The only HTML requirement for Fx.SmoothScroll is that all named...

  • By
    jQuery Link Nudging

    A few weeks back I wrote an article about MooTools Link Nudging, which is essentially a classy, subtle link animation achieved by adding left padding on mouseover and removing it on mouseout. Here's how to do it using jQuery: The jQuery JavaScript It's important to keep...

Discussion

  1. 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. Hey David,

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

  3. @Alex: You really writes touching stuff!

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

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

  6. @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. i did something similar some time ago http://xrado.hopto.org/post/moofader2

    greetings

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

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

  11. 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. Thanks for sharing your slide show. You are half my age and three times farther along – and I am happy for you.

  14. 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. @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. 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. @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. David, thanks a lot. This saved me a huge amount of time. Great work.

  25. 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. @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. @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. 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. 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. 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 !

  36. 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!

  37. 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!

  38. Frederick Lim

    How I can add an URL in the image?

    • I was wondering the same thing Frederick. Has this been answered yet?

  39. Garethsoul

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

  40. 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!

  41. 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?

  42. Chad

    Can each slide contain a link? I seem to be having problems getting them to link out to anything.

  43. Dave

    Do you have a version for mootools 1.1 ?

  44. This is just what I needed, thanks! Just need to alter the fade speed now…

  45. RoN Ramsey

    Excuse me for being s dummie but I can’t get the fading slideshow to work. Can you please post an example of how and where it is pasted into the code of a website. You have posted the code and the CSS but I can’t figure out how to get it in the right place in the code. I created a div and I resized it to the size of my images but the images just show up all at the same time on the page.
    Thank You!

  46. RoN Ramsey

    https://gist.github.com/telecarver/817ad512b60e1b0d84ed I don’t know if this will work. The last post deleted part of the URL

  47. Xeno

    img.set(‘opacity’, 0); is wrong. Should be: img.set(‘style’, ‘opacity: 0;’);

  48. Sean

    This is a great slideshow! I’ve got mine up and running like a charm so thanks.

    My only question is.. is there a way to overwrite the thumbnails the script makes for you with my own? My slideshow has landscape (wide) photos but I want my thumbnails to be small squares at the bottom. I have them the size I want but currently the images are distorted and squeezed to try and fit the size I set.

    Please let me know if this is possible and how to achieve this. Thank you!

  49. Sean

    Nevermind, finally figured it out!

    Changed src: img.get('src') to: src: img.get('thumb'):

    /* add to table of contents */
    toc.push(new Element('img',{
        src: img.get('thumb'),
        title: img.get('alt'),
        styles: {
            opacity: thumbOpacity
        },
    

    And added a section at the end of my html code:

    “img src” is where my full-sized picture exists and “thumb” is where I stored my corresponding thumbnails!

  50. Eva

    I’d like to change the transition, instead of fade in and out, I’d like the images to slide in from right to left. Would anyone know the code to achieve that?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!