O'Reilly

Create a Quick MooTools Slideshow with Preloading Images

By on  
David Walsh Slideshow

I've been creating a lot of slideshow posts lately. Why, you ask? Because they help me get chicks. A quick formula for you:

var numChicks = $$('.slideshow').length; //simple!

The following code snippet will show you how to create a simple slideshow with MooTools; the script will also preload the images and feature a progress message. Why preload images? They make the slideshow more elegant and you can avoid an onLoad mess. Oh, and chicks...loads and loads of chicks.

The HTML

<div id="slideshow-holder">
	<div id="progress"></div>
</div>

Basically just two DIVs which will hold content.

The CSS

#slideshow-holder	{ width:600px; height:400px; background:url(spinner.gif) center center no-repeat #fff; position:relative; }
#progress			{ position:absolute; width:100%; text-align:center; color:#999; top:225px; }

The image holder is given set dimensions, starts with a background spinner, and its position set to relative; the images will all be positioned absolutely. The progress holder is set right below the spinner.

The MooTools JavaScript

window.addEvent('domready',function() {
	/* preloading */
	var imagesDir = 'epics/';
	var images = ['2.jpg','3.jpg','1.jpg','4.jpg','5.jpg'];
	var holder = $('slideshow-holder');
	images.each(function(img,i){ images[i] = imagesDir + '' + img; }); //add dir to images
	var progressTemplate = 'Loading image {x} of ' + images.length;
	var updateProgress = function(num) {
		progress.set('text',progressTemplate.replace('{x}',num));
	};
	var progress = $('progress');
	updateProgress('text','0');
	var loader = new Asset.images(images, {
		onProgress: function(c,index) {
			updateProgress('text',index + 1);
		},
		onComplete: function() {
			var slides = [];
			/* put images into page */
			images.each(function(im) {
				slides.push(new Element('img',{
					src:im,
					width: 600,
					height: 400,
					styles: {
						opacity:0,
						top:0,
						left:0,
						position:'absolute',
						'z-index': 10
					}
				}).inject(holder));
				holder.setStyle('background','url(logo.png) center 80px no-repeat');
			});
			var showInterval = 5000;
			var index = 0;
			progress.set('text','Images loaded.  MooTools FTW.');
			(function() {slides[index].tween('opacity',1); }).delay(1000);
			var start = function() {
				(function() {
					holder.setStyle('background','');
					slides[index].fade(0);
					++index;
					index = (slides[index] ? index : 0);
					slides[index].fade(1);
				}).periodical(showInterval);
			};

			/* start the show */
			start();
		}
	});
});

The first set of variable declarations represent basic settings for the preloader: images, preload-message-updating, etc. We pass our Asset.images instance an array of images. When each image loads, we update the status message. When every image has loaded, we remove the status message and start the slideshow. That's it!

Of course the above could be turned into the class....I'm just slightly lazy...Feel free to turn it into a class and share with everyone!

Track.js Error Reporting

Recent Features

  • How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

Incredible Demos

  • MooTools Zoomer Plugin

    I love to look around the MooTools Forge. As someone that creates lots of plugins, I get a lot of joy out of seeing what other developers are creating and possibly even how I could improve them. One great plugin I've found is...

  • CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...

