jQuery 1.4 Animation Techniques: Beginners Guide

By Dan Wellman
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction

About this book

Master animation in jQuery to produce slick and attractive interfaces that respond to your visitors' interactions

jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML, and is the most popular JavaScript library in use today. Using the features offered by jQuery, developers are able to create dynamic web pages. This book will act as a resource for you to create animation and advanced special effects in your web applications, by following the easy-to-understand steps mentioned in it.

jQuery 1.4 Animation Techniques: Beginners Guide will allow you to master animation in jQuery to produce slick and attractive interfaces that respond to your visitors' interactions. You will learn everything you need to know about creating engaging and effective web page animations using jQuery. The book uses many examples and explains how to create animations using an easy, step-by-step, beginners guide approach.

This book will provide you with...

This book provides various examples that gradually build up the reader’s knowledge and practical experience in using the jQuery API to create stunning animations. The book starts off by explaining how animations make your user interface interactive and attractive. It explains the various methods used to make the element being animated appear or disappear. It provides a set of steps to create simple animations and show fading animations.

You can later learn how to make complex animations by chaining different effects together as well as how to halt a currently running application. You will find out how to slide your animation elements and learn to create custom animations that can be complex and specialized.

You will find out how to obtain and set up the jQuery UI— the official user interface library for jQuery. The book will tell you how to animate a page's background image, and will teach you how to make images scroll in a certain direction and at a certain speed depending on the movement of the mouse pointer

Publication date:
March 2011
Publisher
Packt
Pages
344
ISBN
9781849513302

 

Chapter 1. Introduction

Welcome to the jQuery 1.4 Animation Techniques: Beginner's Guide book. Over the course of the book we'll look at each and every method that produces or controls animations available in the jQuery JavaScript library. We'll see how the methods are used, the arguments they are able to accept, and the different behavior they produce. We'll also look at how to use a range of accompanying resources including selected jQuery plugins and the jQuery UI library.

In this introductory chapter, we'll look at the following topics:

  • A brief history of animation on the Web

  • Why animating your UIs is important

  • Animation methods provided by jQuery

  • The template file used by each of the examples

  • A basic animation example

 

Animation on the Web


In 1989 Compuserve released GIF89A, an enhanced version of the popular GIF image format which allowed a sequence of frames to be stored as a single image and played by supporting software.

