JavaScript tips and tricks Tutorials

javascript advanced tricks and javascript animation tricks and javascript & dom tips tricks and techniques and cool javascript tricks and codes
Dr.NaveenBansal Profile Pic
Published Date:25-10-2017
Your Website URL(Optional)
c HAPTEr 9 Helpful JavaScript Tricks Here’s the payoff for learning the JavaScript/jQuery basics covered in Chapter 8. You can apply those skills to your Animate projects. One of the easiest ways to start is to use Animate’s triggers and action snippets to write code, and then apply your own modifications to customize that code. That’s exactly how this chapter begins. Then it presents yet another version of the photo gallery, using a nifty image source swapping technique. Along the way you learn how to change an element’s dimen- sions, position, and background colors the JavaScript/jQuery way. This chapter explains how you can simplify your code by assigning symbols and elements to variables. You’ll also learn to create Animate compositions that make decisions for themselves, through the use of conditional statements. Last, but not least, you’ll see how to control symbols’ independent timelines. More Showing and Hiding Tricks Chapter 5 showed several examples using the Show and Hide actions. Now it’s time to revisit that subject and see how you can bend those simple tricks to your own iron will. Consider a simple Animate composition like the one in Figure 9-1. You can find 09-1_HideAndSeek with the exercises for this chapter on the Missing CD at www.missingmanuals. com/cds/edgepv7mm. 203m ore s ho Win G And The idea is to make the text boxes with the words Show, Hide, and Toggle behave h idin G Tri Cks like buttons. Click on the word and the car picture disappears or reappears. For example, as covered in Chapter 5, this is the quick way to make Hide work: 1. In Animate, right-click (Control-click) the word “Hide” and choose Open Actions for “tbHide” from the shortcut menu. 2. Choose click from the triggers menu. 3. In the Actions panel, click the Hide Element button on the left.  No TE  In this example, the letters tb are added to the front of each element that is a text box. As your projects grow, you may want to use similar techniques to further distinguish the many elements inside. Two or three letter prefixes or suffixes work well. That inserts the generic hide code, Figure 9-2, which looks like this: sym.("Text1").hide(); You need to change “Text1” to car so that a click on the word hides the image of the car. When you’re done, it reads like this: sym.("car").hide(); You go through a similar process when you create a trigger for the text box with the word “Show.” Just make sure you use the Show Element action. Figur E 9-1 This Animate composition has an image of a car and three text boxes with the words “Hide,” “Show,” and “Toggle.” Guess what happens next. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 204m ore  No TE  s ho Win G And Check back on page 121 if you need to brush up on showing and hiding elements using triggers and h idin G Tri Cks actions. So what about that word “Toggle”? It can be awfully handy to have a single but- ton or command to turn an element on the web page on and o. Y ff ou could write something with one of those conditional statements like, “If the car is visible, hide the car; else show the car.” But there’s an even easier way. jQuery has a companion to the show and hide functions called toggle. All you need to do is follow the steps above to apply a click trigger and a hide action to the car element. Then you can edit the statement. You want to change the hide action to a toggle action. When you’re done, the code for Toggle looks like this: sym.("car").toggle(); Save your work and give it a test. If the car is visible, clicking either Hide or Toggle makes it disappear. Likewise, if the car is hidden, clicking Show or Toggle makes it reappear. Delaying Action for Show, Hide, and Toggle If you read through Chapter 8, you may recognize that show(), hide(), and toggle() are functions. Somewhere deep in the JavaScript code that’s linked to your Animate composition are the routines that make these functions perform. When your browser comes across a function name like hide(), it looks up those routines and applies them to the car element. You don’t have to know the nitty-gritty coding details that make a function work; it’s enough to understand what they do and how to use them. It’s like the difference between driving a car and being an auto mechanic. Here’s one more hide, show, and toggle trick. You can add arguments (sometimes called parameters) to the hide(), show(), and toggle() functions that change the way they behave. Open the click actions for the text box “hide.” Change the code by placing the number 4000 inside the parentheses after “hide.” The statement should look like this: sym.("car").hide(4000); Do the same for the show() function of the text box with the word “Show.” Now test the composition. When you click on “Hide” and “Show,” the box gradually shrinks from view or grows into view from the upper-left corner. You may have seen this technique used to show and hide menus on a navigation bar. Without any argument, “Toggle” still works instantaneously. You may recall that JavaScript likes to divide time into milliseconds—that is, thou- sandths of a second. That’s exactly what’s happening in your hide() and show() functions. It takes 4 seconds for the shrinking and growing to take place. If you’d rather use words to specify the timing, try “slow,” “normal,” and “fast.” Don’t forget to include the quote marks. Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 205m ore s ho Win G And h idin G Tri Cks Figur E 9-2 When you use Animate’s triggers and actions, you often need to modify the code for your needs. For example, here the generic hide code needs to be edited to identify “car” as the element to hide. Fading In and o ut As the infomercial salesperson likes to say: But wait There’s more The shrinking and growing from the previous example works well for some chores, like menus. For photos and other images, a nice dissolve animation works well. Sure, you can create this effect on the timeline and use “Play from” triggers, but why bother if you can do the same thing by swapping functions? If you want to keep using the same composition, you can change the words in the text boxes to read “Fade Out” and “Fade In” or you can add new text boxes to do the job. You can continue to use click as the trigger. The action uses new functions: • fadeOut(): The element dissolves (becomes less opaque) until it disappears. • fadeIn(): The element increases in opacity until it is fully visible. • fadeToggle(): Shows or hides the element by changing its opacity. Keep in mind, as always, JavaScript and jQuery are case sensitive, so be sure to fadeOut() rather than FadeOut or fadeout. As with the hide() and show() functions, you can use arguments to control the speed. These fading actions accept both numbers (in milliseconds) and the words “slow,” “normal,” and “fast.” Slip Sliding Up and Down Order now and you’ll get sliding action, too You guessed it: You can swap these functions in place of show() and hide(). • slideUp(): Slides an element up until it disappears. • slideDown(): Slides an element down until it is fully visible. • slideToggle(): Shows or hides the element using the sliding action. As with the hide() and show() functions, you can use arguments to control the speed. These sliding actions accept both numbers (in milliseconds) and the words “slow,” “normal,” and “fast.” ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 206m ore s ho Win G And If you completed all the steps, you’ll have a hide-and-seek sampler that you can h idin G Tri Cks view in your browser, Figure 9-3. If you haven’t followed along, you can find 09-2_HideAndSeek_done on the Missing CD at edgepv7mm. Figur E 9-3 The text boxes in this example all work like buttons. Click on a word to see how the function affects the image of the car. Examine the code, and you’ll see the different delay settings that control the timing of the animated effect. FREQUENTLY ASKED QUESTIo N The Fickle Finger of Click Why don’t I see that pointing finger when my cursor moves In this example, tbHide is the ID for the text box that holds the over a clickable item? word “Hide.” It is the element with the mouseover trigger. With this action in place, the cursor changes to a pointing finger We’re all well-trained. We expect to see that pointing finger when it’s over the text box. In the earliest preview versions of when we move our cursor over a button or a hyperlink. Yet Edge Animate, there was no cursor property for elements, so when you create clickable elements in Animate, that’s not this was the standard way to add that familiar pointing finger. always the case. Page 160 explains how to set the cursor There are several other cursor variations that you can use. They property for an element. See Figure 9-4. Then, that cursor match the options shown in Figure 9-4. In the example on appears automatically when you mouse over the element. page 213, simply replace the word pointer with one of these: There is a JavaScript/jQuery fix to this problem, too. It involves crosshair, e-resize, help, move, n-resize, ne-resize, nw-resize, only one piece of code. First right-click (Control-click) an ele- progress, s-resize, se-resize, sw-resize, text, w-resize, and ment in your project, and then choose the mouseover or trigger. wait. (The resize cursor options display an arrow. The letters In the actions planel, add a line of code that looks like this: in front indicate the direction of the arrow. For example, for sym.('tbHide')).css('cursor','pointer'); nw-resize, think “northwest-resize.”) Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 207m ore s ho Win G And h idin G Tri Cks Figur E 9-4 In Properties, Animate has a nifty feature that makes it easy to specify a cursor style that’s used when someone mouses over an element on the stage. More Visual Eec ff ts with animate() As explained in Chapter 7, formatting chores for web pages can be handled by CSS (Cascading Style Sheets). JavaScript and jQuery statements can rewrite the CSS rules and, in the process, change the way elements appear on a web page. The animate() function does just that. For example, using animate(), you can change the opacity of the car image, or you can change the appearance of the text in a text box. The animate() function works a little differently from the previous ones, because it can use several arguments at once. For example, you can change the opacity of an image and crop the image at the same time. To do that with the car image, you’d write the function like this: sym.("car").animate( opacity: .25, width: 200px ); There are a few new things to note in this example. The animate() function holds arguments inside parentheses like any self-respecting function. The opening paren- thesis is at the end of line 1, and the closing parenthesis is at the beginning of line 6. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 208m ore s ho Win G And Inside those, there are curly braces that hold multiple arguments. In this case, the h idin G Tri Cks arguments specify the opacity and width of the image. These arguments match up with standard CSS specs, and they’re separated by commas. The function is consid- ered a single command, so there’s only one semicolon at the end of the command. In this case, the width spec scales the image by changing its width. Since the car graphic is over 380 pixels wide, the code scrunches the car, making it shorter. You can use triggers to run more than one action, so you can change the car image and change the specs for a block of text all at once. This time, let’s suppose you want to use a rectangle as a button. 1. At the bottom of the 09-1_HideAndSeek example, draw a rectangle. Name it btnBar. 2. Right-click (Control-click) btnBar and choose Open Actions for “btnBar” from the shortcut menu. 3. Choose the click trigger. 4. In the btnBar Actions panel, write these lines of code: sym.("car").animate( opacity: .25, width: 200 , 2000 ); sym.("tbHide").animate( fontSize: '12', fontFamily: 'Times' , 2000 ); The font changes work for tbHide because it has a p tag associated with it. Paragraphs have font properties. If it had a div the changes woudn’t work, be- cause in HTML divs don’t have any font properties. If you’re familiar with CSS, you may remember that you specify font size using a hyphenated identifier: font-size. Typefaces are also specified with a hyphenated identifier: font-family. In JavaScript, these identifiers don’t use a hyphen, which might be confused with a subtraction operator. Instead they use what’s known as camel text, where the first word begins with a lowercase letter and subsequent words start with an uppercase letter, as in fontSize and fontFamily. You can specify the delay for animate() effects as you do with show() and hide() functions. In this example, the delay is set to 2000 for both the car image and the tbHide text box. The 2000 appears right before the closing parenthesis, and it is also separated by a comma. For a working copy of the Hide and Seek exercise, see 09-2_HideAndSeek_done from the Missing CD. Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 209m ore s ho Win G And What, No Slide Left and Slide Right? h idin G Tri Cks You may have noticed the absence of “slideLeft” and “slideRight” methods in the tips on page 206. That’s because they don’t exist. The slideUp and slideDown methods are built into JavaScript, but if you want to slide left or right, you have to roll your own. Fortunately, it’s not that hard, now that you know the power of the animate() method. All you have to do is find out the position of the left edge of an element, and then change the position of that edge. In the filmstrip project back on page 100, several photos of flowers were combined into one long JPG image. That example was accomplished using the timeline: By moving the left edge of the filmstrip, you make different photos slide into view. (You can check out the finished project from the Missing CD: 04-6_Film_Strip_done .) You can create the same effect using triggers, actions, JavaScript. The first thing you need to do is find the left edge of the filmstrip, which you can do with a JavaScript statement like this: sym.("flowerStrip").position().left; The sym.(“flowerStrip”) portion of the statement identifies the flowerStrip element. Then the .position().left method gets the left edge or the x position for the element. So, what can you do when you know the value of the left edge of an element? As explained on page 220, you can display that value using an alert() method, which is helpful when you’re debugging a project. An even more powerful use for the value is to store it to a variable. The last example in this book (page 231) does that using the value in a switch() conditional statement. You can use the .animate() method to move the element to a new position on the stage. That statement looks like this: sym.("flowerstrip").animate(left: "-500px", "slow"); That code changes the position of the left edge of flowerStrip slowly moving it 500 pixels to the left, as shown in Figure 9-5. Just what you want to make your filmstrip work. As you probably guessed from this example, you use negative numbers to slide left and positive numbers to slide right.  TIp  You can use the animate() method with the right, top, and bottom edges, too. In the case of the filmstrip, the left edge is the most logical choice for positioning. If you want to experiment, use 09-3_Slide_Left from the Missing CD. If you’d rather cut to the chase, you can see a finished example: 09-4_Slide_Left_done . You’ll notice that there’s something lacking in the finished example: one click moves the filmstrip one image and that’s the end of the show. It takes a few more JavaScript tools to develop a smoothly functioning filmstrip, as you’ll see later in this chapter (so keep your files handy). You’ll need to know how to store a value to a variable where it can be manipulated (page 216). You’ll also need a conditional statement that knows how to make a decision, like “If the left edge of flowerStrip is at -500px, ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 210sWAPP in G im AGes in Anim ATe change the value of the left edge to -1000px.” To perform this kind of JavaScript wizardry, check out the switch() conditional statement on page 231. Figur E 9-5. The animate() method is used with a click trigger to slide the filmstrip 500 pixels to the left. This statement displays a different flower photo on the stage. Swapping Images in Animate One of the keystones of web design is the image swap. You see it used all over the place, and JavaScript is usually the engine that’s working behind the scenes. In the earlier examples, you saw how JavaScript could rewrite CSS specifications for for - matting and positioning. In the case of an image swap, JavaScript is rewriting the src (source attribute) for an image tag. Want to make a button change its appear- ance when the cursor is over it? Use the mouseover trigger. You’ll need a mouseout trigger to change it to its normal state when the cursor moves away. Want a button to change when it’s clicked? You can use mousedown and mouseup to change its appearance. In each case, you want to swap the source of the button image. The perfect place to practice your image swapping chops is a photo gallery. photo Gallery Revisited One common technique for displaying a group of photos is to have one large main photo and smaller thumbnail images, as shown in Figure 9-6. Your audience can click or mouse over a thumbnail to display that pic as the main photo. This type of gallery works well for up to about a dozen photos. If you try to use too many photos, the thumbnail images are too small to be useful. The project 09-5_Rollover_Gallery is ready to go. If you want to see the end result, check out 09-6_Rollover_Gallery_done. Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 211sWAPP in G im AGes in Anim ATe Figur E 9-6 Here’s a common layout for a rollover photo gallery. Point to one of the images at the bottom, and it is displayed as the main photo at the top. This technique uses simple image swapping code and works on computers, tablets, and phones. Examine the gallery files and you’ll find that some of the work has been done for you. The main photo and thumbnails are in place on the stage. In the Elements panel, you have four thumbnail images, each beginning with sm_ (think “small”). The main photo is named “bike.” Select it, and you’ll notice the filename listed in Properties. All the images, big and small, are in the images subfolder of your project. In fact, there are three other images that don’t appear on the stage: farmhouse, squirrel, and flowers. The project will use these photos, but they don’t need to be imported as long as they’re in the images subfolder. They’ll be referenced as sources for the main photo. Follow these steps to finish up the rollover gallery: 1. Select the large bike photo. Then, in Properties, change the div tag to img. Animate automatically applies the div tag to everything you import. In this case, you want to use the src attribute of an img tag. This step is important, because later you want to use CSS properties that are unique to an img element. 2. With bike still selected, in Properties change the image name to mainPhoto. In the Elements panel, you see mainPhoto when the image is selected. The bike won’t remain a bike for long, so it’s best to give it a more generic name that will make sense in your code. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 212sWAPP in G im AGes in 3. Right-click (Control-click) the farmhouse thumbnail and choose Open Actions Anim ATe for sm_farmhouse, and then choose mouseover from the triggers. You’re making life easy for gallery visitors. They won’t even have to click to swap photos; all they have to do is move the cursor over a thumbnail. 4. On the left side of the Actions panel, click the Hide Element button. You don’t really want to hide anything, but this is an easy, typo-free way to write much of the code you need. In the next step, you’ll make alterations. 5. Change “text1” to “mainPhoto”. Then change the hide() function to attr(). With these changes, your code should look like: sym.(“mainPhoto”).attr(); 6. Inside the parentheses for the attr() function, type: ‘src’,’images/farmhouse.jpg’. Now the line of code looks like this: sym.(“mainPhoto”).attr(‘src’,‘images/farmhouse.jpg’); Make sure you use single quote marks around the src and photo attributes. The src attribute identifies the source for an image. The images/farmhouse.jpg text provides the path and name of the photo. You use similar code for each of the thumbnails. 7. On a new line in the Actions panel’s mouseover tab, type this line: sym.(“sm_farmhouse”).css(‘cursor’,‘pointer’); As explained in the box on page 207, this line will change the cursor to that familiar pointing finger when it is over the farmhouse thumbnail. The box also explains how to use the cursor button in Properties to create this effect. 8. Click the x button in the upper-right corner of the Actions panel. Go to File➝Save and then press Ctrl+Enter (c-Return). The Actions panel closes, and you preview your project in your browser. 9. Move your mouse over the farmhouse thumbnail. The cursor changes to the pointing finger and the main photo changes to show the farmhouse. If your project behaves differently, go back and double-check your code. Pay particular attention to the parentheses and those single quote marks. Make sure the photo path references the images folder, not the image folder. Make sure that you changed the mainPhoto’s tag to img, as described in step 1. 10. Open the Actions panel for sm_farmhouse. Select and copy (Ctrl+C or c-C) the code in the panel. You need to add similar code to the other three thumbnails. You might as well save time by copying, pasting, and editing the code. Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 213iden Tifyin G And Ch An Gin G elemen Ts 11. Open one of the other thumbnails. Choose the mouseover trigger, and then And symbols paste (Ctrl+V or c-V) in the code. When you paste it in, the code looks like this: sym.(“mainPhoto”).attr(‘src’,’images/farmhouse.jpg’); sym.(“sm_farmhouse”).css(‘cursor’,’pointer’); The text that needs to be edited to match the thumbnail is shown in bold. 12. Repeat the copy-and-paste process for the rest of the thumbnails. When you’re done, you have a working photo gallery. The thumbnails are big enough that they should work for an iPhone as well as a computer. If you want to dress the project up a little more, you can create rollover highlights or a drop shadow to mark the currently selected pictures. oTHER USES Fo R Ro LLo VERS All you need to do is roam the Web a bit, and you’ll see all sorts of rollover examples, like changing the cursor to a pointing n fi ger. They give your audience useful feedback. If you tackled the previous exercise, then you can see how you’d create a simple rollover button. Create two images for your button, one for its normal state and one for the mouseover state. As with the gallery example, give your images helpful names when you create them. With buttons, you may want to add something to the end of the name that identifies the state. For example, if you’re creating website navigation buttons, you could have image filenames like home.jpg, home_ovr.jpg, contact.jpg, and contact_ovr.jpg. Import the normal state button to your project, and make sure the mouseover state button is in your images file, and you’re ready to swap. Identifying and Changing Elements and Symbols When you’re working with triggers and actions, half the battle is identifying the ele- ment that you want to change. The other half of the battle is changing its properties. When learning new coding techniques, it’s best to start simple and build your skills. Consider a composition with two elements: a rectangle and a text box. In this case, the text acts as a button changing the width of the rectangle. Here’s the lay of the land, as shown in Figure 9-7: • The rectangle’s ID is Square. • The text box’s ID is tbChangeSquare. • There’s nothing else on the stage. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 214iden Tifyin G And Ch An Gin G elemen Ts And symbols Figur E 9-7 The stage is set for your first identification project. The rectangle’s ID is set to Square because that’s its shape to start. The text box’s ID is set to tbChangeSquare. It will act as a button that changes the width property of Square. You want to put your code in the “click” trigger for the text box tbChangeSquare. (For a refresher on using a click trigger see page 204.) Your code is like building blocks that you use to identify an element and its properties. You almost always start at the outermost level—that’s the main stage symbol. As explained back on page 170, you use the word “sym” to identify a symbol. The main stage and its timeline are the mother of all symbols for a project. sym. Animate, like JavaScript, uses dot (.) notation to separate elements that are inside of other elements. Here the stage (sym) is one element and Square is another. You also use dots to separate the properties and methods that belong to elements. Now that the stage is identified, it’s time to zero in on the rectangle with the ID “Square.” sym.("Square"). Think back on page 205, during the discussion of show() and hide() functions, where the car element is identified using the jQuery selector. That’s what’s going on here. The dollar sign () along with the ID is used to zero in on a specific element. You’re going to use CSS to change the format of this element, so the next step is to add another building block: sym.("Square").css() A number of properties can be changed using CSS and, as explained on page 220, the process involves pairs: a property name and a value. These pairs go inside the parentheses, with each listed inside quotes. The name/value pairs are separated by a comma. Suppose you want to change the width of Square to 400 pixels: the final bit of code looks like this: sym.("Square").css("width","400px"); Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 215iden Tifyin G And Ch An Gin G elemen Ts The units for width and height values are given in pixels (px). Lastly, you need to And symbols end the statement with a semicolon. Right-click (Control-click) the text box tbChangeSquare and choose the click trig- ger. Paste or type your line of code and then test your project. It should look like Figure 9-8. Figur E 9-8 Here’s the code that gets attached to the “click” trigger of the text box ID’d as tbChangeSquare. When the text gets clicked Square will be square no more. Assigning Variables It’s common to use variables to identify different symbols, elements or values. In fact, that’s what many of Animate’s action buttons do. Look for ones with names like Get Symbol or Get Element. You get to choose the variable name, and then you assign a value to the variable. Suppose you want to shorten the way you identify Square. A line of code like this does the trick: var theSquare=sym.("Square"); Now you can use the variable theSquare to reference the element with the ID of Square. No more need to mention the stage (sym) or use the jQuery selector with dollar signs, parentheses, quotes and brackets. It gives you an easier way to make changes to that element. So, you can change the width, height, and fill color with commands like: var theSquare = sym.("Square"); theSquare.css("width","400px"); theSquare.css("height","400px"); theSquare.css("backgroundColor","blue"); ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 216iden Tifyin G And Ch An Gin G elemen Ts But there’s an even better way to change multiple properties of a single element. And symbols You don’t have to repeatedly identify Square. You can identify it once and change multiple properties at once as long as the changes appear within curly braces. It works like this: var theSquare = sym.("Square"); theSquare.css( "width" : "400px", "height" : "400px", "backgroundColor": "blue" ); Put curly brackets inside of the parentheses, then you can list several properties within those brackets. As usual, you need to put both the property name and the value in quotes. In this case, separate property names and values with a colon, then separate each property/value pair using commas. Using Actions to Assign Variables The Actions panel gives you snippets of code that can be used to assign symbols and elements to variables. For example, when you click on Get Element, Animate provides this snippet: var element = sym.("Text1"); As always, you can change the code for your own purposes, replacing “element” with any variable name you want. In this case, sym identifies the stage level element. Then replace Text1 with the ID of the child element you want to identify. Click the Get Symbol button to add this snippet: var mySymbolObject = sym.getSymbol("Symbol1"); In this case, the getSymbol() function replaces the jQuery selector, but really the drill is the same. Change the variable name (mySymbolObject) to something meaningful for your project. Then swap “Symbol1” with the ID of a symbol that’s on stage or listed in your Element panel. Remember, there may be many instances on stage of a single symbol in the Library. When you’re animating, you’ll want to identify specific instances on the stage. The getSymbol() method identifies a specific instance of a symbol by its ID, which you’ll find in the Properties panel when it’s selected. You can also see the instance names in the Elements panel whether the instance is visible on stage or not. Once you’ve identified a specific instance of a symbol, you have access to its timeline and any child elements within the symbol.  TIp  For more details on working with the getSymbol method, go Help➝Edge Animate JavaScript API (ap- plication programming interface). This opens Adobe’s technical notes on the using JavaScript with edge in your web browser. Search for “getSymbol” and you’ll find a section called Working with Symbols. Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 217iden Tifyin G And Ch An Gin G elemen Ts And symbols Co DER’S CLINIC Move On Up to the Code Window When you’re just beginning to learn JavaScript and jQuery, the to add your code. If you’d like to use some snippet buttons like action panels directly associated with elements are helpful. the ones in the action panel, click the bracket button in upper- Their whole system prompting you with triggers and offering right corner. Your snippet friends will join the fun. action buttons makes it easy to keep your place and learn the The Code window has one other nifty trick up its sleeve. It new language. As your projects get more complex and your checks the syntax of your statements while you work. If it sees coding skill improve you may be willing to give up some of that an obvious mistake, an error message appears at the bottom hand-holding for the ability to work more quickly. If that’s the of the window. See Figure 9-9. As is often the case with syntax case, it’s time to move on up to the Code window, where you checkers, the messages can be puzzling. Perhaps the most can quickly access all the code in your project. You’ll spend less helpful thing they do is point you to a specific line in the code time opening and closing windows for individual elements and where Animate found something unexpected. The error is in more time writing and learning code. that line or sometimes the line preceding it. Go to Window➝Code or press Ctrl+E (cmd-E) to open the The choice between the Code window and the Actions panels window. On the left side you see the elements in your project, isn’t an either/or decision. You can use both. For example, you beginning with the Stage. If an element has a trigger and code may want to start off your project using Action panels to add attached, you’ll find it there. Click the element name to examine code snippets to some elements. Then as your project grows the code. Want to add code for an element that’s not listed? you may want to use the Code window to copy and paste some Click the + button next to Stage, then choose Elements. Choose of that code to other elements. from the list of elements and then choose the trigger. That adds the element and trigger to the column on the left. You’re ready Figur E 9-9 The Code window is a great tool when your code and projects get more complex. With all the code for all the elements in one place, you can quickly and easily automate your composition. The Code window even checks for errors, as shown in the warning at the bottom. It caught an error in Line 12 of the displayed code. Someone forgot a closing parenthesis. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 218iden Tifyin G And Ch An Gin G elemen Ts Checking Values with Text Boxes and Alert Dialogs And symbols When you begin assigning values to element properties and variables, you may want to check them. One quick and dirty way to do that is to create a temporary text box and then place the property or variable in question in the box. For example, perhaps you’d like to check the width of the variable theSquare. 1. Add a new text box to your project and change its ID to tbValue. Initially, you need to have some placeholder text in the box. Something like “Values” will work. 2. Open the click trigger that changes the size of theSquare. In the previous exercise, tbChangeSquare had the click trigger. 3. Add this line below the other code: sym.("tbValue").html(theSquare.css("width")); Here’s the breakdown of that new line: sym identifies the main stage and time - line. (“tbValue”) identifies the text box. html is a property of textboxes and it expects text—a string of characters. Now, with a few explanatory comments, the code for the click trigger looks like this: // Assign the Square element to the variable theSquare var theSquare = sym.("Square"); // Change the width, height and backgroundColor properties of theSquare theSquare.css( "width" : "400px", "height : "400px", "backgroundColor" : "blue" ) // Show the "width" value of theSquare in the text box tbValue sym.("tbValue").html(theSquare.css("width")); There are some new things going on in that last line of code. The .html() method is used to add html code to a web page. (See the box on page 221 for more details on adding hyperlink tags to your text boxes.) Put a string of text inside of those parentheses and it appears on the page. In this case, it appears within the tbValue text box. You could put a string literal in the text box like this: sym.("tbValue").html('My manual is missing'); If you want to see the value of a property, all you need to do is put the prop- erty name within the parentheses. So, to display the theSquare’s width you put theSquare(“width”) inside of the parentheses. Ch APter 9: h el Pf Ul jA VAsC ri PT Tri Cks 219iden Tifyin G And Ch An Gin G elemen Ts 4. Test your composition. And symbols When you click “Change the square,” all the width changes take place and the tbValue text box displays the value “400px.” If your composition doesn’t work as expected, double-check the parentheses. In particular, make sure the last line ends with two closing parentheses and a semicolon. You can check out a finished example 09-7_Variables_Values_done from the Missing CD (www.  TIp  If you think your value-checking text box will be getting a lot of use, you probably want to assign it to a variable, too. For example: var valueBox=sym.(“tbValue”); Then you can check values in this manner: valueBox.html(theSquare.css(“width”)); Using variables often simplifies the identification of elements. It not only speeds things up when you’re coding, it means you’re less likely to create a script-stopping typo. USING ALERT() DIALo G Box ES To CHECK VALUES If you don’t want to clutter up the stage with temporary text boxes, you can use the alert() dialog box in a similar fashion. It works in a browser like a pop up window. One of the downsides of this method is that you need to close the alert() window before you can continue previewing your animation. The code for an alert box looks like this: alert("text appears here");  TIp  If you place an alert() function in your code and the dialog box never appears, that’s a sign that there’s an error somewhere. Often, the error occurs before the alert() and so the script stops and the alert() function never runs. The text within the quotes is displayed literally. However, you can use it just like the html property of the text box to display values of properties or variables. For example, you can do this: alert(theSquare.css("backgroundColor")); The result is that the background color of theSquare is displayed in the alert dialog box. You used the shorthand “blue” to describe the background color. JavaScript prefers to refer to the color’s RGB values, so you see: rgb(0, 0, 255).  TIp  If you’re ready to move up to more powerful debugging tools for your JavaScript/jQuery projects, consider Firebug ( ) an extension for the Firefox browser. Firebug, itself, has many extensions for dier ff ent scripting languages and libraries. If you use Google’s Chrome browser, check out the built-in Developer Tools. You can find them by clicking the wrench icon in the upper-right corner, then choosing Tools→Developer Tools. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 220iden Tifyin G elemen Ts WiThin s ymbols Co DER'S CLINIC Adding HTML Anchor Tags to Text Boxes Back on page 169, you saw that it’s easy to apply an HTML anchor a variable. The main purpose of the .html() method is to add tag a (sometimes called a hyperlink) to an entire text box, HTML code to a web page. Just place the code you want inside but not so easy to apply a link to specific words within a text of the parentheses and inside of quotation marks. So that line box. If you’ve delved into the HTML for a web page, you’ve shown earlier might look like this if it were placed inside of undoubtedly seen anchor tags like: an Animate action: Why not buy a a href= sym.("tbText").html("Why not buy a a ""Missing href=''Missing Manual/a? Manual/a?"); In this example, the words “Missing Manual” appear on the You can use all your favorite tags, like h1, p, br/ and of course web page as a hyperlink that opens the page identified by a. Squeeze as much as you want inside of those parentheses and the URL within the quotes. your box will display it all. If you enter a line like that in a text box, you end up with The big question is, what do you want to use to trigger the html() everything. The tags which should be hidden, are visible and method. You can use any trigger you want, but in most cases you there’s no hyperlink. The solution lies in the .html() method won’t use a “click” trigger to change big chunks of text on a page. that works with text boxes. The exercise on page 219 shows More often, you’ll want to use the stage’s compositionReady trigger. how to use the .html() method to display text or the value of Identifying Elements within Symbols When you start putting elements inside of symbols, you add another layer of complexity to identifying parts of your composition. Just remember to start on the outside and work your way in. Think of onion layers or those wooden Russian dolls nested inside each other. Suppose you have a symbol instance on the stage and an element inside of that symbol. The order to identify that interior element is: stage then symbol instance then element. For experimentation, draw a square, a circle and a text box with “Words” shown, as shown in Figure 9-9. Give them these IDs: • Square ID = Square • Circle ID = Circle • Text Box ID = Words Select all three elements and press Ctrl+Y (c-Y), the Modify→Convert to Symbol command. In the Library, name your symbol BoxSymbol. Drag two instances of BoxSymbol on to the stage. They’ll need better unique names than the ones Animate provides. Give them IDs of BoxInstanceOne and BoxInstanceTwo. Ch APter 9: h el Pf Ul jAVAsC ri PT Tri Cks 221iden Tifyin G elemen Ts WiThin If you’re going to change the elements within an instance of a symbol on the stage, s ymbols your first step should be to identify the instance. For ease of use later, you might want to assign that instance to a variable, like this: var boxTwo = sym.getSymbol("BoxInstanceTwo"); If you click the Get Symbol button, as explained on page 217, you need to replace Symbol1 with the ID of the symbol instance. You may also want to change the vari- able name mySymbolObject to something more helpful. The next step is to identify the element within the symbol. Suppose you want to change the text in the Words text box in boxTwo. You can zero in on the text box like this: boxTwo.("Words") Next on the to do list is identifying the property for your text: html. boxTwo.("Words").html(); Your text can be a string literal (as explained on page 195) or it can be a variable that has a string assigned to it. A string literal might look like this: boxTwo.("Words").html("To be or not to be"); If you’re going to use a variable, it needs to be defined in advance. Like this: var Hamlet = "To be or not to be"; boxTwo.("Words").html(Hamlet); If you want to change the height property of the element with the ID of Square, the code would look like this: var boxTwo = sym.getSymbol("BoxInstanceTwo"); boxTwo.("Square").css("height", "400px"); If you want to trim down the code even more you can create a variable that identi- fies Square within the symbol: var boxTwo= sym.getSymbol("BoxInstanceTwo"); var theSquare = boxTwo.("Square"); theSquare.css("height","400px"); The first line is identical to the previous code. The second line creates a new variable called “theSquare” and assigns the element inside of boxTwo with the ID “Square” to the variable. The last line uses “theSquare” to identify the element within the symbol and assigns a value to the height property of the element. Even if there are several instances of the symbol on the stage, only the Square inside of boxTwo will change. For some more details about working with nested symbols, see the box on the next page. You can explore some of these symbol and element techniques in the completed example called 09-8_Get_Symbol_done. See Figure 9-10. It shows how to change specific elements inside of two instances of the same symbol. ADOBe e DGe Anim Ate Preview 7: t he missin G mA nu Al 222

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.