Javascript, jQuery, popular, Tutorials

How to Add Flair to your Actions with jQuery – Part 3 – Javascript Tutorial

Welcome back to part 3 of Adding Flair to your Actions with jQuery! If you missed Part 2, go ahead and read that first, or just move ahead!

Simultaneous versus queued effects

The .animate() method, as we’ve just discovered, is very useful for creating simultaneous effects in a particular set of elements. There may be times, however, when we want to queue our effects, having them occur one after the other.

Working with a single set of elements

When applying multiple effects to the same set of elements, queuing is easily achieved by chaining those effects. To demonstrate this queuing, we’ll again move the Text Size box to the right, increase its height and increase its border width. This time, however, we perform the three effects sequentially, simply by placing each in its own .animate() method and chaining the three together:

$(document).ready(function() { 
$('div.label').click(function() {
var paraWidth = $('div.speech p').outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.animate({left: paraWidth - switcherWidth},
'slow')
.animate({height: '+=20px'}, 'slow')
.animate({borderWidth: '5px'}, 'slow');
});
});

Chaining permits us to keep all three .animate() methods on the same line, but here we have indented them and put each on its own line for greater readability.

We can queue any of the jQuery effect methods, not just .animate() , by chaining them. We can, for example, queue effects on in the following order:

  1. Fade its opacity to .5 with .fadeTo() .
  2. Move it to the right with .animate() .
  3. Fade it back in to full opacity with .fadeTo() .
  4. Hide it with .slideUp() .
  5. Show it once more with .slideDown() .

All we need to do is chain the effects in the same order in our code:

$(document).ready(function() { 
$('div.label').click(function() {
var paraWidth = $('div.speech p').outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo('fast',0.5)
.animate({
'left': paraWidth - switcherWidth
}, 'slow')
.fadeTo('slow',1.0)
.slideUp('slow')
.slideDown('slow');
});
});

But what if we want to move the to the right at the same time as it fades to half opacity? If the two animations were occurring at the same speed, we could simply combine them into a single .animate() method. But in this example, the fade is using the ‘fast’ speed while the move to the right is using the ‘slow’ speed. Here is where the second form of the .animate() method comes in handy:

$(document).ready(function() { 
$('div.label').click(function() {
var paraWidth = $('div.speech p').outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo('fast',0.5)
.animate({
'left': paraWidth - switcherWidth
}, {duration: 'slow', queue: false})
.fadeTo('slow',1.0)
.slideUp('slow')
.slideDown('slow');
});
});

The second argument, an options map, provides the queue option, which when set to false makes the animation start simultaneously with the previous one.

One final observation about queuing effects on a single set of elements is that queuing does not automatically apply to other, non-effect methods such as .css() . So let’s suppose we wanted to change the background color of to red after the .slideUp() but before the slideDown() . We could try doing it like this:

$(document).ready(function() { 
$('div.label').click(function() {
var paraWidth = $('div.speech p').outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo('fast',0.5)
.animate({
'left' paraWidth - switcherWidth
}, 'slow')
.fadeTo('slow',1.0)
.slideUp('slow')
.css('backgroundColor','#f00')
.slideDown('slow');
});
});

However, even though the background-changing code is placed at the correct position in the chain, it occurs immediately upon the click.

One way we can add non-effect methods to the queue is to use the appropriately named .queue() method. Here is what it would look like in our example:

$(document).ready(function() { 
$('div.label').click(function() {
var paraWidth = $('div.speech p').outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo('fast',0.5)
.animate({
'left': paraWidth - switcherWidth
}, 'slow')
.fadeTo('slow',1.0)
.slideUp('slow')
.queue(function() {
$switcher
.css('backgroundColor', '#f00')
.dequeue();
})
.slideDown('slow');
});
});

When given a callback function , as it is here, the .queue() method adds the function to the queue of effects for the matched elements. Within the function, we set the background color to red and then add the corollary .dequeue() method. Including this .dequeue() method allows the animation queue to pick up where it left off and complete the chain with the following .slideDown(‘slow’) line. If we hadn’t used .dequeue(), the animation would have stopped.

More information and examples for .queue() and .dequeue() are available at http://docs.jquery.com/Effects .

We’ll discover another way to queue non-effect methods as we examine effects with multiple sets of elements.

Working with multiple sets of elements

Unlike with a single set of elements, when we apply effects to different sets, they occur at virtually the same time. To see these simultaneous effects in action, we’ll slide one paragraph down while sliding another paragraph up. First, we’ll add the remaining portion of the Gettysburg Address to the HTML, dividing it into two separate paragraphs:

 

Text Size






Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty, and
dedicated to the proposition that all men are created
equal.


Now we are engaged in a great civil war, testing whether
that nation, or any nation so conceived and so dedicated,
can long endure. We are met on a great battlefield of
that war. We have come to dedicate a portion of that
field as a final resting-place for those who here gave
their lives that the nation might live. It is altogether
fitting and proper that we should do this. But, in a
larger sense, we cannot dedicate, we cannot consecrate,
we cannot hallow, this ground.


read more

The brave men, living and dead, who struggled
here have consecrated it, far above our poor
power to add or detract. The world will little
note, nor long remember, what we say here, but it
can never forget what they did here. It is for us
the living, rather, to be dedicated here to the
unfinished work which they who fought here have
thus far so nobly advanced.


It is rather for us to be here dedicated to the
great task remaining before us—that from
these honored dead we take increased devotion to
that cause for which they gave the last full
measure of devotion—that we here highly
resolve that these dead shall not have died in
vain—that this nation, under God, shall
have a new birth of freedom and that government
of the people, by the people, for the people,
shall not perish from the earth.



Next, to help us see what’s happening during the effect, we’ll give the third paragraph a 1-pixel border and the fourth paragraph a gray background. We’ll also hide the fourth paragraph when the DOM is ready:

$(document).ready(function() { 
$('p:eq(2)').css('border', '1px solid #333');
$('p:eq(3)').css('backgroundColor', '#ccc').hide();
});

Finally, we’ll add the .click() method to the third paragraph so that when it is clicked, the third paragraph will slide up (and out of view), while the fourth paragraph slides down (and into view):

$(document).ready(function() { 
$('p:eq(2)')
.css('border', '1px solid #333')
.click(function() {
$(this).slideUp('slow')
.next().slideDown('slow');
});
$('p:eq(3)').css('backgroundColor', '#ccc').hide();
});

A screenshot of these two effects in mid-slide confirms that they do, indeed, occur virtually simultaneously:

The third paragraph, which started visible, is halfway through sliding up at the same time as the fourth paragraph, which started hidden, is halfway through sliding down.

Callbacks

In order to allow queuing effects on different elements, jQuery provides a callback function for each effect method. As we have seen with event handlers and with the .queue() method, callbacks are simply functions passed as method arguments. In the case of effects, they appear as the last argument of the method.

If we use a callback to queue the two slide effects, we can have the fourth paragraph slide down before the third paragraph slides up. Let’s first look at how to set up the .slideDown() method with the callback:

$(document).ready(function() { 
$('p:eq(2)')
.css('border', '1px solid #333')
.click(function() {
$(this).next().slideDown('slow',function() {
// code here executes after 3rd paragraph's
// slide down has ended
});
});
$('p:eq(3)').css('backgroundColor', '#ccc').hide();
});

We do need to be careful here, however, about what is actually going to slide up. The context has changed for $(this) because the callback is inside the .slideDown() method. Here, $(this) is no longer the third paragraph, as it was at the point of the .click() method; rather, since the .slideDown() method is attached to $(this).next() , everything within that method now sees $(this) as the next sibling, or the fourth paragraph. Therefore, if we put $(this).slideUp(‘slow’) inside the callback, we would end up hiding the same paragraph that we had just made visible.

A simple way to keep the reference of $(this) stable is to store it in a variable right away within the .click() method, like var $thirdPara = $(this) .

Now $thirdPara will refer to the third paragraph, both outside and inside the callback. Here is what the code looks like using our new variable:

$(document).ready(function() { 
var $thirdPara = $('p:eq(2)');
$thirdPara
.css('border', '1px solid #333')
.click(function() {
$(this).next().slideDown('slow',function() {
$thirdPara.slideUp('slow');
});
});
$('p:eq(3)').css('backgroundColor', '#ccc').hide();
});

Using $thirdPara inside the .slideDown() callback relies on the properties of closures .

This time a snapshot halfway through the effects will reveal that both the third and the fourth paragraphs are visible; the fourth has finished sliding down and the third is about to begin sliding up:

Now that we’ve discussed callbacks, we can return to the code from earlier in this article in which we queued a background-color change near the end of a series of effects. Instead of using the .queue() method, as we did earlier, we can simply use a callback function:

$(document).ready(function() { 
$('div.label').click(function() {
var paraWidth = $('div.speech p').outerWidth();
var $switcher = $(this).parent();
var switcherWidth = $switcher.outerWidth();
$switcher
.fadeTo('slow',0.5)
.animate({
'left': paraWidth - switcherWidth
}, 'slow')
.fadeTo('slow',1.0)
.slideUp('slow', function() {
$switcher
.css('backgroundColor', '#f00');
})
.slideDown('slow');
});
});

Here again, the background color of changes to red after it slides up, and before it slides back down.

In a nutshell

With all the variations to consider when applying effects, it can become difficult to remember whether the effects will occur simultaneously or sequentially. A brief outline might help:

  1. Effects on a single set of elements are:
    simultaneous when applied as multiple properties in a single .animate( ) method.
    queued when applied in a chain of methods, unless the queue option is set to false .
  2. Effects on multiple sets of elements are:
    simultaneous by default
    queued when applied within the callback of another effect or within the callback of the .queue() method

Summary

By using effect methods that we have explored in this article, we should now be able to incrementally increase and decrease text size by using either the .css( ) or the .animate() method. We should also be able to apply various effects to gradually hide and show page elements in different ways and also to animate elements, simultaneously or sequentially, in a number of ways.


Learning jQuery 1.3
 
Learning jQuery 1.3
  • Better Interaction Design and Web Development with Simple JavaScript Techniques
  • An introduction to jQuery that requires minimal programming experience
  • Detailed solutions to specific client-side problems
  • For web designers to create interactive elements for their designs
  • For developers to create the best user interface for their web applications
  • Packed with great examples, code, and clear explanations
  • Revised and updated version of the first book to help you learn jQuery

   http://www.packtpub.com/learning-jquery-1.3/book


You Might Also Like