The GIF format was already popular on what passed for the Internet in those days (remember, the World Wide Web didn't even exist until 1991) due to its small file size, lossless compression, and wide support. The enhanced version, which allowed animations that anyone could create themselves provided they had supporting software, quickly became popular also.

In addition to animated GIFs, browser vendors added support for proprietary HTML elements that handled animation natively, such as the <blink> and <marquee> elements, which added different animated effects to text.

Neither of these elements was particularly attractive or successful and the W3C, as well as leading industry accessibility and usability experts, advised against their use in most cases. Different browsers at the time supported one or the other of these elements but not both. Both elements were added by their respective vendors as part of the original browser wars.

In the late 1990s, popular browsers added support for a technique known as Dynamic HTML (DHTML), which allowed scripting languages to modify the contents of a page after the page had loaded. DHTML wasn't any single technology, but rather a collection of techniques (JavaScript, CSS, the DOM, and so on) that worked together to enable a basic level of interactivity and/or animation.

In fact, DHTML made it possible to create quite advanced animations, but restrictions in the early implementations of the required technologies, as well as hugely varying browser support, made DHTML tricky at best.

This era also saw the release and rise of Flash (and Shockwave, a competing technology that was eventually subsumed by Macromedia), a vector and raster graphics format that allowed audio and video streaming, frame-by-frame animation, and a host of other features. Flash quickly became popular and at the time of writing is still the number one format for web-based video, browser-based gaming, and advertising.

Gradual standardization of the DOM across (most) browsers, as well as the rise of JavaScript libraries such as jQuery, which abstracted away the differences that remained between browsers, have opened up animation to a much wider range of people than ever before. The term DHTML isn't often used these days because of its connotations with poor support between browsers, but the underlying principles and techniques that drive many interactive and animated sites remain similar.

Today, in addition to the animations made plausible and accessible by JavaScript libraries we have much newer, much more exciting possibilities with CSS3 and native HTML elements such as the <canvas> element, which provides complete pixel-level control over an area of the page. We'll be looking at some CSS3 animation techniques, as well as the <canvas> element in more detail towards the end of the book. Flash-based animation is on the decline for the first time this century, and new technologies are poised on the horizon.

 

The power of animated UIs


Modern operating systems use animations constantly to engage their users and to create a more compelling computing experience. Used in the right way, animations provide assistance to the users of the system, to lead and guide them through different tasks, provide context or feedback, and reinforce positive actions.

A good example of this is the way that applications are minimized in Windows 7, or OSX—the application appears to squish down into the icon on the taskbar/dock, which shows the user where to go when they want to return to the application. It's the simple details like this that can be the most effective.

Good animations can lend an air of sleek professionalism to an interface and make it appear more advanced or more modern. Apple's iPhone (or iPad) is a perfect example—the seamless use of subtle animations and transitions within the operating system and its applications allow the user to connect with the device in a profoundly satisfying and immersive way. Anything that appears or disappears is faded smoothly in or out, and menus and content panels slide in or out from the top or the sides. Sudden events can unsettle or distract users, but a well-timed animation can help to make them aware that something is happening or something is about to happen.

Be warned however—badly executed, clumsy, or overly pointless animations can do the opposite, making your interface appear basic, poorly designed, or inferior. No animation can be better than poor animation. Even if your application works perfectly, superfluous animations can leave your users feeling frustrated and cause them to forgo your application or website.

Desktop computers and a rapidly growing number of mobile and hand-held devices are easily powerful enough to handle quite complex animations, and with integrated hardware acceleration and more refined CSS3 and HTML5 making its way into the latest browsers, the possibilities of what can be achieved on the Web are increasing exponentially.

When to use animations

Animations can make a great impression and enhance the user experience in the following situations:

  • When showing or hiding windows, pop ups, and content panels

  • When something is moved to a different area of the window or page

  • When something has changed state on the page as a result of the action of the user

  • When something is transitioning between different states

  • To lead the user to a specific call to action or bring their attention to something important

When not to use animations

Too many animations or animations in unnecessary places can be damaging. Try and avoid animations, or at least give them serious consideration, in the following situations:

  • When an action needs to be repeated very frequently by the user

  • Where the capabilities of the devices known to use the system are likely to be incapable of displaying the animation adequately

  • On time-sensitive actions or processes

Bear in mind that these are guidelines only, not laws which must be obeyed at all costs, and they are certainly not definitive. There are few situations where animations should never, ever be used and few situations where they must always be used.

Use your judgment to determine whether an animation is suitable for your application or page and its intended audience. If possible, give your users the chance to enable or disable animations based on their own personal preferences.

Animation checklist

Before implementing an animation in our pages or applications, consider the following checklist of questions:

  • Is the animation appropriate for your target users?

  • Is the animation practical?

  • Does the animation add value or enhance the user experience?

  • Will the animation run at appropriate speeds on the devices that are most likely to be used?

If you can answer yes to all of the above, the animation will probably be a positive feature. If you answered no to any of these questions, you probably need to stop and think about what you are trying to achieve by adding the animation, and whether or not it could be better achieved in some other manner.

 

Animating with jQuery


jQuery provides a range of animation methods natively, without the use of additional effects libraries or plugins. There are however, many plugins contributed from the online community, including jQuery UI, the official UI library for jQuery, which extend jQuery's animation capabilities. Natively, jQuery provides methods that add sliding and fading behavior with minimal configuration, and which work cross-browser. It also exposes methods related to managing the animation queue, and provides a means for creating custom animations that work on almost all numerical CSS styles. Over the course of this book, we'll look at every animation method that the library contains in detail. These methods are listed below:

  • animate()

  • clearQueue()

  • delay()

  • dequeue()

  • fadeIn()

  • fadeout()

  • fadeTo()

  • fadeToggle()

  • hide()

  • queue()

  • show()

  • slideDown()

  • slideToggle()

  • slideUp()

  • stop()

  • toggle()

All in all, it gives us a powerful and robust environment to easily add almost any type of animation that we can conceive.

Animation is also a popular theme for plugins, with many available plugins that bring different types of animations to our fingertips, for instant implementation with minimal configuration. We'll look at several plugins later in the book.

 

The template file


Each of the example files we'll create throughout the course of this book will rely on a common set of elements. Rather than repeatedly showing these same elements in every single code section and example in the book, I'll show you them just once now:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="css/.css">
      <!--[if lte IE 8]>
      <script src=http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
      <![endif]-->
  </head>
  <body>
    <script src="js/jquery.js"></script>
    <script>
       (function($){


      })(jQuery);
    </script>
  </body>
</html>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Save a copy of this file now and call it template.html. This is the base file that we'll use for every single example, so when we start working through the examples and I say "add the following markup to the <body> of the template file", I mean insert it directly between the opening <body> tag and the first <script> tag in the template file, as shown above. Whenever we add any JavaScript to the template file, it will be added within the anonymous function in the second <script> tag.

Let's just take a look at what the template file contains. We start out with the HTML5 doctype declaration as we'll be using plenty of HTML5 elements in our examples. We also set the lang attribute of the <html> element to en, and <meta> tag with its charset attribute to utf-8, neither of which are strictly required but are nevertheless best practice.

Next comes an empty <title> element, to which we can add the name of each example, and a <link> element with an incomplete href, ready for us to add the name of the stylesheet that each example will use.

Because current versions (prior to version 9) of Internet Explorer don't support any HTML5 elements, we need to use Remy Sharp's html5shiv script to make this browser use them correctly. We can link to the online version of this file for convenience using a conditional comment that targets all versions of IE lower than version 9. Feel free to download html5.js and store it locally if you plan on playing with the examples in IE while disconnected from the Internet.

To get the most out of the examples throughout the book, it would probably be wise to upgrade to the latest stable release versions of the most common browsers, which at the time of writing are Firefox 3.6.13, Chrome 9.0, Safari 5.03, and Opera 11, although expect these to change quite rapidly.

At the time of writing, Internet Explorer 9 is available in beta release and is scheduled to go to full release at some point in early 2011. IE9 does support a lot of HTML5 and CSS3, so using the html5shiv file may not be required.

The <body> of the page is empty except for some <script> tags. We'll obviously use jQuery in every example, so the first tag links to that. The current version of jQuery is 1.5 at the time of writing (but like the browser versions, this is likely to change pretty quickly!).

In the second <script> tag we have an empty function, into which all of the example JavaScript code we write will go. We pass the jQuery object into our anonymous function and alias it to the $ character. Although not strictly necessary (except in the example where we create a jQuery plugin), this is another good habit to get into.

Creating a project folder

So that's the template file that we'll be referring to and using in the code examples throughout the book. Let's also take a moment to look at the folder structure that the example files use. Create a project folder and call it jquery-animation or similar. Within this, create three new folders and call them css, img, and js.

The HTML pages we create will go into the jquery-animation folder alongside the subfolders. All of the CSS files we create will go into the css folder and all of the images that we use in the examples will go into the img folder. The jQuery library and any additional script files we use or create will go into the js folder. This is also the directory structure you'll find if you download and unpack the accompanying code archive containing all of the examples.

 

A basic animation example


Let's look at a basic example of the kind of animation that can help reassure our visitors that something is happening. If the user performs an action, and the results are not displayed immediately, feedback that their action is in the process of being executed is a helpful use of animation. This is what we will end up with at the end of the example:

In the previous screenshot we can see the loading indicator centered beneath the trigger <button>. It features three separate loading bars which sequentially light up to show that something is happening. Each bar is styled slightly differently.

 

Time for action – creating an animated loader


In this example we'll create a simple animated loading indicator that we can start when a particular process is initiated, and stop once the process has completed.

  1. Open up the template file that we just looked at and add the following <button> to the <body> of the page (this should go before the <script> elements):

    <button id="go">Initiate the action</button>
  2. Next, in the empty function in the second <script> element at the bottom of the page, add the following code:

    var loader = $("<div></div>", {
        id: "loader"
      }).css("display", "none"),
      bar = $("<span></span>").css("opacity", 0.2),
      loadingInterval = null;
    
      for (var x = 0; x < 3; x++) {
      bar.clone().addClass("bar-" + x).appendTo(loader);
      }
    
      loader.insertAfter("#go");
    
      function runLoader() {
        var firstBar = loader.children(":first"),
        secondBar = loader.children().eq(1),
        thirdBar = loader.children(":last");
    
        firstBar.fadeTo("fast", 1, function(){
          firstBar.fadeTo("fast", 0.2, function() {
            secondBar.fadeTo("fast", 1, function() {
              secondBar.fadeTo("fast", 0.2, function() {
                thirdBar.fadeTo("fast", 1, function() {
                  thirdBar.fadeTo("fast", 0.2);
                });
              });
            });
          });
        });
      };
    
    $("#go").toggle(function() {
      loader.show();
      loadingInterval = setInterval(function() { runLoader(); }, 1200);
    }, function() {
      loader.hide();
      clearInterval(loadingInterval);
    });
  3. Save the file as loading.html in the main project folder (jquery-animation). Finally, we'll need to add a few basic styles to the example. Create a new file in your text editor and add to it the following code:

    #loader { margin:10px 0 0 36px; }
    #loader span {
      display:block; width:6px; float:left; margin-right:6px;
      border:1px solid #336633; position:relative;
      background-color:#ccffcc;
    }
    #loader .bar-0 { height:15px; bottom:-20px; }
    #loader .bar-1 { height:25px; bottom:-10px; }
    #loader .bar-2 { height:35px; margin-right:0; }
  4. Save this file in the css folder as loading.css.

