Animations and Effects

Users like a fluid user interface (UI) that quickly responds to their actions. The jQuery framework provides a set of animations and effects for enhancing the way your UI transitions based on user input. As these effects happen, the other markup on the page moves in response. If you slide a new bullet into a list, for example, the other bullets move to make space for the new one. The jQuery animations and effects are an easy way to add more “feel” to the look of your UI.

A simple example is to use the .hide() and .show() methods of jQuery. Recall the average speed calculator example markup (refer to Listing 18.2). You can mark the <div id='calculation'> with the hidden attribute. You can then add the following line to calculateSpeed to hide the results by default.

$('#calculation').hide();

Next, you can use .show() to animate the display of the <div> tag if the user input is valid. You would add this line under the actual calculation inside the if statement. The .show() method can be used without arguments; or, it can take the number of milliseconds it should use to fade the item into display. It can also take a named speed such as fast or slow (as in the following).

$('#calculation').show('slow'),

You need only run this once to notice the improvement this gives to the “feel” of the page. There are many similar effects to .show() and .hide() available. The following provides an overview of these standard effects. Again, most of these take the milliseconds as the duration you want the animate to spread over. You can also use named speeds like slow and fast. Of course, there are many other parameters available should you want to really customize some of these effects:

Image Basic effects—.show(), .hide(), .toggle()

Image Fading effects.fadeIn(), .fadeOut(), .fadeTo(), .fadeToggle()

Image Sliding effects.slideDown(), .slideToggle(), .slideUp()

You can also use jQuery to create custom animations. The framework provides the method .animate() (and similar supporting methods) for doing custom animations. Generally, you create a custom animation using specific CSS styles on a selection. You then tell jQuery the speed at which you want to make the changes, how you want to see the changes (linear or swing), and what to do when the animation completes.

As an example, we add the following animation to the calculateSpeed example after the call to .show(). This animates the text moving left to right from small to large. Note that once you animate something, you may have to reset the CSS if you want to reanimate the item the next time the user takes an action.

$('#calculation').animate(
  {
    width: "50%",
    opacity: 0.4,
    marginLeft: "0.25in",
    fontSize: "2em"
  }, 1000, 'swing'),

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset