cooking, programming and everyday life xrado

Sunday, April 13, 2008

mooFader - image fader slideshow

i needed one for the website i was working on, so i made small class that works with mootools 1.11.
head:
<script type="text/javascript" src="mootools-1.11.js"></script>
<script type="text/javascript" src="moofader.js"></script>
<script>
var images = Array('<?=implode("','",glob('images/*.JPG'));?>');
window.addEvent('load', function(){ new mooFader('fader',images); } );
</script>
html:
<div style="position: relative; width: 390px; height: 390px;" id="fader">
	<img src="images/rado.JPG">
</div>
script:
var mooFader = new Class({

	options:{
		duration: 3000,
		fade: 1000
	},

	initialize: function(el,im,options) {
		this.setOptions(options);
		this.holder = $(el);
		if(!this.holder) return;
		this.starter = this.holder.getElement('img');
		this.starter.setStyle('position','absolute');
		this.im = im;
		this.faders = [];
		this.images = im.length;
		this.counter = 0;
		this.change.periodical(this.options.duration,this);
		new Asset.image(this.im[this.counter]);
	},

	change: function(){
		if(this.counter > this.images-1) this.counter = 0;
		var img = new Element('img',{
			'src'	: this.im[this.counter],
			'styles': { 'position':'absolute' }
		}).injectTop(this.holder);
		var fader = img.getNext();
		new Fx.Style(fader,'opacity',{ duration:this.options.fade, onComplete: function(el){ fader.remove(); } }).start('1', '0');
		this.counter++;
		new Asset.image(this.im[this.counter]);
	}
});

mooFader.implement(new Options, new Events);
Demo page can be found here.
I was looking for something as simple as this for a Joomla 1.5 (old Mootools) template, but I found there was a little problem that made the first image in the array last double the time if it was the same inside the holder (the fader waits X duration before changing to index 0, so if index 0 is the same image SRC inside the holder there won't be any visual change until next index is called after another X duration)

So, to fix this I just added a new integer option "start" which sets the initial counter value (this.counter = this.options.start), so in my case:
mooFader('slideshow', slides, {duration:5000, fade:1000, start:1});

I could also force a first change calling "this.change()" at right the end of the intialization function, and optionally to eliminate a almost imperceptible "ghosting" effect, set a ".first" class in the IMG tag inside holder DIV with visibility set to "hidden" or simply use a transparent gif instead of the first image inside the array.

The problem with these last options is that if javascript is OFF no image will be shown.

Hope it helps,

Thanks for the script!

thanks for sharing you opinion, greetings

COMMENTS ARE DISABLED