Apps

Animations: How to use fadeout and slideToggle functions in jQuery

Ryan Boudreaux demonstrates how to use the fadeout and slideToggle functions in jQuery to create animation effects.

Following on last week's tutorial on creating animations with jQuery, this week I will demonstrate how to create an animation using .fadeout(), and .slideToggle() functions. All of the files used in this demonstration (images, CSS, HTML, script) are available for download so you can follow along.

The jQuery library provides several methods for including animation on web document pages. These include simple, standard animations that are frequently used, and it also provides the ability to craft sophisticated custom effects. In this segment, we'll closely inspect several of the effect methods, revealing the power jQuery has for providing visual feedback to the visitor.

The fadeout function

The jQuery .fadeout() function hides the matched elements by fading them to a transparent state making adjustments to the opacity. Once the opacity reaches 0, the display state of the style property is set to "none," and the element no longer affects the layout of the object -- or page for that matter.

Syntax for the fadeout function:

.fadeOut( [duration] [, easing] [, callback] )

  • Duration - A string or number determining how long the animation will run.
  • Easing - A string indicating which easing function to use for the transition.
  • Callback - A function to call once the animation is complete.

Similar to the .animate() function, the durations are given in milliseconds, the easing specifies the speed at which the animation progresses at different points throughout the action, and the callback function is fired once the animation is complete.

Demonstration of the fadeout function

We will fade out a paragraph with a "slow" duration and include the callback complete function with the following HTML added to our index.html file (included in the download):

   <!-- HTML -->
     <section>
       <article id="fadeOut">
         <p>Click here to fade out the paragraph!</p>
       </article>
       <article>
         <p id="fadeP">"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
       </article>
     </section>

And the following styles are included in our styles.css file:

#fadeOut, #fadeOutLinear, #slideBox {
       cursor: pointer;
       border-color:#CCC;
       border:solid thin;
       width:250px;
       padding:5px;
       text-align:center;
}
#complete {
       text-decoration:underline;
       font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
       margin:10px;
       padding:10px;
       color:#339;
}
article p {
       font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
       font-size:14px;
}

And the following jQuery code added to our document ready event function:

   <script>
    // JavaScript
      $(document).ready(function(){
       //Fade out paragraph
        $('#fadeOut').click(function() {
        $('#fadeP').fadeOut('slow', function() {
        // Animation complete.
           $(this).after('<article id="complete">Fadeout is now complete!</article>');
        });
       });
      });
   </script>
Remember to save your index.html and styles.css files, then open the HTML in your browser and click the "Click here to fade out the paragraph!" link; the original (Before) and resulting (After) output is displayed in Figure A as shown in Chrome 18.0.1:

Figure A

Easing, an optional string

With the update to jQuery 1.4.3, easing brings life to an effect, and this is where the optional string for naming an easing function may be used. Easing functions specify and control the speed at which the animation progresses at different points within the animation and how it progresses over time by manipulating its acceleration. The two built-in implementation methods in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. For really dramatic easing effects the jQuery easing plug-in incorporates even more animation possibilities, however, at this time the plug-in is under development.

This demonstration will show a fade out of the orchid image that was used in the previous tutorial, and we will incorporate the linear ease effect.

First, let's add in the HTML code just below the existing code:

      <article id="fadeOutLinear">
       <p>Click here to fade out the image!</p>
      </article>
      <article>
       <img src="images/Orchid.gif" alt="Orchid" title="Orchid" id="fadeImage" />
      </article>

Then, the jQuery function gets added to the document ready function:

   //Fade out image
   $('#fadeOutLinear').click(function() {
   $('#fadeImage').fadeOut('slow', 'linear', function() {
   // Animation complete.
   $(this).after('<article id="complete">Fadeout is now complete!</article>');
   });
  });
Save the index.html file in your text editor, refresh the page in your browser, and then click on the "Click here to fade out the image!" link. Figure B shows the Before image and Figure C shows it after the fadeout.

Figure B

Figure C

The callback functions for both demonstrations have been implemented in each example with the jQuery:

$(this).after('<article id="complete">Fadeout is now complete!</article>');

Demonstration of the slideToggle() function

The jQuery .slideToggle() function displays or hides the matched elements with a sliding motion. And the syntax for the sliding toggle is displayed below:

.slideToggle( [duration] [, easing] [, callback] )

Did you notice the similarity in the syntax and property options to the sliding toggle and the animation and fade out effects? The difference for the sliding toggle effect is that it causes lower parts of the matched set of elements to slide up or down, and thus appear to reveal or conceal upon execution of the event. If the element is initially displayed, it will be hidden once the function is executed, and if the element is initially hidden, it will be displayed; as such, the display property is saved and restored as needed. When the height of the element reaches 0 after a hiding animation, the display style property is set to "none" to ensure that the element no longer affects the layout of the page.

For the demonstration of the slide toggle function we will add in the following HTML to the index.html file:

      <article id="slideBox">
       <p>Click here to slide the box!</p>
      </article>
      <article id="box">
       <p>"Time is but the stream I go a-fishing in."<br/>
       Henry David Thoreau</p>
      </article>

We will also add in a style for the id="box" in our styles.css file:

#box {
       margin-top:25px;
       border-color:#33F;
       border:solid thin;
       width:270px;
       height:100px;
       padding:5px;
       background-color:#0C6;
}

And this is the jQuery for the slide toggle function added to the document ready function:

        //Slide toggle effect
        $('#slideBox').click(function() {
        $('#box').slideToggle('slow', function() {
        // Animation complete.
        $(this).after('<article id="complete">Slide effect is now complete!</article>');
        });
       });

Save your index.html and styles.css files, and then go back to the browser and refresh your page. Test the "Click here to slide the box!" link. The results are displayed in the figures below as rendered in Chrome 18.0.1:

Figure D

Figure E

Click again, and the element will appear again:

Figure F

Notice that the callback complete event is initiated each time the slide toggle function finishes; in this case, there are two complete notifications since the event was triggered twice.

Practical applications for the slide toggle function would include added effects for FAQs with sliding answers upon click of the associated question, collapsible menus in navigation, and creating a "Chat with me!" chat panel that slides open when clicked.

More on jQuery:

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

0 comments