What just happened?

The <button> hardcoded onto the page is used to show and hide the loading animation. This is done purely for the purpose of this example. In an actual implementation, we'd show the loading animation at the start of a load operation, when new content was being added to the page for example, and then hide it again once the operation was complete.

The first thing we do inside the outer function is set some variables. We create a new <div> element as a container for the loader, using an object literal as the second argument to the $() (jQuery()) method to give it an id of loader. We then set its style to display:none with jQuery's css() method so that it is not immediately visible.

We also create a new <span> element, which will be used as a template to create the three individual loading bars. We set its opacity to 0.2 (20% opaque), also using the css() method. jQuery normalizes this style for us so that it works correctly in Internet Explorer. The last variable, loadingInterval will be used to store the id of an interval so that we can clear the interval when we need to. We set this to null initially as the interval has not yet been set.

Once our variables have been defined and initialized, we then execute a short for loop, with just three iterations. Within this loop we clone the span element we created, give it a class name for styling purposes, and then append it to the container. Once the three loading bars have been added to the container, we insert the container after the <button>.

Next we define a function called runLoader. This is the function that will be repeatedly called by the interval. The function doesn't run until the button is clicked. Within this function we cache the selector for each of the three individual bars and then run a series of nested functions.

We first increase the first loading bar to full opacity using the fadeTo() jQuery animation method. This method takes a string indicating the speed of the animation as its first argument, the opacity that the element should be faded to as its second argument, and a callback function as the third argument. The callback function is executed as soon as the animation ends.

