jQuery 2.0 Animation Techniques: Beginner's Guide

5 (1 reviews total)
By Adam Culpepper , Dan Wellman
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Getting Started
About this book

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. jQuery empowers you with creating simple as well as complex animations.

jQuery 2.0 Animation Techniques Beginner’s Guide will teach you to understand 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.

In jQuery 2.0 Animation Techniques Beginner’s Guide, each chapter starts with simple concepts that enable you to build, style, and code your way into creating beautifully engaging and interactive user interfaces.

With the use of wide range of examples, this book will teach you how to create a range of animations, from subtle UI effects (such as form validation animation and image resizing) to completely custom plugins (such as image slideshows and parallax background animations).

The book provides various examples that gradually build up your knowledge and practical experience in using the jQuery API to create stunning animations. The book uses many examples and explains how to create animations using an easy and step-by-step approach.

Publication date:
December 2013
Publisher
Packt
Pages
292
ISBN
9781782169642

 

Chapter 1. Getting Started

Welcome to the jQuery 2.0 Animation Techniques Beginner's Guide. 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.

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 that 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, 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 the rise of Flash (and Shockwave, a competing technology that was eventually subsumed by Macromedia—which was later acquired by Adobe in 2005), 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 and 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. When 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 OS X—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 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 though, 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 handheld 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

  • 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 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 devices known to use the system are likely to be incapable of displaying the animation adequately

  • On time-sensitive actions or processes

