Customized Effects with jQuery 1.4

Exclusive offer: get 50% off this eBook here
jQuery 1.4 Reference Guide

jQuery 1.4 Reference Guide — Save 50%

This book and eBook is a comprehensive exploration of the popular JavaScript library

$23.99    $12.00
by Jonathan Chaffer Karl Swedberg | March 2010 | AJAX Open Source Web Development

The jQuery library provides several techniques for adding animation to a web page. These include simple, standard animations that are frequently used and the ability to craft sophisticated custom effects. In this article by Karl Swedberg and Jonathan Chaffer, authors of jQuery 1.4 Reference Guide, we'll closely examine each of the effect methods, revealing all of the mechanisms jQuery has for providing customised visual feedback to the user.

Some of the examples in this article use the $.print() function to print results to the page. This is a simple plug-in, not covered in the article.

Customized effects

We will describe how to create effects that are not provided out of the box by jQuery.

.animate()

Perform a custom animation of a set of CSS properties.

.animate(properties[, duration][, easing][, callback])
.animate(properties, options)

Parameters (first version)

  • properties: A map of CSS properties that the animation will move toward
  • duration (optional): A string or number determining how long the animation will run
  • easing (optional): A string indicating which easing function to use for the transition
  • callback (optional): A function to call once the animation is complete

Parameters (second version)

  • properties: A map of CSS properties that the animation will move toward
  • options: A map of additional options to pass to the method. Supported keys are:
    1. duration: A string or number determining how long the animation will run
    2. easing: A string indicating which easing function to use for the transition
    3. complete: A function to call once the animation is complete
    4. step: A function to be called after each step of the animation
    5. queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately
    6. specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions

Return value

The jQuery object, for chaining purposes.

Description

The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a map of CSS properties. This map is similar to the one that can be sent to the .css() method, except that the range of properties is more restrictive.

All animated properties are treated as a number of pixels, unless otherwise specified. The units em and % can be specified where applicable.

In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element.

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number to or from the current value of the property.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The 'fast' and 'slow' strings can be supplied to indicate durations of 200 and 600 milliseconds, respectively. Unlike the other effect methods, .fadeTo() requires that duration be explicitly specified.

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
Click here
</div>
<img id="book" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="book.png" alt="" width="100" height="123"
style="position: relative; left: 10px;" />

We can animate the opacity, left offset, and height of the image simultaneously.

$('#clickme').click(function() {
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
$.print('Animation complete.');
});
});

jQuery 1.4

Note that we have specified toggle as the target value of the height property. As the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition:

jQuery 1.4

The opacity of the image is already at its target value, so this property is not animated by the second click. As we specified the target value for left as a relative value, the image moves even farther to the right during this second animation.

The position attribute of the element must not be static if we wish to animate the left property as we do in the example.

The jQuery UI project extends the .animate() method by allowing some non-numeric styles, such as colors, to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.

The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

As of jQuery version 1.4, we can set per-property easing functions within a single .animate() call. In the first version of .animate(), each property can take an array as its value: The first member of the array is the CSS property and the second member is an easing function. If a per-property easing function is not defined for a particular property, it uses the value of the .animate() method's optional easing argument. If the easing argument is not defined, the default swing function is used.

We can simultaneously animate the width and height with the swing easing function and the opacity with the linear easing function:

$('#clickme').click(function() {
$('#book').animate({
width: ['toggle', 'swing'],
height: ['toggle', 'swing'],
opacity: 'toggle'
}, 5000, 'linear', function() {
$.print('Animation complete.');
});
});

In the second version of .animate(), the options map can include the specialEasing property, which is itself a map of CSS properties and their corresponding easing functions. We can simultaneously animate the width using the linear easing function and the height using the easeOutBounce easing function.

$('#clickme').click(function() {
$('#book').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 5000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function() {
$.print('Animation complete.');
}
});
});

As previously noted, a plug-in is required for the easeOutBounce function.

jQuery 1.4 Reference Guide This book and eBook is a comprehensive exploration of the popular JavaScript library
Published: January 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

.stop()

Stop the currently running animation on the matched elements.

.stop([clearQueue][, jumpToEnd])

Parameters

  • clearQueue (optional): A Boolean indicating whether to remove queued animation as well. Defaults to false
  • jumpToEnd (optional): A Boolean indicating whether to complete the current animation immediately. Defaults to false

Return value

The jQuery object, for chaining purposes.

Description

When .stop() is called on an element, the currently running animation (if any) is immediately stopped. For instance, if an element is being hidden with .slideUp() when .stop() is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.

If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When .stop() is called, the next animation in the queue begins immediately. If the clearQueue parameter is provided with a value of true, then the rest of the animations in the queue are removed and never run.

If the jumpToEnd property is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our .slideUp() example, the element would be immediately hidden. The callback function is then immediately called, if provided.

The usefulness of the .stop() method is evident when we need to animate an element on mouseenter and mouseleave.

<div id="hoverme">
Hover me
<img id="hoverme" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="book.png" alt="" width="100"
height="123" />
</div>

We can create a nice fade effect without the common problem of multiple queued animations by adding .stop(true, true) to the chain.