Discussion

  1. var numChicks = $$('.slideshow').length;
    

    Doesn’t that suggest they’re only interested in the length of your slideshows, rather than the number of slideshow posts you make? :P

  2. @Addy Osmani: Having a sizable slideshow doesn’t hurt. Maybe I should have used PHP:

    $num_chicks = get_posts('type'=>'slideshow');
  3. As long as you remember to protect your $$('.slideshow') with curly brackets I think you should be fine.

    You’d hate for some ‘child’ elements to randomly start appearing unexpectedly around your page ;)

  4. MLaZz

    Dude, nice photos..! I mean, they are really good!
    Especially the purple one!

    Back to chicks – redirect guys to Christina Ricci posts so only chicks stay around ;)

    $num_chicks = get_posts(‘type’=>’slideshow’) + get_posts('post_has_photos_of'=>'christina+ricci');
  5. I see that you use

    (function() {slides[index].tween('opacity',1); }).delay(1000);

    this kinda syntax quite a lot.
    I mean (function(){}).xyz() type of code.

    Does it have a some real advantage, apart from making code a lil complex to read.

  6. @Nitin: I used that because the “.delay” method is a Function method, thus I need to wrap the “tween” directive in a function.

  7. Vitor

    You just wanted and excuse to show off ur engagement photos!!
    Showoff!! LOL

    Great job and nice Photos

  8. I would have thought that you could just tell chicks you were a mooTools guru, but slide shows work too!

  9. Lars

    Nice one!

    Any easy way to make the slideshow randomize the pictures so that it will randomize the order on load?

  10. Lars

    Nice one!

    Any easy way to make the slideshow randomize the pictures so that it will randomize the order on load?

  11. hamburger

    Hello David,
    i found an issue in your script:

    updateProgress('text','0');  should be updateProgress('0'); 

    and what kind of mo are you using.
    with my original one mootools-1.2.4-core-yc.js from the moo-side
    i get the error Asset is not defined.

  12. @hamburger:
    Asset is part of mootools.more, go there http://mootools.net/more and download the js with Asset if you need this one only

    @David:
    I was doing a slideshow with gradient lightbox, and wanted to integrate some ready done mootools slideshow, so I went with this one. Did some refactoring to put it in a class and it works great! Thanks a lot.

    My slideshow: http://standupweb.net/mootools/gradientLightbox.php

  13. hello, thanks for you. cool jquery

  14. Gav

    Hi there,

    Excellent slideshow but just wondering if anybody found a way of randomizing the images?
    Thanks Gav

  15. don

    hi guys…

    anyone know of a way to add images using an external xml file?

    thanks

    donb

  16. Will

    I love this script. However, it doesn’t seem to work on firefox 2 for some reason. unfortunately the project I’m working needs to be compatible with such antiquities.

  17. quang trung

    Hi David

    I don’t sure about my issue. It relate to use duration options instead delay function.

    (function() {slides[index].tween('opacity',1); }).delay(1000);
    

    What’s diffirence ? performance ? speed ?

  18. ann

    How would you use this to click through the images, instead of having them auto-cycle? (i.e. click on image 1 to have it load image 2)

  19. Solo

    What a cool slideshow!
    I was wondering if anyone has been able to add a hyperlink for each image. It would help me a lot.

    Thanks!

  20. thank you. i like this slider.

  21. Hi David

    Your Diapo is using the Asset.images of Mootools , and I have a question about that considering this following code coming from MooWheel ( here http://labs.unwieldy.net/moowheel/ )

    MooWheel.Remote = new Class({
        
        Extends: MooWheel,
    
    initialize: function(data, ct, options) {
    
            var preloadImages = function(wheelData) {
                var imageUrls = [], map = {};
    
                for (var i = 0, l = wheelData.length; i < l; i++) {
                    if (wheelData[i]['imageUrl']) {
                        imageUrls.push(wheelData[i]['imageUrl']);
                        map[i] = imageUrls.length - 1;
                    }
                }
    
                if (imageUrls.length == 0)
                    return false;
     
                //rappel : Asset.images Preloads an array of images (as strings)
                //and returns an array of img elements. does not inject them to the page.
                var images = new Asset.images(imageUrls, {
                    onComplete: function() {  //Executes when all image files are loaded.
                        for (var j in map) {
                            wheelData[j]['image'] = images[map[j]];
                        }
    
                        // hack to make this.parent work within callback
                        //
                        // The callee property contains the function that is currently executing.
                        // This is useful if the function has no name.
                        //
                        arguments.callee._parent_ = this.initialize._parent_;
      
    
                        this.parent()(wheelData, ct, options); // calls initalize method of MooWheel class
    
                    }.bind(this)
                });
    
                return true;
            }.bind(this);
    

    We need here to activate the code this.parent()(wheelData, ct, options); at the end of the OnComplete
    Inspite of the hack with arguments.callee._parent_ (seems depreciated now !)
    we don't reach the method of the parent class MooWheel of MooWheel.Remote

    How do you think we can do it now ?

  22. Tony

    Really cool script, g;ad I read the comments, couldn’t get it to work until I included more.js :)

  23. LeNche

    Every day I amaze your detailed examples. You’re perfect. Greetings from Serbia ;)

  24. Chik

    Your script looks like just what I need… but I can’t get it to work :-(
    As nearly as I can tell, it’s not a path issue for the pics. I don’t know if I need Mootools 1.2.4 loaded… I don’t have it, and know nothing about it. Do I need that? Thanx!

  25. Chik

    Ooooops… never mind, I got it figured out. I just needed to walk away for a few minutes :-)
    Desperately need sleep…

  26. Deya

    Hi, Im new in this page I’d like to know do I have to download something special to make it work? I put the code and I have the .js funtion file but It doesn’t work, can somebody help me ? thanks!

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

Recently on David Walsh Blog

  • Serve a Directory via Python

    Sometimes I'm working with a test HTML file and some JavaScript but need to work off of a served space.  In that case, I sometimes need to swap out folders within MAMP Stack which leads to a maintenance nightmare.  Bleh. I recently found out that you can...

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...