Note

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 questions, 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 (http://jquery.com) provides a range of animation methods natively, without the use of additional effect libraries or plugins. There are, however, many plugins contributed from the online community, including jQuery UI (http://jqueryui.com), the official UI library for jQuery, which extends 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 here with descriptions of each:

Methods

Description

animate()

It performs a custom animation of a set of CSS properties.

clearQueue()

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

delay()

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

dequeue()

It executes the next function on the queue for the matched elements.

fadeIn()

It displays the matched elements by fading them to opaque.

fadeOut()

It hides the matched elements by fading them to transparent.

fadeTo()

It adjusts the opacity of the matched elements.

fadeToggle()

It displays or hides the matched elements by animating their opacity.

finish()

It stops the currently-running animation, removes all of the queued animations, and completes all of the animations for the matched elements.

hide()

It hides the matched elements.

queue()

It shows the queue of functions to be executed on the matched elements.

show()

It displays the matched elements.

slideDown()

It displays the matched elements with a sliding motion.

slideToggle()

It displays or hides the matched elements with a sliding motion.

slideUp()

It hides the matched elements with a sliding motion.

stop()

It stops the currently-running animation on the matched elements.

toggle()

It displays or hides the matched elements.

It's important to note that there are two properties that can change the Global jQuery Object. These are listed below:

Property

Description

jQuery.fx.interval

It is the rate (in milliseconds) at which animations fire.

jQuery.fx.off

It globally disables all animations.

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.

 

Creating the 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 any similar name. 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.

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 examples in the book, we'll take a look at them just once here:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="css/.css">
  </head>
  <body>
    <script src="js/jquery.js"></script>
    <script>
       $(function(){

      });
    </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://packtpub.com. If you purchased this book elsewhere, you can visit http://packtpub.com/support and register to have the files e-mailed directly to you.

Save a copy of this file into the jquery-animation folder we just created 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, it means insert it directly between the opening <body> tag and the first <script> tag in the template file we just created in the preceding code. Whenever we add any JavaScript to the template file, it will be added within the anonymous function in the second <script> tag.

Let's 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 the <meta> tag's 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.

Since the versions prior to Internet Explorer 9 (IE9) don't support any HTML5 elements, we need to use Remy Sharp's html5shiv script to make this browser use HTML5 correctly. We can link to the online version of this file for convenience using a conditional comment that targets all of the 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 24, Chrome 30, Safari 6, and Opera 17 (although expect these to change quite rapidly).

Note

It's important to note that jQuery 2.0 doesn't support oldIE, meaning IE8 and below. For this reason, we won't be covering any browser compatibility fixes for those versions of IE.

If your project needs to be compatible with IE8 or older, you'll need to use jQuery 1.10 or below. Furthermore, if your project uses HTML5 elements and needs to be compatible with IE8 or below, you'll need to use html5shiv (https://code.google.com/p/html5shiv).

IE9 does support a lot of HTML5 and CSS3, so using the html5shiv file in general will only be required as long as IE8 holds its top spot as the world's most used browser. At the time of writing, Internet Explorer 8 had a market share of 21 percent worldwide according to NetMarketShare (http://netmarketshare.com). With 19 percent, IE10 comes in second and Chrome 29, FireFox 23 and IE9 are following shortly behind. The <body> tag 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 2.0 at the time of writing (but like the browser versions, this is likely to change pretty quickly).

Throughout the book, we'll be using a local version of jQuery, so that we won't have to rely on being connected to the Internet or worry about Internet slowness. However, in most cases, in production, it's recommended to link to one of the 4 CDNs (Content Delivery Network) for jQuery. These can be found below:

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.

 

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 result is not displayed immediately, providing feedback to the user that their action is in the process of being executed is a helpful use of animation.

In the next screenshot we can see the loading indicator centered beneath the Initiate the action 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> element to <body> (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");
    var bar = $("<span></span>").css("opacity", 0.2);
    var 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").click(function () {
    if (!$("#loader").is(":visible") ) {
      loader.show();
      loadingInterval = setInterval(function () {
        runLoader();
      }, 1200);
    } else {
      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 the following code to it:

    #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 and update the HTML file to call this stylesheet.

  5. At this point, your code should look like the following screenshot once we click on the button:

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 is being added to the page for example, and then hide it again once the operation is complete.

The first thing we did inside the outer function is set some variables. We created a new <div> element as a container for the loader, using an object literal as the second argument in the anonymous function 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.

Note

An object literal is a list of paired values separated by commas and wrapped in curly braces.

We also created 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) 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 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.

Note

An interval is a numerical value set (in milliseconds) to pause or delay an action.

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 (so that each bar can be styled separately), and then append it to the container. Once the three loading bars have been added to the container, we insert the loader after the <button> element.

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 increased 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 (in milliseconds, or using strings "fast" or "slow"), the opacity that the element should be faded to as its second argument (values range from 0-1, including decimals such as 0.50), 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 same process is repeated for the third loading bar.

Finally, we use the jQuery click() method to add two functions which will be executed alternately each time the button is clicked. We'll use an if statement to check whether our #loader element is visible on the page by using .is(":visible") and adding an exclamation point (!) so that it returns true if the #loader element is not visible. If it isn't visible, we'll show the loader and then set the interval that repeatedly calls the runLoader() function. If the element is already visible, we hide the loader and clear the interval.

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 (http://api.jquery.com/jQuery.getJSON), makes a great test case. Depending on the speed of your connection, the loader may not be visible for very long.

Pop quiz – basic animation with jQuery

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

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

  2. 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

  3. As an alternative to a Flash animation

  4. When animated GIF images are not supported

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

  1. An integer representing the ending opacity

  2. An object containing configuration options for the animation

  3. 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

  4. No arguments are required

 

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 concluded the chapter with a basic example of using 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.

In the next chapter, we'll be focusing on animating images. We'll be creating a basic image rotator, and then extending the functionality of that script to build more functionality on top. We'll be left with a very lightweight image rotator that we can use on future development projects.

About the Authors
  • Adam Culpepper

    Adam Culpepper is a frontend web developer who works for Envoc, a software development firm, located in Baton Rouge, Louisiana. He is very active in his community; organizing, founding, and sitting on the board of many industry-related groups and organizations in his area. When he's not reading, writing, working, organizing, or attending a community event, he's spending time with his great friends and family or his girlfriend Amber, his son Aiden and his cat Emma. Adam can be reached at his website (www.adamculpepper.net) or through Twitter (@adamculpepper).

    Browse publications by this 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
Latest Reviews (1 reviews total)
I ordered the book to supplement my learning for a web programming course. It was very useful as a reference and learning tool.
jQuery 2.0 Animation Techniques: Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now