$('#hoverme-stop-2').hover(function() {
$(this).find('img').stop(true, true).fadeOut();
}, function() {
$(this).find('img').stop(true, true).fadeIn();
});

Animations may be stopped globally by setting the $.fx.off property to true. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

.delay()

Set a timer to delay execution of subsequent items in the queue.

.delay(duration, [queueName])

Parameters

  • duration: An integer indicating the number of milliseconds to delay execution of the next item in the queue
  • queueName (optional): A string containing the name of the queue. Defaults to fx, the standard effects queue

Return value

The jQuery object, for chaining purposes.

Description

Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue.

Using the standard effects queue, we can, for example, set an 800-millisecond delay between the .slideUp() and .fadeIn() of the foo element:

$('#foo').slideUp(300).delay(800).fadeIn(400);

When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.

.queue()

Manipulate the queue of functions to be executed on the matched elements.

.queue([queueName])
.queue([queueName], newQueue)
.queue([queueName], callback)

Parameters(first version)

  • queueName (optional): A string containing the name of the queue. Defaults to fx, the standard effects queue

Parameters (second version)

  • queueName (optional): A string containing the name of the queue. Defaults to fx, the standard effects queue
  • newQueue: An array of functions to replace the current queue contents

Parameters (third version)

  • queueName (optional): A string containing the name of the queue. Defaults to fx, the standard effects queue
  • callback: The new function to add to the queue

Return value (first version)

An array of the functions currently in the first element's queue.

Return value (second and third versions)

The jQuery object, for chaining purposes.

Description

Every element can have one or many queues of functions attached to it by jQuery. In most applications, only one queue (called fx) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. The typical example of this is calling multiple animation methods on an element. For example:

$('#foo').slideUp().fadeIn();

When this statement is executed, the element begins its sliding animation immediately, but the fading transition is placed on the fx queue to be called only once the sliding transition is complete.

The .queue() method allows us to directly manipulate this queue of functions. The first and second versions of the function allow us to retrieve the entire array of functions or replace it with a new array, respectively.

The third version allows us to place a new function at the end of the queue. This feature is similar to providing a callback function with an animation method, but does not require the callback to be given at the time the animation is performed.

$('#foo').slideUp();
$('#foo').queue(function() {
$.print('Animation complete.');
$(this).dequeue();
});

This is equivalent to:

$('#foo').slideUp(function() {
$.print('Animation complete.');
});

Note that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.

.dequeue()

Execute the next function on the queue for the matched elements.

.dequeue([queueName])

Parameters

  • queueName(optional): A string containing the name of the queue. Defaults to fx, the standard effects queue

Return value

The jQuery object, for chaining purposes.

Description

When .dequeue() is called, the next function on the queue is removed from the queue and then executed. This function should, in turn (directly or indirectly), cause .dequeue() to be called so that the sequence can continue.

.clearQueue()

Remove from the queue all items that have not yet been run.

.clearQueue([queueName])

Parameters

  • queueName(optional): A string containing the name of the queue. Defaults to fx, the standard effects queue

Return value

The jQuery object, for chaining purposes.

Description

When the .clearQueue() method is called, all functions on the queue that have not been executed are removed from the queue. When used without an argument, .clearQueue() removes the remaining functions from fx, the standard effects queue. In this way it is similar to .stop(true). However, while the .stop() method is meant to be used only with animations, .clearQueue() can also be used to remove any function that has been added to a generic jQuery queue with the .queue() method.

Summary

This article revealed the mechanisms jQuery has for providing customised visual feedback to the user.


If you have read this article you may be interested to view :


jQuery 1.4 Reference Guide This book and eBook is a comprehensive exploration of the popular JavaScript library
Published: January 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Jonathan Chaffer

Jonathan Chaffer is a member of Rapid Development Group, a web development firm located in Grand Rapids, Michigan. His work there includes overseeing and implementing projects in a wide variety of technologies, with an emphasis in PHP, MySQL, and JavaScript. He also leads on-site training seminars on the jQuery framework for web developers.

In the open source community, he has been very active in the Drupal CMS project, which has adopted jQuery as its JavaScript framework of choice. He is the creator of the Content Construction Kit, a popular module for managing structured content on Drupal sites. He is also responsible for major overhauls of Drupal's menu system and developer API reference.

He lives in Grand Rapids with his wife, Jennifer.

Karl Swedberg

Karl Swedberg is a web developer at Fusionary Media in Grand Rapids, Michigan, where he spends much of his time making cool things happen with JavaScript. As a member of the jQuery team, he is responsible for maintaining the jQuery API site at api.jquery.com. He is also a member of jQuery's Board of Advisors and a presenter at workshops and conferences. When he isn't coding, he likes to hang out with his family, roast coffee in his garage, and exercise at the local CrossFit gym.

Books From Packt


jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

jQuery 1.3 with PHP
jQuery 1.3 with PHP

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Getting started with Audacity 1.3
Getting started with Audacity 1.3

Backbase 4 RIA Development
Backbase 4 RIA Development

Grok 1.0 Web Development
Grok 1.0 Web Development

NetBeans Platform 6.8 Developer's Guide
NetBeans Platform 6.8 Developer's Guide

Drupal 6 Performance Tips
Drupal 6 Performance Tips


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
p
S
m
i
4
A
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software