« Palm Tungsten E2, iSync, and Bluetooth
What the hell is an aluminum falcon? »

Fade in, fade out

While I was in the process of coding up the site and relaunching it, I decided that I’d make the more popular of the articles I’d written previously available to those who found them via search engines or other blogs.

During this process, I noticed that two of the three most popular were the articles that explained how to make a div fade in and out with scriptaculous. I also noticed it was somewhat confusing to have two of them, so I figured I’d start the relaunched site by combining the two posts into one and providing a simplified example.

First things first, this assumes you have some knowledge of HTML and javascript. If you don’t, this article probably won’t help you much.

Secondly, in order for the code to work, you must have scriptaculous installed. If you don’t, go download it now. Again, this code will not work without it.

Note: Scriptaculous depends on the Prototype library (which is included in the scriptaculous download). Make sure you read the included readme/install files and upload both.

Now that you have scriptaculous downloaded and uploaded to your web server (you did upload it, right?), you’ll need to include it into the page that contains the div you want to fade. It should look something like this:

<script type="text/javascript" src="/js/prototype.js"></script>
<script type="text/javascript" src="/js/scriptaculous.js"></script>

Note: If you uploaded the files to somewhere other than /js/, use the directory that you put it in. For example, if you uploaded them to /scripts/, use /scripts/ instead of /js/.

Now let’s build the link that will toggle the div:

<h2><a href="javascript:Effect.toggle('foo','appear');">Toggle</a></h2>

What the above does is create a link inside an h2 that calls the toggle effect from scriptaculous on a div with the id of foo.

Now let’s build the div itself:

<div id="foo">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p>Vestibulum auctor lacus id lectus.</p>
</div>

Finally, let’s put it all together:

<h2><a href="javascript:Effect.toggle('foo','appear');">Toggle</a></h2>

<div id="foo">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p>Vestibulum auctor lacus id lectus.</p>
</div>

Here’s an example that shows how it works.

There are two other effects that work with toggle in addition to appear. They are blind and slide. For more information on what these do, see the scriptaculous combination effects docs.

That’s all there is to it. Let me know if you have any questions and I’ll try to answer them. Good luck!

Comments are closed.