Book Image

jQuery 2.0 Animation Techniques: Beginner's Guide - Second Edition

Book Image

jQuery 2.0 Animation Techniques: Beginner's Guide - Second Edition

Overview of 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.
Table of Contents (18 chapters)
jQuery 2.0 Animation Techniques Beginner's Guide
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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