Chapter 8. Controlling Your Animations with JavaScript and jQuery

If you worked on some of the examples in Chapter 5, you’ve already dabbled in JavaScript and jQuery. When Animate creates triggers and actions, it produces JavaScript/jQuery code. Modern browsers all understand this code, and it works universally, unless someone has explicitly turned JavaScript off. Like the CSS code mentioned in Chapter 7, JavaScript can be interspersed within the HTML code for a web page, or a separate JavaScript (.js) file can be can be linked to the page.

This chapter isn’t meant to be a complete study of JavaScript and jQuery, but it is meant to help you get started. You’ll learn how to read the code that Animate produces, and you’ll learn how you can tweak that code to customize your Animate compositions. Throughout, you’ll find tips and techniques that help solve common issues when you’re working in Animate. This chapter focuses mostly on JavaScript and jQuery theory. Chapter 9 explains how to put this theory into action.

Once upon a time (in the 1990s), there was a company called Netscape, which delivered one of the first widely used web browsers, Netscape Navigator. Soon, the company was in a death battle with another company called Microsoft, which put forth a competing browser called Internet Explorer. In an effort to keep a competitive edge over their nemesis, some Netscape wizards developed a scripting language that could be used to add automation and interactive features to web pages. The language had different names at different times, like Mocha and LiveScript, but the name that stuck was JavaScript. JavaScript was welcomed and widely used by the web-making masses. It proved to be so popular that Microsoft developed its own version, JScript…but that’s another tale. At times, JavaScript suffered from all-too-familiar tech ailments: competing standards and implementation conflicts among browsers. (Translation: Microsoft’s Internet Explorer behaves differently from every other browser.) As time went by, many of these issues were smoothed over. Support for JavaScript became more consistent among browsers. JavaScript libraries were developed, which made it easier for web designers to focus on building pages rather than dealing with browser inconsistencies. jQuery is one of the most popular libraries that serve this function. (Pardon the pun.) jQuery helped solve many other issues for JavaScript coders, truly living up to its motto: Write less, do more. With the advent of HTML5, many new and powerful tools were available for web building, and when combined, they were very powerful indeed. Web builders were happy, and the web page audience enjoyed visually entertaining and interactive experiences. Sadly, Netscape didn’t survive, but JavaScript lives on.

If you want to create a simple animation that runs from start to finish, you don’t have to dig into JavaScript/jQuery code. However, if you want to add interactivity to your project or perform other magical feats, you’ll want to add triggers and actions as explained in Chapter 5. If you want to modify those triggers and actions, you need to learn something about the way JavaScript and jQuery work. At first, programming and animation may feel like a curious match, since artists and programmers often seem to be such different people. But when you think about it, programming and drawing are both creative activities. Just like an artist, a programmer needs imagination and vision. And animation is a very programmatic visual art, complete with reusable chunks of action that branch off into separate scenes. On large creative teams, you’ll find some people responsible for artwork and others responsible for code. However, there are plenty of small shops where the same person handles both duties.

One of the best ways to learn how JavaScript works is to read code. That’s easy enough to do, and it’s exactly where this chapter starts. You can begin by examining the code that Animate creates when you save a project. Then add an element or make a change, and examine the new code that Animate creates. Bit by bit, you can learn how certain chunks of code affect your project.

Follow these steps to see how this technique works:

When you examine the source code for the empty web page, there’s nothing much new that wasn’t discussed in previous chapters. There’s a <script> reference to the JavaScript preloader, Empty_edgePreload.js. The preloader is responsible for linking your project to all the resources it needs. Many of those are JavaScript libraries. For details, see the box on Animate Project Files. You won’t be messing with the files in your edge_includes folder. Those are standard libraries, like jQuery. You want to examine the two JavaScript files that are specific to your project. Conveniently, they’re in the same folder with the .html file for the page and the first part of the filename matches your project. So, as you see in the bottom of Figure 8-1, if your project name is “Empty,” then the preloader filename is Empty_edgePreloader.js. If you inspect the preloader code at the bottom, you see an object called aLoader and its definition. Note the names of JavaScript files in the the definition, like jquery-1.7.1.min.js. These are files of JavaScript code that Edge Animate needs to do its magic. Another line that begins: loadResources(aLoader, doDelayLoad); is a function that makes use of the aLoader object. You can examine JavaScript files in some web browsers or in a text editor like Notepad (Windows) or TextEdit (Mac). Another option for viewing and editing HTML, CSS and JavaScript files is Adobe’s Edge Code a sibling in the Edge family. You can get the application from the Adobe Creative Cloud (http://creative.adobe.com).

aLoader = [
    { load: "edge_includes/jquery-1.7.1.min.js"},
    { load: "edge_includes/jquery.easing.1.3.js"},
    { load: "edge_includes/edge.1.0.0.min.js"},
        {test: !hasJSON, yep:"edge_includes/json2_min.js"},
          { load: "Empty_edge.js"},
          { load: "Empty_edgeActions.js"}];

loadResources(aLoader, doDelayLoad);

The first time you open the Empty_edge.js file, it may be a little confusing. There are lots of strange terms and characters, like { }, ( ), and $, sitting on indented lines. It starts off like this:

 /** Adobe Edge: symbol definitions
 */
(function($, Edge, compId){
//images folder
var im='images/';
var fonts = {};

var resources = [
];

var symbols = {
"stage": {
   version: "1.0.0",
   minimumCompatibleVersion: "0.1.7",
   build: "1.0.0.180",
   baseState: "Base State",
   initialState: "Base State",
   gpuAccelerate: false,
   resizeInstances: false,
   content: {
         dom: [
],
         symbolInstances: [

         ]
      },
   states: {
      "Base State": {
         "${_Stage}": [
            ["color", "background-color", 'rgba(255,255,255,1)'],
            ["style", "width", '550px'],
            ["style", "height", '400px'],
            ["style", "overflow", 'hidden']
         ]
      }
   },
      ...the .js file continues but is not shown here...

If you’re new to this, try the drowning sailor technique: Grab hold of anything that looks recognizable. Comments are always good. (For a refresher on comments, see the box on Many Ways to Comment.) There’s a block comment at the top that says, “Adobe Edge: symbol definitions.” That’s pretty clear. The code that follows must define the symbols in the project.

Around the tenth line in the preceding code, you see:

"stage": {

It seems likely that this is a reference to Animate’s stage. Lines that follow appear to define the stage. There’s a reference to “Base State” and later states, which sound suspiciously as though this code may set the starting values for specific properties for the stage. Sure enough, down around line 20, there are more Base State details, including height, width, and background-color. Animate master that you are, you remember that these are properties you can set in the stage’s Properties panel. In fact, at this point, if you’re daring, you can edit these properties from inside this JavaScript file. For example, if you change the line:

["style", "height",'400px'],

to:

["style", "height",'800px'],

and then save the Empty_edge.js file, then the next time you open Empty.html in a browser, the stage will be 800 pixels tall.

The next chunk of code appears to set values for the base state of the timeline. It looks like this:

timelines: {
   "Default Timeline": {
      fromState: "Base State",
      toState: "",
      duration: 0,
      autoPlay: true,
      timeline: [
      ]
    }
  }
}
};

The duration property has a value of 0. That’s about right for an Empty Animate project. Likewise, autoPlay is set to true, which seems about right.

As shown in Figure 8-2, the code near the bottom of the file, beginning with:

Edge.registerCompositionDefn(compId, symbols, fonts, resources);

…and through to the end, is used to set up the composition (Animate project). It checks to see that everything is loaded and that the browser window is ready. When it’s ready, it runs the launchComposition method.

/**
 * Adobe Edge DOM Ready Event Handler
 */
$(window).ready(function() {
     Edge.launchComposition(compId);
});
})(jQuery, AdobeEdge, "EDGE-23150191");

The more code-sleuthing becomes a habit, the faster you’ll learn JavaScript and its partner in crime jQuery. If you carefully duplicate and save projects, you can experiment with the code just to see what happens. If you mess up a duplicate file or project—no problem. Just delete it and try again.

The next step in the sleuthing expedition is to add a new element to the stage and see how that changes the code in Empty_edge.js. It’s best to start simply, so you don’t get lost in a sea of code, so just add a square that’s 100 x 100 px and name it Square.

Open the Empty_edge.js file in a code editor or plain text editor and you see the new code that defines your square. Under these lines that were already in the project when it was empty:

content: {
      dom: [

you see:

{
            id:'Square',
            type:'rect',
            rect:['146px','78px','104px','104px','auto','auto'],
           fill:["rgba(192,192,192,1)"],
            stroke:[0,"rgba(0,0,0,1)","none"]
         }],

The first few lines are pretty clear. There’s an element with the ID of Square. That’s the name you gave to the rectangle. The next line confirms that the element is the “rect” type. The other lines describe the rectangle properties you’d find in the Properties panel (Figure 8-3). The next three lines describe the appearance of the rectangle. For example:

rect:['146px','78px','104px','104px','auto','auto'],

The first two numbers set the position of the rectangle (X=147, Y=89). The next two numbers describe the width and height. A couple of the rectangle’s properties are set to “auto.” Following that, the fill and stroke properties are set in rgba terms: red, green, blue, and Alpha.

fill:['rgba(192,192,192,1)'],

In this case, the fill is gray, because of the even red, green, and blue values. With Alpha set to 1, the square is 100 percent opaque. Want to change your square to be red? Edit that line to read:

fill:['rgba(255,0,0,1)'],

Want to make the square semi-transparent? Change that last number (a) to a decimal, like this:

fill:['rgba(255,0,0,.5)'],

Now, there may not be a great value in being able to edit values like these on a new Animate project; you can easily make those changes in Animate when you begin a project. But there is a value in experimenting to see how changes like these affect elements in your project. The things you learn at this stage can be applied to other chunks of code you create using triggers and actions. From time to time, you may get JavaScript code from members of your project team or other sources. The more fluent you are in JavaScript/jQuery, the better you’ll be at solving problems and building masterpieces.

JavaScript shares many programming concepts with other popular languages. If you have any programming experience, from C to Java to ActionScript, you certainly have a head start with JavaScript. This section covers some of the JavaScript and jQuery basics that are helpful to know when you’re working with Animate. It’s certainly not a complete reference or a tutorial on the subjects. If you’re looking for a complete study of JavaScript and jQuery, that’ll take an entire book. The name of that book happens to be JavaScript and jQuery: The Missing Manual by David Sawyer McFarland (O’Reilly). You can find online information about JavaScript at www.w3schools.com/js or https://developer.mozilla.org/en/JavaScript.

When it comes to types of data, JavaScript provides the usual suspects:

Here are some other features you should keep in mind when you work in JavaScript:

Programs and scripts perform their magic through a sequence of operations where variables are assigned values, calculations are performed, and comparisons are made. These operations require operators like + for addition and / for division. The operators used in JavaScript are similar to those used in other programs and scripting languages.

The assignment operator is =. You use this to assign a value to a variable, as in:

age = 23;
name = "James Joyce";

Basic math operations use these standard operators:

OPERATION

OPERATOR

EXAMPLE

Add numbers

+

45 + 21

Subtract numbers

-

45 - 21

Multiply numbers

*

45 * 21

Divide numbers

/

21/7

You can use these operators with literals—that is, actual numbers—or you can use them with variables that have number values assigned to them. Sometimes you’ll end up with a string that is a numeral, as in:

age ="23";

The variable “age” has been assigned a string. You can tell by the quote marks. That string happens to be numerals. What if you want to perform a math operation with age? JavaScript gives you an easy way to convert that string to its numerical value.

Just put a + sign in front, like so:

doubleAge =+age * 2;

Then you can calculate to your heart’s content.

A special set of operators is used to compare values. The trickiest one is the equal-to operator. It’s easy to forget you want two = signs, as in ==.

Here are the comparison operators. The result of each example is true:

OPERATION

OPERATOR

EXAMPLE

Are two values equal?

==

(4+1)==5

Are two values unequal?

!=

(4+1)!=3

Is the left value greater than right value?

>

24 > 12

Is the left value greater than or equal to the right value?

>=

24 >= 12

24 >= 12 + 12

Is the left value less than the right value?

<

12 < 24

Is the left value less than or equal to the right value?

<=

12 <= 24

12 <= 6 + 6

JavaScript gives you a way to modify and rewrite HTML documents. JavaScript does this by accessing elements in the document and then making changes. CSS formatting works in a similar way when it applies formatting to individual elements in a web page. In effect, it amounts to rewriting the HTML that defines the page. The document object model, affectionately known as the DOM, is the skeleton of any web page, as visualized in Figure 8-4. It’s a conceptual definition of a web page that describes the elements.

Before you can make changes to an element in an HTML document, you need to identify or select that element. There are three common ways to identify the elements in a web page: by tag, by ID, or by class.

JavaScript has methods for getting an element by ID and for getting an element by tag. It also provides ways to move around the DOM to select different elements. This technique is called traversing, and if you’re not used to using it, it’s likely to cause headaches. However, there’s good news and more good news: jQuery provides ways to select elements that are much easier to use. And, for the most part, Animate uses jQuery methods to select elements.

In Animate, when you name an element, something is going on behind the scenes. Animate is giving that element an ID. So if you name a photo mainPhoto in Animate, it’s just as if you’d written id=“mainPhoto” in the <img> tag. Remember how CSS references IDs by placing a # (pound sign) in front of the name? (For a reminder, see Applying CSS Styles to Element IDs and Classes.) jQuery uses the same system. If you want to reference your mainPhoto using jQuery, you’d write:

$('#mainPhoto')

Remember how CSS references classes by placing a period in front of the name? jQuery uses that system to identify classes, too. If you want to select all the elements in the gallery class, it looks like this:

$('.gallery')

Finally, if you want to select all the elements with <img> tags, you don’t need any special character at the front. That would look like this:

$(img)

In JavaScript, the word “this” has a special meaning. A great deal of your effort in writing and editing JavaScript and jQuery code involves identifying exactly the right element so that you can do something to it. You may want to move it to a new position. You may want to change its color. You may want to replace all the text that it displays. The reserved word “this” is often used to identify an element that has been clicked or the object from which a function (method) is called. However, “this” is more flexible in JavaScript than it is in other languages, so its use may surprise you. In Animate, “this” usually refers to the symbol. When you first fire up Animate, that symbol is the main stage and its timeline. The lookupSelector() function may be used to identify specific element—in other words, children of that symbol. For example, this statement will identify an element named “text1” and then hide it:

$(this.lookupSelector("text1")).hide();

Early versions of Animate used this code in the Actions panel, and it still works. However, later versions of Animate use a slightly different syntax:

sym.$("Text1").hide();

In this case, “sym” stands for “symbol.” If you’re working on the main stage, sym refers to the stage and its timeline. If you’ve created new symbols and opened one up for editing, the word sym refers to that symbol’s stage and timeline. The dollar sign is the jQuery selector that looks up the element by name (ID). The .hide() function remains the same. You can add this statement using the Actions panel and then edit it for your own purposes. Change text1 to the name of the element you want to identify. Then, if needed, change the function hide() to one that you want to use. One great advantage of this “build-it-yourself snippet” is that you’ll cut down on typos in your code.