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’re familiar with Flash and now you’re adding Animate to your web-building toolbox, you’re not alone. You’ll find that JavaScript has a lot in common with ActionScript, Flash’s programming language. Technically, they’re both scripting languages, meaning that they’re programming languages that run inside other environments—like web pages. On top of that, JavaScript and ActionScript both share the same programming language specification, ECMA-262.
Since you’re just dying to know, ECMA stands for European Computer Manufacturers Association, the standards group that established the spec.
Initially, programmers used both JavaScript and ActionScript in snippets to perform quick and easy chores. These snippets are similar to the triggers and actions in Animate. For example, in ActionScript, you’d write something like the following:
on (press) { startDrag(this); }
Often, you’ll find JavaScript interspersed throughout the HTML code that describes web pages. From a technical point of view, JavaScript and ActionScript are considered high-level languages, because they’re closer to human language than the 1s and 0s of machine language.
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:
Create a new Animate project and immediately save it with the name Empty.
Animate creates HTML and JavaScript files.
Go to File→Preview In Browser.
Your project opens in your web browser. Surprise—you see an empty page.
Right-click (Control-click) the web page in your browser and choose View Source (or View Page Source).
Most browsers show the HTML code for a web page in a separate tab or window.
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);
Most browsers give you a way to view a web page’s HTML source code. The command is usually View Source or View Page Source. If you’re using Google Chrome for a browser, then after you choose View Page Source, you can click on the JavaScript filenames in the displayed code to view the JavaScript files in a new tab, as shown in Figure 8-2. This is a quick, handy way to study code, but you can’t edit the files. Both Google Chrome and Mozilla Firefox have great developer tools that help you examine web pages and the files that make them work.
Figure 8-1. Top: All popular web browsers let you view the HTML source code for a web page. The command in Chrome, shown here, is Right-click→View Page Source. Bottom: The source shown here lists the preload script that Animate adds to the web page. In turn, the preload script links several JavaScript libraries to the page.
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.
If you edit your Animate project’s JavaScript file while it’s still open in Animate, you tend to confuse Animate. You’ll see a message noting that the file has been changed and you’ll be asked if you want to reload the file. If you say Yes to reload the file, you load the file that was saved outside of Animate and you lose any change you made in Animate. If choose No, you won’t see any changes in Animate. However, if you save the file, you’ll overwrite any changes you made outside of Animate.
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.
Figure 8-2. In Google Chrome, you can open a web page, then view the HTML code. If there are links to external JavaScript files, a click will display the code in a new tab, as shown here. The code at the bottom of this file registers Animate projects and plays the composition when the browser is ready.
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.
Hold the Shift key down when you drag out a rectangle to create a square. Keep your eye on the Properties panel, and it’s not hard to create a 100 px 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.
Figure 8-3. You can find the same properties that define a square’s position, size, and color in the JavaScript code that Animate creates. Tweak the code, and you change the way your square looks in Animate and on the web page.
When it comes to types of data, JavaScript provides the usual suspects:
Numbers can be whole numbers like 756 or decimals like 7.56. Numbers are expressed without any particular punctuation. For example, you might have a statement like:
var myNumber = 12 + 5;
The 12 and 5 are added together, and the result is stored in the variable myNumber.
Strings are groups of characters, like your name or the words “Moby-Dick.” Strings must appear inside quotes, either single or double. Statements with valid strings might look like this:
var author = "Herman Melville"; var firstSentence = 'Call me Ishmael.';
You can combine two strings using the + operator. For example:
var author = "Herman " + "Melville";
Stores a single string “Herman Melville” in the author variable.
Booleans, as usual, have two values: true or false. They’re often used to determine if a certain condition exists. Here’s an if conditional statement that checks to see if the sun has come up:
sunRise = true; if (sunRise == true) { newDay(); };
The first line assigns the value “true” to the variable sunRise. If it’s true that the sun has come up, then the newDay() function is performed. The details of newDay() are defined elsewhere. It’s important to remember that the operator to compare equal values is ==, not a single =.
Arrays provide a convenient way to group several items together. For example, an array of colors might look like this:
var colors = ['red','blue','green','alpha'];
In that case, you could retrieve values from the array with a statement like this:
myFavorite = colors[1];
The numbering for arrays always begin with 0, so in this example colors[1] references blue.
A single array can hold different types of data. So for example, an array for an employee could have strings that store first and last names, and numbers that store age and number of years employed. There are a number of ways to add items, remove items, and change items in an array. Details are available online at www.w3schools.com/js or https://developer.mozilla.org/en/JavaScript.
Functions consist of one or more statements that can be executed. You may be surprised to see functions listed among the data types, but in JavaScript, functions are considered a data type. As a result, functions have some interesting capabilities. For example, they can be stored in variables or arrays. A function might be declared like this:
function fullName(first, last) { return first + ' ' + last; }
The word “function” explains that the code that follows is a function. The name of the function is fullName, and it takes two arguments: first and last. These arguments need to be provided when the function is called. One or more statements for the function appear in between curly braces { }. This function joins three strings to create one string. The arguments first and last are strings, presumably the first and last names. In between, a string literal is used to insert a space character. Code to call the function might look like this:
name = fullName(firstName, lastName);
In this case, the variables firstName and lastName are presumed to be strings that have already been defined to represent someone’s name. So if previously the variable firstName was given the value Umberto and lastName was given the value Eco, then this statement would assign the string “Umberto Eco” to the variable name.
Here are some other features you should keep in mind when you work in JavaScript:
JavaScript is loosely typed. Unlike many other languages, variables do not have a specific data type when they are created. This means a variable could be assigned a number value and then later a string value.
JavaScript is case sensitive. Capitalization matters in JavaScript. That means “javascript,” “JavaScript,” and “javaScript” could be used to name three separate variables.
Variable names must be specific characters. Variables must begin with a letter, $, or _. They cannot begin with a number. The rest of the characters in a variable must be letters, numbers, $, or _. Variables can’t contain any other characters or punctuation.
JavaScript has reserved words. Like most programming languages, JavaScript has a number of words that have special meanings. These are usually called reserved words or keywords. You don’t want to confuse the process by using these words for variables or in other places. The following are examples of reserved words:
You can find the complete list of JavaScript reserved words at https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words.
JavaScript uses semicolons (;) to end statements. To properly interpret JavaScript code, browsers need to know where one statement ends and the next begins. JavaScript uses semicolons to separate statements. If there’s only one statement on a line, many browsers will let you get away with not putting a semicolon at the end, but it’s considered a best practice to always put a semicolon at the end of a statement.
JavaScript ignores whitespace. In general, JavaScript ignores spaces, tabs, and new lines. That leaves you free to add whitespace to your code to make it more readable. Naturally, if you put whitespace in the middle of something like a number, that would change 736 into two numbers, 7 36.
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 <= 6 + 6 |
Comparison operators are often used in conditional statements. For example, as a programmer for the Department of Motor Vehicles you might say, “If this applicant’s age is less than 16, then deny driver’s license.” Written in JavaScript, the statement might look like this:
If (applicantAge < 16) { denyLicense(); alert('License is denied, due to youthful recklessness!'); }
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.
Tags are HTML’s basic method for identifying things like headings <h1> or paragraphs <p>. Tags always use angle brackets: < >.
IDs are used to identify one unique item on a page. An ID can be assigned to an element using an attribute within a tag. For example, a picture could be given an ID of mainPhoto within the <img> tag:
<img id="mainPhoto" src="images/bearcat.jpg">
Classes are used to identify similar elements on a page. To identify a photo as part of the “gallery” class, you’d write:
<img class="gallery" src="images/bearcat.jpg">
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.