In the callback function, we then fade the first loading bar back to its original opacity of 0.2. We supply another callback function to this method call, and within this callback function we animate the second loading bar to full opacity, and then back to its original opacity. The process is repeated for the third loading bar.

Finally, we use the jQuery toggle() method to add two functions which will be executed alternately each time the <button> is clicked. In the first function, we show the loader and then set the interval that repeatedly calls the runLoader() function. In the second function, we hide the loader and clear the interval.

Pop quiz – basic animation with jQuery

  1. Thinking about what we discussed earlier regarding when and when not to use animations, when would be an appropriate time to use this animation?

    a. When there is a browser-intensive operation taking place

    b. When there is a delay between something being requested from the server and the request returning from the server, but where the processing required by the browser is minimal

    c. As an alternative to a Flash animation

    d. When animated GIF images are not supported

  2. What arguments are used with jQuery's fadeTo() method?

    a. An integer representing the ending opacity

    b. An object containing configuration options for the animation

    c. A string or integer representing the speed or duration of the animation as the first argument, the ending opacity of the target element, and optionally a callback function to be executed when the animation ends

    d. No arguments are required

Have a go hero – extending the loading animation

I mentioned that we could use the loading animation when making requests and waiting for a response. Try using it with jQuery's AJAX methods, showing the loader just before making the request, and hiding it again once the response has been processed. The JSONP example, which retrieves images of cats, on the jQuery website at http://api.jquery.com/jQuery.getJSON/) makes a great test case, although depending on the speed of your connection, the loader may not be visible for very long.

 

Summary


In this introductory chapter, we looked at a brief history of animation on the Web including how it began, early HTML elements and browser support, the rise of Flash, and the direction it's heading in the not too distant future.

We also looked at how animations can be used in a user interface to enhance the user experience. We saw some guidelines as to when animation should and shouldn't be used and looked at some of the things we should consider when implementing animations.

We closed the chapter with a basic example looking at a loading animation. In this example, we used the fadeTo() jQuery method to change the opacity of elements on the page, and a simple interval to "play" the animation. We didn't cover the method in full detail, but we saw one example of how it can be used. We'll look at this method in more detail in the next chapter, which covers all of the fading animations provided by jQuery.

About the Author

  • Dan Wellman

    Dan Wellman is an author and frontend engineer living on the South Coast of the UK and working in London. By day he works for Skype and has a blast writing application-grade JavaScript. By night he writes books and tutorials focused mainly on frontend web development. He is also a staff writer for the Tuts+ arm of the Envato network, and occasionally writes for .Net magazine. He's the proud father of four amazing children, and the grateful husband of a wonderful wife.

    Browse publications by this author
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial