Section 4.2. Scripting Your Button


4.2. Scripting Your Button

Now that you know how to make a button, you have to learn what to do with it. Remember, Flash will take care of the visual feedback, including cursor and state switching, but the button won't otherwise be functional. Don't worry, though. You can start scripting with a little assist.

4.2.1. Easy Scripting with Script Assist

If you prefer to write your own HTML rather than using a GUI editor, you may want to skip this section and move on to "Hand-Coding." However, sometimes assisted scripting can help even veterans remember a bit of seldom-used syntax, or the specific parts required to complete a line of code. For this reason, giving this section a quick look won't hurt.

If you're not yet comfortable with writing code, Flash 8's Script Assist can help you find your way. It's a guided method of shaping your script into its final form. While it would not be possible to create an unknown variety and complexity of code with a wizard-like linear interface, Script Assist is the next best thing.

You start by browsing a nested menu of available ActionScript entries and double-clicking on something you would like to add to your script. Flash does its best to determine where to add the code and to start the script with the appropriate syntax. It then presents a series of user interface (UI) elements, such as text boxes, menus, and radio buttons, to help you finish the code. All you have to do is fill in the appropriate values, and a script is born.

Now modify Chapter 3's project by scripting a button that will open a web page:

  1. Open the file animation_buttons.fla in the 04 folder. This is the animation you completed in the last chapter, but a new layer called buttons has been added. In the last frame of this layer, two new buttons exist in a keyframe. The arrow button will eventually play the animation again, and you'll code the globe now to launch the web site. These buttons have been created for you to allow you to focus on the scripting in this chapter, but if you want to practice creating your own buttons, that's a good idea, too.

  2. Select the globe button and open the Actions panel using the Window Actions menu command.


  3. In the Actions panel, make sure that the button is selected and that the title bar says "ActionsButton." (It's easy to put a script in the wrong place if the wrong thing is initially selected.) In this exercise, you want to create a button script rather than a frame script.

  4. If you've been following along, or the default setup is still intact, your Actions panel should look the same as it did in Chapter 3: a vertical menu area on the left, and a text editor on the right (see Figure 3-15). This is the configuration used by most Flash coders with some scripting experience. It allows you to type in the script as you might in any text editor, but with additional features such as syntax coloring, code hinting, and similar benefits. This is the setup you used to enter the stop() action to prevent your last animation from looping.

  5. You'll return to the hand-coding method after this demonstration, but for now you should see Script Assist at work. If the left side is not visible, drag the vertical bar on the left edge of the window to the right, exposing the menu. If the right half of the window has a shorter text area beneath a reserved area, you're probably already in Script Assist mode. In any case, enabling the Script Assist button in the right portion of your Actions panel should make it match Figure 4-4.

    Figure 4-4. The Actions panel, with Script Assist enabled, ready for input

  6. Before you populate your script, remember that you want to go to a URL for the book content, and that you are using a button to get there. In the lefthand menu, scroll to the top, open the Global Functions category with a single click, and then open the Browser/Network subcategory with another single click.

  7. In this latter category, you will find a small collection of related actions. (Can you guess which action you want to work with? Whenever possible, Flash uses intuitively named actions.) Double-click on the getURL action.

  8. You should see that Flash has written much of your script for you. In addition to adding the getURL() command, it has also added two lines of code, beginning with on (release), to contain the command. This is called an event handler, because it "handles" eventsthat is, it reacts to events caused by Flash or the user. In this case, it is a button event handler, and it is designed to react when the user releases the mouse button after clicking on this button symbol instance. See the "Event Handlers" sidebar for more information.

  9. All you have to do now is let Script Assist help you configure the unfinished getURL() action. If the getURL line in the script you are writing isn't still selected, select it now. The reserved area above the script will display some text input boxes and menus. In the URL text field, type http://www.flash8outofthebox.com. In the Window text field, type _blank. Don't worry about the other settings, as they are optional.

  10. Notice down below that the script has been completed by the Script Assist mode. You may prefer to type this syntax from memory when you become more comfortable with ActionScript. Your script should now look like Figure 4-5.

    Figure 4-5. Completing the getURL() method with Script Assist

  11. Save your work. For optimal results when testing, publish your movie using File Publish Preview Default - (HTML). This will display your SWF within an HTML page, so that you dont have to worry about your Flash authoring environment knowing how to talk to your browser.

4.2.2. Hand-Coding

Script Assist can be helpful when you're just starting out, or when you need a quick syntax clarification. However, as you become more familiar with ActionScript, you'll likely find yourself wanting to have more intimate control over your code, and wanting to take fewer steps when writing your scripts.

In the previous project, you used Script Assist to apply an instruction directly to a button. However, code can be more efficient and productivity can be improved if you consolidate your ActionScript in as few locations as possible. One way of doing this is to place much of your code in frame scripts but refer to, or target, a desired button when writing code for that button.

To do this, you must give a unique name to each button instance that you intend to script in this fashion. Try to use this approach to add a script to the remaining button in your animation. Make the left arrow go back to frame 1 and play the animation again:

  1. Single-click on the button that looks like a left-facing arrow to select it. In the Properties panel, locate the <instance name> field in the lowerleft corner, and type replay_btn to name the button.

  2. Next, select the last frame in the actions layer, where you previously placed your stop() script.

    Event Handlers

    A typical Flash experience may include a variety of events that cause other actions to occur. Some of these events may be passive, such as when the playhead enters a frame. Others may be interactive, because they are created by a user activity of some kind, such as pressing a mouse button or key.

    When these events occur, they will go unnoticed unless a script is in place to react to, or "handle," them. For example, you could click your mouse forever on a button with no script attached, and no interaction would result. Events would certainly be occurringthe mouse would be pressed and released, for instancebut unless one or more event handlers were in place to trap those events, your movie would not respond and your scripts would not be executed.

    Different kinds of scriptable Flash elements can be instructed to react to different kinds of events. For example, a particular set of event handlers is most commonly used to handle button events such as mouse press and mouse release. Although they can be triggered again and again by the user, these are typically thought of as single events. Another set of event handlers is used to trap movie clip events, such as when the playhead enters the frame or when data is loaded into the movie clip.

    There are also a few ways to write event handlers, depending on how and where they are used. A very basic way to write an event handler is when the script is applied directly to the asset in question. For example, consider a button that is designed to stop playback when the user clicks on the button and releases his or her mouse. If that script is applied directly to the button, the event handler will read this way:

     on (release) {     stop(); 

    The above format is useful in that it is very direct, but it can also make your code more difficult to follow, edit, debug, and reuse, because your scripts are scattered across many symbols in many places.

    The preferred way of addressing this is to consolidate your scripts into fewer locations, such as a few necessary frame scripts, and assign each script to a button's instance name. If the same button above, with an instance name of stop_btn, had the same script applied using this method, it would read:

     stop_btn.onRelease = function(){   stop(); }; 

    This syntax is a bit different from the first example, in that you are setting the event handler equal to something called a function. A function is nothing more than a way of writing a part of your script so that the instructions you include therein are executed only when the function is called. In this case, the button is calling the function, but you can call functions yourself, too. This prevents Flash from acting on these instructions automatically, as the stop() action you used in your first frame script in Chapter 3 did.

    Writing scripts this way is considered an optimal way of coding, or "best practice," but don't be concerned if it seems confusing. You'll learn more about writing functions later; the most important thing at this point is your growing confidence. Just be comfortable with the fact that, in both forms of this script, the event handler is trapping the mouse release event, and reacting by executing the instructions within that handler.


  3. Use its instance name, and an event handler, to add a script to this button. If Script Assist is still on, turn it off and practice writing the script yourself. Use the same event handler as you did with the Web button to trap the mouse release event:

     replay_btn.onRelease = function() { }; 

  4. When you type the dot after replay_btn, a code hint appears. These are context-sensitive options that Flash will auto-complete for you, if desired. Instead of typing the needed phrase in its entirety, you can choose onRelease from the code hint menu. See the "Code Hints" sidebar for more information.

  5. Add a method that will tell Flash to send the playhead to a certain point and then begin playing. Type gotoAndPlay and the first of the two parentheses typically required by methods (as discussed in the last chapter):

     replay_btn.onRelease = function() {     gotoAndPlay( }; 

    Notice that as soon as you type the opening parenthesis after gotoAndPlay, another code hint appears. This code hint initially informs you that you must enter a frame as the needed parameter. If you click on the right arrow, it then tells you that an optional scene can be included. A scene is a way of splitting long timelines into more manageable chunks, like stringing together multiple smaller timelines. Scenes are discussed later.

    Code Hints

    You may have noticed that when you type _btn followed by a dot (period) into the Script pane of the Actions panel, a drop-down list appears. This feature is called code hinting. Flash recognizes the _btn suffix as indicating a button instance and therefore prompts you with a handy list of button-related methods, commands, and properties.

    Although entering much of the ActionScript syntax will eventually become second nature, this is a wonderful feature if you're just starting out. It can be difficult to memorize proper syntax for every keyword, and code hinting can help you recall things like case sensitivity, required parameters, and even the correct pairing of keywords and objects.

    When prompted with the code hint, you can scroll through the drop-down list with the arrow keys to locate the item you need. You can even start typing, if you know the first letter or two, to jump directly to the nearest item in the list. Once you've found what you're looking for, press Enter/Return to add the item to the script automatically.

    Other suffixes, such as _mc for movie clip, will prompt code hints as well. The examples in this book will usually include these suffixes to get you started.

    In ActionScript 2.0, you can specify the type of an object without using a specific suffix. You'll learn more about this later, but as a short example, you can declare a variable that refers to a movie clip instance as follows:

     var myClip:MovieClip; 

    The var keyword and the :MovieClip data type tell ActionScript that myClip is a movie clip instance, thus providing code hints without requiring the _mc suffix.


    The two things the code hint asks for are called parameters. Together, they give the Flash Player the information needed to execute the method you are using. In this case, a simple play() command would also work, because Flash loops automatically and you want to go back to the first frame. However, in addition to briefly demonstrating parameters, it's good to know about this option because it will let you jump to a frame other than frame 1 and begin playing. For example, if you use frame 14 as the parameter for your gotoAndPlay() method, you can replay your animation from the point at which the boxes are in their final locations and the text begins to appear.

  6. Finish the script to launch the desired URL when the user clicks the button. Type 1 (or 14, if you like), close the parentheses, and add a closing semicolon for good form. (If you haven't already, read the "Semicolon;" sidebar in Chapter 3.)

     replay_btn.onRelease = function() {     gotoAndPlay(1); } 

  7. Save your work and test your file. In addition to the globe button launching this book's web site, the left-arrow button will now replay the animation (either from the first frame, as in the example file, or from the point at which the text begins to animate, if you used frame 14 in your script).



Flash 8(c) Projects for Learning Animation and Interactivity
Flash 8: Projects for Learning Animation and Interactivity (OReilly Digital Studio)
ISBN: 0596102232
EAN: 2147483647
Year: 2006
Pages: 117

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net