Using MooTools to fade between two images

Fading between two images is actually a fairly simple task with MooTools. The first thing you need to do is setup up two DIV tags that are absolutely positioned over one another inside another DIV tag that uses default placement. Then you place your image tags inside each of the absolutely positioned DIV tags. Each of the DIV tags needs to have an id attribute so they can be referenced in your javascript code.

The HTML for the task will look like this:

<div style="height:112px;" >
	<div id="div1" style="position:absolute; opacity: 0;"><img id="image1" src="image1.jpg" /></div>
	<div id="div2" style="position:absolute; opacity: 1;"><img id="image2" src="image2.jpg" /></div>
</div>

This gives you two DIV tags that will stack on top of one another but the DIV they are inside of will flow with the page. One of the DIV tags starts with an opacity of zero and the other with an opacity of one.

Next you will need a way to make one image disappear and the other appear. We do this by using the MooTools effects. MooTools allows you to animate the change of a style from one value to the next. The easiest way to do this is to use the effect member available on any element accessed with MooTools. To transition from one image to the other smoothly we animate the opacity of each DIV element in opposite directions one becoming fully opaque and the other becoming fully transparent. We do that with the following function:

function show(whichOne){
	if(whichOne == 1){
		tDiv = "div1";
		vDiv = "div2";
	}else{
		tDiv = "div2";
		vDiv = "div1";
	}
	if($(tDiv).fx){$(tDiv).fx.stop();}
	if($(vDiv).fx){$(vDiv).fx.stop();}
	$(tDiv).fx = $(tDiv).effect('opacity', {duration: 2000}).start(0);
	$(vDiv).fx = $(vDiv).effect('opacity', {duration: 2000}).start(1);	
}

First you decide which DIV tag will become Transparent and which one will be visible. Next there are two lines of code to check for an active animation and stop any animations that are already running, before we start some new animations. The last two lines create an animation attached to each DIV, going from the current opacity to the specified Opacity, and sets the animation object to the DIV tags .fx member. See the full code below or check out the example.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • DZone
  • StumbleUpon
  • del.icio.us
  • Reddit
  • Technorati
  • Netvouz
  • Slashdot
  • blinkbits
  • blogmarks
  • Furl

This entry was posted on Monday, March 17th, 2008 at 6:00 am and is filed under JavaScript, MooTools, programming, image, effect. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Be the first to leave a comment.

Leave a Reply

You must be logged in to post a comment.

Bad Behavior has blocked 221 access attempts in the last 7 days.