Tuesday, 2 December 2008

Simple ul list with a nice slide-out effect for <li> elements

In the past weeks some readers of this blog asked to me what's a simple way to implement an animated "disappear" effect (using unobtrusive JavaScript code) for an element of a list when an user clicks on a link contained into a <li> element of that list.

I think a very simple way to do that is using MooTools slideOut() effect. This tutorial explains how to implement that using "five" lines of JavaScript code.

Download source code Live Preview


Step 1: Include MooTools framework
First, you may download the latest version of MooTools and add a link to the framework in the tag <head> of the page:

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

Step 2: HTML code
Image to implement a simple list of products and for each product into that list add a link "Hide":

<ul id="myList">
<li id="l1">Playstation | <a href="#">Hide</a></li>
<li id="l2">iPod Touch | <a href="#">Hide</a></li>
<li id="l3">XBOX 360 | <a href="#">Hide</a></li>
<li id="l4">Nokia N97| <a href="#">Hide</a></li>
<li id="l5">Dell Inspiron | <a href="#">Hide</a></li>
</ul>

The result is something like this:



How you can see, we have a products list with ID="myList" and some <li> elements with a progressive ID: l1, l2, l3, l5, l5. We want to obtain this effect: when an user clicks on a link ("Hide"), the related <li> element disappear with a nice animated slide out effect. How can we do that? Take a look at the following step!

Step 3: Unobtrusive JavaScript code
Copy and paste this code below the code at the step 1 to enable slideOut() effect:

<script>
window.addEvent('domready', function() {
/* From the list with ID myList, for each li element of the list...: */
$('myList').getElements('li').each(function(e){
/* ...get the ID of the selected item */
e.getElement('a').addEvent('click', function(listID){
/* Enable Fx.Slide effect for the selected item */
var list_element = new Fx.Slide(listID);
/* Enable slideOut() effect */
list_element.slideOut()
}.pass(e.id));
});
});
</script>

That's all! Download the source code or take a look at the live preview.

Download source code Live Preview


Related contents
If you have not confidence with MooTools I suggest you to take a look at this introduction lessons I wrote some time ago:

Lesson 1 - Basic Tips for Web Designer
Lesson 2 - Get elements ID using unobtrusive code
Lesson 3 - Interaction with Forms

No comments:

Post a Comment