Making Buttons Work in Flash CS3 (ActionScript 3.0)

Flash ActionScript 3.0

At the time of this writing, Flash CS3 is still brand spankin’ new on the shelves.  For some lucky folks, whose companies presumably have volume discounts with Adobe, the latest version of Flash is already in their hands — has, in fact, already been installed without any fanfare or training.  Some of these designer/developers are finding, quite suddenly, that button symbols no longer seem to work in Flash CS3 (I’ve seen quite a few panic posts already on the Adobe forums).  What gives?  Is Flash broken?  Not a bit of it!  :)   Let’s see what’s going on. 

ActionScript 3.0 is a new language

The truth of the matter is, ActionScript 3.0 is different, in many respects, from AS2 or 1.  (As it happens, it’s also the same in many respects, which can be a source of frustration for experienced users, but chin up!)  One of the most basic, familiar things people do in Flash is to assign some ActionScript to a button.  In former versions of ActionScript, this could be done in a number of ways, as explained a bit in “Museum Pieces:  on() and onClipEvent().”  In AS3, the rules have changed.  There were at least four ways to handle events in the past — on() and onClipEvent(), dot notation, addListener(), and addEventListener() — and AS3 mercifully reduces those four down to one consistent approach.  Honestly, this makes it easier.

Here’s how it goes.  Let’s say you have a button symbol on the Stage.  Select it, give it an instance name in the Property inspector.  Now that it has an instance name, it has become accessible to ActionScript, which now has a unique way of identifying it from any other objects present.  In a keyframe script (select a keyframe in line with the button, preferably a keyframe on its own layer), type the following:

myButton.addEventListener(
  MouseEvent.MOUSE_UP,
  function(evt:MouseEvent):void {
    trace("I've been clicked!");
  }
);

And that’s it.  Why not select the button itself?  What’s wrong with good old on()?  For better or worse, direct attachment of code is a thing of the past.  ActionScript 3.0 simply doesn’t support it.  In fact, you’ll notice that the Behaviors panel is dimmed when a FLA’s Publish Settings are configured for AS3.  Why?  Because Behaviors rely on on() or onClipEvent().  Change your Publish Settings to AS2 or 1, they come back.

In the above short sample code, myButton represents whatever instance name you chose for your button symbol.  If you actually used myButton, you’re good; otherwise, change the above code to match what you chose.

The classes that define button and movie clip symbols both inherit much of their functionality from a class called EventDispatcher, which provides that addEventListener() method.  This method is what “wires up” such objects to respond to events, such as a “mouse up” occurrence, where the user has clicked, then released, the mouse.  There are two required parameters (more, if you’re interested — see the EventDispatcher class entry for details), and they are this:  a) what event to listen for, and b) what function to perform when the event occurs.

In this case, we’re listening for MouseEvent.MOUSE_UP.  To see what other events are available, look up the MouseEvent class (or the Event class itself, which has many inheritors of its base functionality).  The function inside any event handler is going to receive an object of its own (here, a MouseEvent object) that gets passed in as a parameter.  In the above sample, that parameter is the arbitrarily named evt (for “event”), and that object contains a number of useful properties, including, for example, target, which refers back to the object that dispatched it.

Change that trace() statement from "I've been clicked!" to this, for example:

trace(evt.target);

… and you’ll see a reference to the button itself.  The SimpleButton class defines button symbols in AS3, so look up that class to see what further properties are available.  You could trace the button’s instance name, for example, by using this expression:

trace(evt.target.name);

… which makes sense if you consider what the expression means.  Again, when the user clicked the button and released, a MouseEvent.MOUSE_UP event was dispatched.  When that occurred, that dispatch included a MouseEvent instance as carry-on luggage.  Because of our event handler, a function received that instance (and its luggage) by way of an evt parameter.  That evt parameter is the incoming MouseEvent instance, and according to the MouseEvent documentation — make sure to click the “Show Inherited Public Properties” hyperlink under the Public Properties heading — MouseEvent instances have a target property, which points to the object that dispatched the event.  Because that object was a button symbol (an instance of the SimpleButton class), we know that any reference to it has a name property.

This differs from the way such event handling was done in AS2.  For button symbols, it went like this:

myButton.onRelease = function():Void {
  trace("I've been clicked!");
}

Notice the lack of an incoming parameter.  To refer to the button itself, from inside that function, you could use the global this property:

myButton.onRelease = function():Void {
  trace(this._name);
}

In ActionScript 2.0, the property that points to a button’s instance name is _name (with an underscore).  Same principle, different approach.

Enjoy ’em both

If the new approach flies over your head, just go to File > Publish Settings, select the Flash tab, and change the version of ActionScript back to AS2 or 1.  But I encourage you to at least take a few stabs at the new way.  As the months go by, you’re going to see plenty of AS3 stuff on the horizon.  Fortunately, Flash CS lets you take your pick of the language desired.

161 Responses to “Making Buttons Work in Flash CS3 (ActionScript 3.0)”

  1. Tim Says:

    Thanks for the insights… they have really helped me!

  2. David Stiller Says:

    Tim,

    Glad to hear that. :)

  3. peter souza Says:

    i have an invisible button, on the up state i have a picture over the invisible button,

    on the over state i have the original picture morph by use of a shape tween into another picture (the morphs are seperate tweens with frame labels)

    on the rollout state i have the morphed picture morph back into the priginal

    and on the mouse up state the fla advances to the next frame.

    now,

    im using a seperate addeventlistener for each function here and seperatly they work fine but when i put them all together there is some conflict, no offical errors but it definitly doesnt work properly.

    how can i apply all these listeners to the invisible button

    if you wanna see the code ill send it to u

  4. David Stiller Says:

    peter,

    I’m already lost, I’m afraid, while reading your first sentence. You have an invisible button, and the Up state of this button has a picture “over the invisible button” … just not sure what that means. Generally speaking, invisible buttons in Flash are button symbols that only have artwork on the Hit frame, in order to make the button clickable — they don’t have artwork on any of the other frames (Up, Over, or Down), because that would mean the artwork would show, and the button would therefore not be invisible.

    You might be talking about a movie clip symbol (something separate) that is instructed to animate based on button event handlers. If that’s it, then yes, it would probably help to see your code. Wrap it in <code> HTML tags and it should show up right here in the comments. :)

  5. peter souza Says:

    button1.addEventListener
    (MouseEvent.MOUSE_OVER,
    function(MouseEvent)
    {(gotoAndPlay(”over”,”Scene 3″))});

    button1.addEventListener
    (MouseEvent.MOUSE_OUT,
    function(MouseEvent)
    {(gotoAndPlay(”out”,”Scene 3″))});

    button1.addEventListener
    (MouseEvent.MOUSE_UP,
    function(MouseEvent)
    {(gotoAndStop(2))});

    ‘button 1′ is the invisible button (with only a hit frame)

    ‘over’ and ‘out’ are the 2 seperate shape tweens

    those 3 work seperatly, but if i have all 3 in the actions then it doesnt work

  6. David Stiller Says:

    peter,

    In the MOUSE_OVER event handler, you’re sending the main timeline to a frame labeled “over” in Scene 3, which is presumably a completely different scene (i.e., a different timeline) from the current one. Maybe not, though. That potentially uproots everything — at least, it does in AS2. Instead of sending the playhead all over the main timeline, I would suggest you put your shape tweens into a movie clip symbol, then use the button to direct the timeline of that symbol. Give the movie clip an instance name and invoke MovieClip.gotoAndPlay() on that, instead. Does that make sense?

  7. peter souza Says:

    finally, what one book would you recommend being the best -how to- actionscript book out right now.thanks

  8. Tomek Says:

    Hi, I’m trying to figure out how to create clickable button in Flash CS3 and AS3 which will open an URL. In older version of flash I used getURL() but I don’t know how to do that now. Can you please help me? thx

  9. David Stiller Says:

    To peter …

    Colin Moock’s Essential ActionScript 3.0 is likely to give you the most bang for your buck. It’s nearly 1,000 pages, and Colin’s writing is among the best out there.

    To Tomek …

    Sure thing. getURL(), as you’ve seen, is no longer available in ActionScript 3.0. The replacement is navigateToURL(), which requires an instance of the URLRequest class instead of just a string, like getURL() did:

    myButton.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        navigateToURL(new URLRequest("http://www.domain.com/"), "_blank");
      }
    );

    The second parameter ("_blank") is optional, just as it is in AS2, and behaves the same way.

  10. David W Says:

    I have the code exactly as you said in the tutorial, but it doesn’t seem to be working. it keeps giving me an error when i publish it saying:
    “1120: Access of undefined property btn_hbw”

  11. David W Says:

    to add, btn_hbw is the instance name of my button

  12. David Stiller Says:

    David W,

    Well … that’s pretty baffling, I agree. If btn_hbw truly is the instance name — and I don’t doubt you that it is — then something must be awry. Have you been able to duplicate this error message in another FLA — I mean a totally simplified one … just a button with an event handler that traces a message?

  13. NickTheNameless Says:

    thanks for this post. if you get the urge, i would be first in line to read any other tutorials you write… i like you style.

    thanks for the book recommendation as well, i’m ordering it today.

  14. David Stiller Says:

    Nick,

    Sure thing! :) As of today (Oct 19, 2007), most of this blog centers on ActionScript 2.0, but I’m certainly well versed in AS3 and have begun writing blog entries on the new language too.

    Thanks for ordering the book! I had a blast writing it and hope you enjoy it. It recently went for a second print run, which corrected a handful of errors. Of course, copies of the first print are likely still in stores, so make sure to visit FoundationFlashCS3.com to check out the Corrections page.

  15. Dave Puente Says:

    Hey David,

    i am trying to get my main movie (root) to stop by using a simple button. and also, i would like to have other movies stop as well, with a simple action script like before… i am attempting to use AS3.0 now, because i am tryin to use a component that requires 3.0.

    can you give me some example script to help me, please. here’s what i currently have:

    skipIntro.addEventListener(
    MouseEvent.MOUSE_UP,
    function(evt:MouseEvent):void {
    _root.gotoAndStop(157);
    }
    );

    thanks and cheers!

  16. David Stiller Says:

    Dave,

    In ActionScript 3.0, there is no global _root property, and the Compiler Error panel will give you a warning of that when you try to publish an AS3 SWF with _root in it. There are a number of approaches you can take, but here’s one nudge that may give you somethin’ to chew on. :) See that evt parameter in your event handler function? That variable represents an instance of the MouseEvent class, which is the object that actually gets dispatched as the user lifts the mouse. Check out the MouseEvent class in the ActionScript 3.0 Language Reference, look up the Public Properties heading, and click the “Show Inherited Public Properties” hyperlink. That will open up additional properties from MouseEvent’s family tree. (Properties are the characteristics a given object has; methods are the things that object can do; events are things that object can react to.)

    One of those properties is named target, which gives you a reference to the object that raised the event. This is a button symbol, so you’re dealing (in AS3, anyway) with an instance of the SimpleButton class. Go to the SimpleButton class and look at its Public Properties heading, making sure to show the inherited stuff. You’ll find a parent property that refers to the timeline that contains the button in question (this is the equivalent to the MovieClip._parent or Button._parent properties in ActionScript 2.0). If this button is sitting in the main timeline, then the following expression gives you a reference to the main timeline, by way of those properties:

    skipIntro.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        trace(evt.target.parent);
      }
    );
  17. Attila Danka Says:

    this blog is very good!

    thanks

  18. Dave Puente Says:

    Thanks for your response sir!

    this is the simplest question ever, probably. how do i simply make the timeline stop? what is the code to do that? thanks!

  19. David Stiller Says:

    To Attila …

    Thanks!

    To Dave …

    To stop a timeline, you invoke the MovieClip.stop() method. See, even the main timeline is an instance of the MovieClip class (provided it has a timeline; otherwise, in AS3, it might just be a Sprite or DisplayObject).

    Start with this:

    skipIntro.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        stop();
      }
    );

    … and experiment with your incoming evt object to explore other avenues. Use the trace() function to help determine where you are, in terms of objects and timelines.

  20. Dave Puente Says:

    What is the name of the timeline? can i name it in AS 3.0? in flash? i’m so new to AS 3.0. it’s a bit like chinese to me right now. thanks for your quick responses, David.

  21. Dave Puente Says:

    My question is how do i talk to the MAIN movie? or do i have to put everything in one movieclip now in AS 3.0? and then name it?

  22. David Stiller Says:

    Dave,

    The timeline doesn’t have an instance name — not in any version of ActionScript — but all you need is a reference to it. You may treat the main timeline as a MovieClip instance, which is why you could use _root.gotoAndPlay(15) in AS2. Have you started simply with stop() so far? Did that work for you? Have you tacked stop() on the end of the expression evt.target.parent? Did that work for you?

    Toy around with it a bit. :) I’m showing you more than one approach so you can personally evaluate which one seems easier to you — but it’s important you understand both. I don’t know how deeply nested your skipIntro button is. The very simplest approach, from a “how much do I need to code” standpoint, may just be the “start with this” sample I showed you.

  23. Dave Puente Says:

    Hey David,

    thanks for your time in responding to me. i tried the good ol “stop();” script, but AS 3.0 doesn’t respond to that. i just want to make the main movie stop at frame 157 and make the “skip intro” button work as well. i can’t use “_root”, as you’ve stated previously… i was wondering if i could send you the FLA file to show you what i am trying to do. it’ such a simple function, i’m sorry if i seem dense or slow… but i purchased a component that only works in AS 3.0 and would really like to use it for a website i’m working on. thanks and cheers!

  24. David Stiller Says:

    Dave,

    I’m going to encourage you to keep trudging through this one, because when you do nail it, the solution is going to mean more to you than a quick answer from me (or from anyone). If the stop() method doesn’t stop the main timeline, then something about your event handler — the function you’ve associated with MouseEvent.MOUSE_UP — doesn’t “see” the main timeline from where it is. I promise you, the MovieClip.stop() method does indeed halt the main timeline, and you don’t have to put everything in one movie clip nowadays.

    You haven’t stated where you ActionScript is located, and it really doesn’t matter, so long as you understand how to find a reference to the timeline you wish to stop (which just happens to be the main timeline). Your next few steps are to trace() out the value of evt and its various properties. Start with this:

    skipIntro.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        trace(evt);
      }
    );

    … then this …

    skipIntro.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        trace(evt.target);
      }
    );

    … then this …

    skipIntro.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        trace(evt.target.parent);
      }
    );

    and make note of the result you get each time in the Output panel. Compare that against the instance names you’ve given your button, and possibly whatever nested movie clips might contain that button, each of which (if there are any) will also need its own instance name. You may even need to keep tacking on additional parent references, but eventually you’ll find the main timeline. Whatever expression gets you there, tack stop() on the end of that.

  25. Randy Miller Says:

    I am having the same problem as David W. on Sept 19th’s entry. I get the same error code. And that is on a stripped and basic FLA with only a single button on the stage called: “myButton”

    This is the error code:
    1120: Access of undefined property myButton.

    This is the AS3

    myButton.addEventListener(MouseEvent.CLICK, myButtonFunction);
    function myButtonFunction(event: MouseEvent) {
    var request:URLRequest = new URLRequest(”http://flashgameu.com”);
    navigateToURL(request);
    }

    I am at a loss. Nothing works.

  26. David Stiller Says:

    Randy,

    I’m still waiting to hear back from David W., so I’m not sure if he managed to resolve his issue on his own.

    The key here is what you mean by “a single button … called ‘myButton’,” because it’s not enough that the Library’s symbol name is “myButton”: one particular instance of that symbol, on the Stage, must have the instance name “myButton”, as configured in the Property inspector; otherwise ActionScript has no idea which object you’re talking about.

    Could it be that you’ve given this button the correct instance name but accidentally added a space character at the end (“myButton ”)?

  27. Paul de Quaasteniet Says:

    Hi - I’m having the same issues as Randy and David W. with the error code 1120: Access of undefined property mybutton. Have played around with it for a long time now with zero success. :-(

  28. Paul de Quaasteniet Says:

    Hi David - Have resolved my issue…I had named the instance of the button “mybutton” and referred to the instance in the actionscript as “myButton”….didn’t realise it was case sensitive. Have made really good progress on my design now, thanks for your blog - useful and very easy to understand.

  29. David Stiller Says:

    Paul,

    Ah, glad to hear it! Yeah, ActionScript has effectively been case sensitive since Flash Player 7. In fact, I wonder now whether Randy and David W. encountered the same issue? I didn’t occur to me to think of that angle. Thanks for bringing it up!

  30. casey g Says:

    hi David, I am just trying to figure out what I can do to make my movie got frame 2 and stop using a simple play button. The play buttons name instance name is “mcClick” I have created a movie clip name zoomin1 here is the code I placed in frame 1’s actions layer.

    stop();

    mcClick.addEventListener(
    MouseEvent.MOUSE_DOWN,
    function(evt:MouseEvent):void {
    evt.target.parent.play(2);
    }
    );

    for some reason it automatically jumps to frame 2 and it bugs out. How should I write it for this to work?

  31. David Stiller Says:

    casey,

    You’re very close! The MovieClip.play() method doesn’t accept any parameters, but MovieClip.gotoAndPlay() does! Keep in mind that you may not need the evt.target.parent prefix (but it’s good to understand the various ways to reference timelines).

  32. John Says:

    I’m completely new to Flah and Actionscript. A question for ActionScript 3.0.

    All I want is to create a simple button. Can you tell me what’s wrong?

    stop();
    function clickSubmit(event:MouseEvent):void {
    evt.target.parent.gotoAndPlay(”Layer 1″,”Scene 3″)
    }
    stopBoarder.addEventListener(MouseEvent.CLICK, clickSubmit);

    stopBoarder is the button’s instance name. I want it so that it goes to Layer 1 and Scene 3 when clicked. Also, do I have to include “Layer 1″, so that I just want a whole scene to play?

  33. John Says:

    Another question, how do I give an instance name to a MovieClip? Or a section/part of it?

  34. David Stiller Says:

    John,

    In ActionScript 2.0, it wasn’t possible to include a Scene name as one of the MovieClip.gotoAndPlay() parameters — that would have required the older gotoAndPlay() global function — but in AS3, sure enough, that optional parameter is back; only now, it’s in the second slot, just as you’ve used it. So, sending the movie to Scene 3 makes sense (assuming the name of that scene is “Scene 3″), but that “Layer 1″ part is only going to work if you’ve added a frame label to one of your layers (in Scene 3) by the name of “Layer 1.” I’m wondering if your first parameter is a layer name, rather than a frame label?

    As it turns out, timeline layers are nothing more than an author-time convenience. In the published SWF, those layers are automatically converted to a sophisticated system of depths, so there really isn’t a way to send the playhead to a particular layer. What the playhead gets sent to is a particular frame, referenced either by number (the default) or by frame label. Think of any given frame as a vertical column that visually displays the content of all layers in that column.

    To add a frame label, you’ll have to put a keyframe into a chosen frame, then use the Property inspector to name that keyframe. I usually use a dedicated labels layer just for that purpose, so they’re all in the same place.

    [Added later …]

    Woops! I forgot to answer your other question, John. Sorry about that! To give a movie clip an instance name, just select it on the Stage and look at the Property inspector. You’ll see the place to do what you’re after in the upper left corner of that panel.

  35. casey g Says:

    Thanks David I will try this once I am at home. I’ve just bought the CS3 package, and this flash is a totally different AS language. I wasn’t too good with AS to begin with so I’m sure you can understand my frustrations….I just miss placing the AS right on the object.. boo hoo hoo..lol. ok, I’ll quit whining and start reading more. Thanks David.

  36. David Stiller Says:

    casey,

    Aw, chin up! :) Things are different, for sure. But keep in mind, you can keep right on using ActionScript 2.0 (and even earlier versions) right in Flash CS3 — it all depends on the Publish Settings for that particular FLA. Take small bites of AS3 and learn as you go.

  37. casey g Says:

    so, I tried this as a new code to get my movie to work but it still told me

    “TypeError: Error #1006: gotoAndplay is not a function.
    at MethodInfo-1()”

    stop();

    mcClick.addEventListener(
    MouseEvent.MOUSE_DOWN,
    function(evt:MouseEvent):void {
    evt.target.parent.gotoAndplay(2);
    }
    );

    what am I doing wrong?? Also, can you answer what the “void” part of this script means?

  38. David Stiller Says:

    casey,

    Since Flash Player 7, ActionScript has effectively been case sensitive, so it’s important to match up your lower- and uppercase letters exactly. The AS3 compiler is the strictest yet, and gotoAndplay() truly isn’t a function (unless you write it!) — you’ll want gotoAndPlay() (capital A and P). ;)

    The :void tells what sort of value this function returns, which happens to be nothing (this function returns no value). Some functions and methods do return values, such as Math.round(), which rounds numbers to the nearest integer. You feed it 4.5, for example, and it feeds you back 5, which makes that return value a number. The Sound.play() method, as another example, returns a SoundChannel instance. In your event handler, the function doesn’t return anything, so the :void suffix means just that: nothing.

  39. casey g Says:

    great, thanks again, I did get this to work but in a different approach after much reading through the help manual. here is what I came up with that worked properly:

    stop();

    function startMovie(event:MouseEvent):void
    {
    this.play();
    }

    mcClick.addEventListener(MouseEvent.CLICK, startMovie);

  40. casey g Says:

    I tried the fix you suggested….it amazes me how one wrong letter can screw stuff up like that. It worked with the capital P just as you said. Awesome blogs david, very very helpful. just for others, here is the final code that allowed me to jump to frame 2.

    stop();

    mcClick.addEventListener(
    MouseEvent.MOUSE_DOWN,
    function(evt:MouseEvent):void {
    evt.target.parent.gotoAndPlay(2);
    }
    );

  41. David Stiller Says:

    casey,

    Good on ya! :) Reading the docs is definitely a good way to go. Seriously, I read the ActionScript 2.0 and 3.0 Language Reference daily. The really helpful thing is, both references are closely organized around that classes that comprise each version of the language. If you’re dealing with a movie clip, look up the MovieClip class; if you’re dealing with a text field, look up the TextField class, and so on. Each class entry will have one or more of (at least) these three categories: properties (characteristics), methods (things the object can do), and events (things the object can react to).

  42. casey g Says:

    Hey David, I found this blog very helpful, I just purchased your book “foundation Flash CS3″ I appreciate the tips on here and look forward to reading the book. I am currently using flash to work on a cartoon idea. It’s in its beginnning stages, but I will need this book to help me work through the animation ideas. If you have any extra tips or solutions that apply to cartoon animation, please let me know, feel free to shoot me an e-mail.

  43. David Stiller Says:

    casey,

    Hey, thanks so much! As it turns out, I know just the Flash animation book to recommend! A good friend of mine, Chris Georgenes, recently wrote How to Cheat in Adobe Flash CS3 (Focal Press), which covers a boat load of cartooning- and animation-specific workflows, tips, and tricks. (I happened to write the interactivity chapter for it, so I got to see Chris pour out and assemble his best stuff from scratch.) Chris’s convention sessions (Flashforward and the like) tend to be standing room only, and he managed to essentially put to paper the magic he does in person.

  44. casey g Says:

    David I have already began to play around with some of your actionscript 3 examples..learning quickly. I worked on the star and moon tutorial, and I toyed with it until I could make the star a regular cursor without clicking it as a button. Then I used the mouseMoveHandler function to do the alpha trick. It worked great, here is the code I used:

    star.addEventListener(Event.ENTER_FRAME, customCursor);

    function customCursor(Event)

    {

    Mouse.hide();

    star.x = mouseX;
    star.y = mouseY;

    }

    star.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

    function mouseMoveHandler(evt:Object):void{
    if (star.x>moon.x){
    star.alpha = .2;
    }
    else{
    star.alpha = 1;}
    }

    I plan on reading the rest of the book and using some concepts on my companies site. I am slowly but surely conquering my actionscript 3 frustrations.

  45. David Stiller Says:

    casey,

    Glad to hear that! To me, using Flash is one of the funnest things I can do with my time — I’m just glad I’ve been able to make a career out of it! ;)

    Looking over your code real quick, I can see an easier way to hide the mouse cursor, and I’m hoping my explanation will give you a bit more insight into event handling. Your custom function, customCursor(), accepts the obligatory parameter expected by all AS3 event handlers. Even though you’re not making use of it in this context — which is fine with customCursor(); you don’t need it — it’s a good idea to adhere to a particular syntx of paramName:paramType, the way you’re using in the mouseMoveHandler() function. Sometimes, that incoming parameter (here, evt) is something you can actually make use of. It carries with it various data about the object that dispatched the event, so when that time comes — and there are examples later in the book — you’ll use that parameter by name (evt) in order to access its properties.

    In the mouseMoveHandler() function, evt’s type is more accurately MouseEvent, thought Object certainly isn’t incorrect. In your customCursor() function, you can re-use the same parameter name if you like, and set its type to Event:

    evt:Event

    Now, one more thing to think about it (this is what I mentioned earlier about a simpler approach) … the Event.ENTER_FRAME event handler executes its associated function every time the playhead ticks along the timeline (and even when it’s standing still). By default, Flash runs at 12fps, which means you’re executing customCursor() function approximately once every 83 milliseconds. As it turns out, you only need to execute the Mouse.hide() portion once, so you can move that one line outside the function. In addition to that, your mouseMoveHandler already executes when the mouse moves, so you should be able to stuff the next to lines into your other event handler. Check it out:

    Mouse.hide();
    
    star.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
    
    function mouseMoveHandler(evt:MouseEvent):void{
      star.x = mouseX;
      star.y = mouseY;
      if (star.x > moon.x) {
        star.alpha = .2;
      } else{
        star.alpha = 1;
      }
    }

    It sounds like you’re really having fun with this, which I always love to hear.

  46. Richard W Says:

    Hi David,

    Firstly, cool blog!

    Secondly, I’ved created a map of the UK (for a franchise company) with buttons and links to different pages:

    http://www.isleofwight.com/mapdemo/

    I need to create a 2nd map that pops-up a map of London when you roll-over the London area, and then allows the user to click on the area they want - as per the main map.

    I’ve tried importing a new movie, and creating a button within a button - and am not really getting anywhere.

    Before I give up and go back to the day job (php developer), have you any sample code on how best to proceed please?

    Many thanks, Richard

  47. David Stiller Says:

    Richard,

    Ah, that’s a more complex beast than a quick example of how event handling works in AS3. ;) I would probably avoid buttons within buttons and stick to movie clips instead — they share all the import mouse-related events, after all — plus, you can control the timelines of movie clips, which you might use for animation on those pop-ups.

    What you’re describing is pretty much the sort of consultation I do for a living. I would certainly be cool with writing a tutorial on it, but it would definitely take an article or two of its own.

  48. rick Says:

    addEventListener is really awesome for creating buttons from just about anything in flash, i.e. txt, iamges, swf etc

    But I’ve been unable to turn an flv playing video into a button. The video plays fine, and I can attach the addEventListener script to the flvstream,

    flvsteam0.addEventListener(MouseEvent.ROLL_OVER etc

    but it doesn’t do anything - I’m still searching the net for someone that’s done this, but not having much luck, I was hopeing to get rid of all my “invisible buttons” alpha=0, that I had to use in AS3

    - any ideas anyone

  49. David Stiller Says:

    rick,

    The reason Video objects don’t respond to MouseEvent events is because none of those appear in the Video class’s event summary, even if you click the Show Inherited Events hyperlink in the ActionScript 3.0 Language Reference. In order to get those, you could simply select your video and convert it to a movie clip symbol — making sure to give both the video and your movie clip their own instance names. Best of both worlds!

  50. Tim Says:

    Thanks David, you’re a life saver.

  51. rick Says:

    Hi, thanks for the fast reply, I understand what you say, however, it seems impractical to convert all my videos to movie clip symbols,

    I’m using progressive download and and don’t know (until I decide) which flv video I want to watch, when clicked I can edit video attributes - e.g. size, alpha, rotation etc by pressing a letter e.g. s,m,r and just moving the mouse.

    I guess for flvs I have to go back to what worked before - invisible placeholders (buttons)

  52. rick Says:

    thanks learned to use the help better. From the help

    Unlike other ActionScript 3.0 components, the FLVPlayback component does not extend UIComponent; therefore, it does not support the methods and properties of that class.

    Cheers for your help

  53. David Stiller Says:

    To Tim …

    Thanks! :)

    To rick,

    Glad I could help somewhat, and wish I could have given you an easier/better answer! Certainly, you’ll be most comfortable going with the approach that works best or makes the most sense to you. If invisible buttons feel like less effort than wrapping Video objects in movie clips, then that’s your ticket. You may want to check out the MouseEvent class to check into monitoring mouse events regardless what object is beneath the mouse.

  54. rick Says:

    Thanks for the great idea Dave!!! I love actionscript 3, but there are so many commands, it’s like you can’t so the woods for the trees, so I end you doing what works, not necessarily the best or easiest way.

    If it’s OK, I have one more question.

    When loading bitmaps I usually use:

    var img:Loader = new Loader();

    then in some function

    some_function()
    {
    var request:URLRequest = new URLRequest(filename);

    img.load(request);
    addChild(img);

    etc

    and that works and it’s ok, but what if I don’t know how many images I may be loading. I could do…

    var img:Loader = new Loader();
    var img1:Loader = new Loader();
    var img2:Loader = new Loader();
    etc

    but there should be a dynamic way of adding loaders when I need them (and killing them when I don’t)

    Thanks for all your help

  55. Lamar Says:

    Dave,
    I’m currently trying to have a button that, once clicked, will lead to Scene 2, but I am having a hard time. Here’s my current code:

    link1.addEventListener(MouseEvent.CLICK, playLink1);

    function playLink1 (e:MouseEvent):void
    {
    gotoAndStop(”main2″,”Scene 2″);
    }

    I named the button link1. I labeled the first frame “main2″ on Scene 2. No luck. Any suggestions? Thanks.

  56. David Stiller Says:

    To rick …

    Well, you could certainly reuse a given Loader instance, but only to display one image at a time (change the Loader.url property to load a new image). You could also use BitmapData to copy the pixels of each loaded image, but generally speaking, it makes most sense to simply instantiate a new Loader object for each new bitmap. I hear ya on the monotony! If you don’t know how many images you’ll need — such as for a dynamic slideshow, say — you could use the array access operator and a for loop:

    var urls:Array = ["a.jpg", "b.gif", "c.png"];
    
    for (var i:int = 0; i < urls.length; i++) {
      this["img" + i] = new Loader();
      this["img" + i].load(new URLRequest(urls[i]));
      addChild(this["img" + i]);
    }

    The array access operator ([]) translates strings into object references. The only trick is that you need a parent object to act as a prefix to the expression (hence, the this). Later on, you could reference img0, img1, etc. and delete them. Does that help a bit?

    To Lamar …

    I set up a quick FLA with exactly your situation, and the button worked fine. Do you really have two Scenes? Is the second one named “Scene 2″?

  57. Lamar Says:

    Dave,
    To create Scene 2, I went “Insert Scene” and i see a “Scene 2.” I then name the first frame “main2″ and put a stop(); at the first frame. Is this correct? I receive this error:

    ArgumentError: Error #2108: Scene Scene 2 was not found.
    at flash.display::MovieClip/gotoAndStop()
    at Untitled_fla::MainTimeline/playLink1()

    Your help is much appreciated. Thanks!

    Lamar

  58. David Stiller Says:

    [Note: Lamar wrote me later to indicate a solution had been found.]

  59. rick Says:

    Thanks so much Dave, you have been so helpful. Just one more challenge for you. I have a fix, but it is not so elegant

    addEventListener is used to detect when something has happened for example timerevent, lodcomplete etc

    So we setup a timer, or a load complete etc
    //
    /////////////////////////////////////////////////////
    //
    tim0:Timer = new Timer(800, 1) // set a timer 800ms, one-shot
    tim0.addEventListener(TimerEvent.TIMER, tevent_0);

    static function tevent_0(event:TimerEvent)
    {
    // do something here
    }
    //
    /////////////////////////////////////////////////////
    //
    no problem with the above code, it just works, the problem at least for me comes when I have multiple timers, all going to the same event complete function e.g.
    //
    /////////////////////////////////////////////////////
    //
    tim0:Timer = new Timer(800, 1) // set a timer 800ms, one-shot
    tim0.addEventListener(TimerEvent.TIMER, tevent_0);

    tim1:Timer = new Timer(800, 1) // set a timer 800ms, one-shot
    tim1.addEventListener(TimerEvent.TIMER, tevent_0);

    static function tevent_0(event:TimerEvent)
    {
    // do something here
    }
    //
    /////////////////////////////////////////////////////
    //
    Now, my challenge is I’d prefer to to find out which timer has caused the timer event - in one event listener function

    at the moment, I just copy the listener tevent_0, a number of times, changing the name to tevent0, tevent1 etc

    It’s ok with 2 timers, but with 32 which is what I am using, it’s annoying - there must be an easier way.

    The same applies for all kinds to listener objects, most, if not all of the examples on the web show you how to handle one listener, but never multiple listeners pointing to the same place, that need to handled almost in the same way, and there doesn’t seem to be any way that a listener function can know exactly who called it

    Best Regards,
    Rick

  60. David Stiller Says:

    Rick,

    It sounds like you’re talking about the Event.target and Event.currentTarget properties in AS3. Have you checked those out? Event subclasses, such as TimerEvent, inherit those properties, and they tell you which object is involved in the handling of the event.

  61. rick Says:

    ok tanks Dave,
    Will have a go, tell you what I figure out

    Also, just messing around generally with timers, I found that timers can be influenced by moving your mouse around your desktop, especially above the close/minimize buttons in windows.

    In addition, my timer tends to lose a second or more over the course of a minutes.

    var timr:Timer;
    timr = new Timer(100, 0);
    timr.addEventListener(TimerEvent.TIMER, player);
    timr.start();

    Is this normal? Or am I doing something wrong???

    By the way, thanks so much for your help, if you’re ever in Tokyo, drop me mail and I7ll take you out for a few beers on me.

    Have a happy chistmas/holidays (choose one) and a great new year!

    Best Regards,
    Rick

  62. Aaron Says:

    I’ve been using flash since flash 8, 9, MX, then I’m working on CS3…I’m trying to make a pop-up menu on the bottom of a page, I initially started it as a button on the OVER state without actionscripting [3.0] it (and once the mouse was over, it would play a 15 frame animation of the menu rolling up), but then I read it’s better not to embed a button in a button (I WAS going to have the button once rolled out have different clickable buttons/menu options on it).

    Anyways, I have the menu as a movie clip, 15 frames long and I used ASC3.0 to gotoandplay that clip when the mouse moves over it, it works fine when I move the mouse over the HIT area and then away, but if I leave the mouse on the HIT area it’ll keep looping, I know I have to write a snippet to specify the stop and how based on mouse position I think, but am looking for some help–I’m trying to figure out how to write the code so when the mouse goes over, it’ll play the POP-UP movie clip animation once and then go to the wait state (a while loop perhaps? but I wouldn’t know how to write and intergrate into what I have) if you will till the user clicks on a menu option but then to reset the animation when they move their mouse away, here’s the code I have currently:

    import flash.events.MouseEvent;

    firstmenutab.addEventListener(MouseEvent.MOUSE_OVER, rolloutClick);
    function rolloutClick(event:MouseEvent):void {
    firstmenutab.gotoAndPlay(1);
    }

    I found this above structure at adobe.com’s flash site.

    Finally, I bought Colin Moock’s book but like you said it’s like 1000 pages, a lot to cover, I did find some usefulness from actionscriptcheatsheet.com which shows what’s new in ASC3.0 and what from ASC2.0 has been removed, if you can point me in the right direction at least what to do to accomplish my mouse issue on the roll-out menu I’m developing, I’d appreciate it David, ty :)

  63. Aaron Says:

    I got it working, I decided to work on the animated rollout later, here’s my working code! ASC3.0 kicks ass:

    firstmenutab.stop();

    firstmenutab.addEventListener(MouseEvent.CLICK, clickHandler);
    firstmenutab.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
    firstmenutab.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);

    firstmenutab.buttonMode = true;

    function clickHandler(evt:Object):void {
    trace(”menu clicked”);
    }
    function mouseOverHandler(evt:Object):void {
    firstmenutab.gotoAndStop(30);
    }
    function mouseOutHandler(evt:Object):void {
    firstmenutab.gotoAndStop(1);
    }

  64. David Stiller Says:

    To Rick …

    It doesn’t surprise me that your timers occasionally lose a bit of time, though that would probably annoy me if I saw it myself (depends on the goal of the application, I’m sure). Flash Player isn’t designed to take priority on a user’s system, and my hunch is that Flash is willing to give up 100% accuracy to keep from bogging down the OS.

    As it happens, I do plan to be in Tokyo for a couple weeks this year! Maybe we’ll meet. :)

    To Aaron …

    Hey, glad you got it! And thanks for the link to the cheat sheets site. Pretty neat PDFs!

  65. Leigh Rochow Says:

    G’day David!

    As an Illustratior in education I purchased the Adobe CS3 suite. I’m completely new to flash’s scripting.

    I was reading over your blog, it really helped me get my buttons working and my next step is to get them to display an image. I’ve aligned the images to frames 5, 10, 15, 20 etc in my main timeline so I’d like the buttons to point to these frames in the timeline.

    I was reading over your extremely helpful conversation with Casey G about gotoAndPlay(). The code Casey used works for me, but the main timeline wont shift to that frame.

    I think my problem is the fact that my buttons are contained within a ScrollPane and my buttons are merged as a movie called “thumbnails_mc”. The code I have does not work if I include it on a base “scene 1″ layer. It only works if I place the code on a layer within thumbnails_mc.

    This leads me to believe that the code I have isn’t pointing towards scene 1 but towards the movie clip?

    Here is what I have in the “thumbnails_mc” movie clip


    portrait_btn.addEventListener(
    MouseEvent.MOUSE_UP,
    function(evt:MouseEvent):void {
    trace("PORTRAIT_BTN CLICK!");
    evt.target.parent.gotoAndPlay(5)
    }
    );

    I receive no errors and the trace works fine. But the main timeline in Scene 1 remains stationary.

    I have stop() in a layer on scene 1. Maybe this is preventing anything changing the current frame?

    Sorry, I’m sure thats confusing to read as a professional. Thank you for any help you can provide!

    :D

  66. Leigh Rochow Says:

    I found something which works for me!

    After smooshing through forums and blogs I finally found a snippet of code which I thought I should try.

    After all it was a heirachical problem. Geeze this scripting stuff has a tough learning curve.

    evt.target.parent.gotoAndPlay(5) evt.target.root.gotoAndPlay(5)

    Thank you for offering such a great blog David!

    I hope my learning helps others! If you see anything wrong with what I’ve done please let me know. I’m a happy camper otherwise :)

  67. Leigh Rochow Says:

    Very sorry to flood the blog but I tested the flash on multiple explorers.

    www.adam.com.au/zeal/illustration.html

    Iexplorer and Firefox both work, but safari on OSX doesn’t seem to run the scrollpane at all..

    Any ideas?

  68. David Stiller Says:

    Leigh,

    haha Don’t worry about the flood! I enjoy the interaction with people, and most of these conversations end up helping others.

    In your first two posts, you discovered a fundamental principle in programming: object references. Objects have a hierarchy in Flash, very much like the files on your hard drive — they’re stored inside folders, which can be nested inside each other.

    You could stick your head out the window and shout, “David!” but since I’m in the US and you’re in Australia, I wouldn’t hear you. You might have a neighbor named David, in which case he might respond — but that wouldn’t be right either (assuming you really did mean me). You would have to correctly reference the “object” that represents me, which from your point of view is in the US, then Virginia, then Virginia Beach, then my street, my house, my office, and finally me.

    In this expression …

    evt.target.root.gotoAndPlay(5)

    … you’re referencing the DisplayObject.root property of the object that raised the event you’re handling (that’s the button, as referenced by the expression evt.target). In this context, root points to the display list for the whole SWF, whose hightest level is the main timeline. Since the main timeline is an instance of MovieClip, you have access to MovieClip methods, such as gotoAndPlay() (though you might want to try gotoAndStop()).

    As for the Safari issue … that’s interesting. The scrollpane you’re using is definitely the AS3 version. Has your Flash Player plugin for Safari been updated to version 9? Flash Player 9 is the first version capable of interpreting ActionScript 3.0.

  69. Leigh Rochow Says:

    Thank you for your response, I love your writing style, your first few words cleared things up for me and the rest just added clarity!

    I took a stab and changed parent to root. I wanted to change the frame number in the stages timeline. Luckily it worked, otherwise I’m sure I would have produced yet another trail and error compile error.

    Can I ask a question for future reference and maybe of interest to other readers?

    Say I have 2 container objects, MovieA and MovieB. I now know how to reference the root timeline, but how would I referense from object A to object B?

    Inside MovieA would I include something like the following code?

    evt.target.MovieB.gotoAndPlay(5)

    Also, how would I reference something deeper in hierarchy? I’m sorry for the fundamental question.

    Thank you for your response. I’m considering entirely redoing my webpage in flash, which is extremely daunting but i’m sure i’ll learn a mountain in the process. Once again, thank you for such a wonderful resource! You’ve helped me take a positive first step into AC3.

    P.S. Yes, the mac later had a popup alerting me to update flash. Woops!

  70. David Stiller Says:

    Leigh,

    Thank you for your response, I love your writing style, your first few words cleared things up for me and the rest just added clarity!

    Sweet! Well, if it’s worth your while, you might find some benefit from Foundation Flash CS3 for Designers (friends of ED). The Amazon.com price is low; just enough, in fact, to get you free shipping (actually, that’s for US addresses; not sure how that would pan out for you). I co-wrote that one with Tom Green in the middle of 2007, and the reviews have been good. It may help you get introduced to other ActionScript concepts.

    Say I have 2 container objects, MovieA and MovieB. I now know how to reference the root timeline, but how would I referense from object A to object B?

    It all depends on where those objects in relation to each other. If MovieA is in the root, then evt.target.root.MovieA should do it. Alternatively parent could prove useful. Remember, evt.target (in this context) gives you a reference to the object that dispatched the event. If that object happens to be — and I’m making this up — MovieA, and if MovieB is in the same timeline as MovieA, then the parent of both of those objects is the same (doesn’t matter if that parent is root or not). So evt.target.parent.MovieB might very well work from MovieA’s point of view.

    You’ve helped me take a positive first step into A[S]3.

    Glad to hear that, Leigh! :)

  71. Bob Says:

    Hey david,

    I am trying to make my button jump from Scene 1 to Scene 2.
    Here is the line of code I put in

    about.addEventListener
    (MouseEvent.MOUSE_DOWN,
    function(MouseEvent)
    {(gotoAndPlay(”1”,”Scene 2″))});

    When I test the movie I get a syntax error, what am I doing wrong

    thanks
    Bob

  72. David Stiller Says:

    Bob,

    I noticed a couple things. Here’s my take on the same snippet:

    about.addEventListener(
      MouseEvent.MOUSE_DOWN,
      function(evt:MouseEvent):void {
        gotoAndPlay(1, "Scene 2");
      }
    );

    Notice that the function now receives an arbitrarily named parameter, evt, which is typed as MouseEvent (yours was missing evt, or some other name for the same parameter). I also typed the return value of this function as void, because it doesn’t return a value. Then, in the gotoAndPlay(), I notice you had the 1 in quotes, but unless you have a frame label named “1,” this parameter should be a number.

  73. Jared Says:

    Hello, I’ve got a question of hierarchy.

    MovieClip rhino1 is embedded inside btn3dSub, therefore the event listener is

    btn3dSub.rhino1.addEventListener(MouseEvent.MOUSE_OVER, btnSubOver);

    and the function would be

    private function btnSubOver(evt:Event):void
    {
    this[evt.target.parent.parent.name.evt.target.parent.name].gotoAndPlay(”over”);
    }

    The code above does not work. My question is how can I combine evt.target.parent.parent . evt.target.parent . gotoAndPlay(”over”) to achieve btn3dSub.rhino1.gotoAndPlay(”over”);

    Have been scratching my head for days. Thanks for your help.

  74. David Stiller Says:

    Jared,

    As it turns out, you don’t need the array access operator here. A direct object reference will do. If btn3dSub happens to be in the same scope as the event handler function, you could simply reference it by instance name:

    function btnSubOver(evt:MouseEvent):void {
      btn3dSub.gotoAndPlay("over");
    }

    Otherwise, you could use this:

    function btnSubOver(evt:MouseEvent):void {
      evt.target.parent.gotoAndPlay("over");
    }

    From the point of view of rhino1, btn3dSub is its immediate parent. Therefore, evt.target.parent points to btn3dSub. Note, the name property isn’t included, because that returns a string. What you want is a reference to the object itself.

  75. Covali Ioana Says:

    “evt.target.root.gotoAndPlay(5)” this line saved my life. i spent 2 day surfing the net in search of an answer. hope was almost lost . u are great. really the best blog. thank you very much and keep it up

  76. David Stiller Says:

    Covali,

    Glad to hear that!

  77. Emily Says:

    Hi David,

    Sorry to bother u. I have a flash intro and after playing, it will jump to another swf file.

    //I added these code at the last frame and works fine//

    stop();
    var swf2:String=’general.swf’;
    var requestSWF2:URLRequest=new URLRequest(swf2);
    var loader2:Loader=new Loader();
    loader2.load(requestSWF2);
    addChild(loader2);

    And now, I want to add a “Skip Intro” button to avoid playing the boring intro everytime. So, I added a “Skip Intro” button which I want to jump to another swf file after clicking it.

    myButton.addEventListener(
    MouseEvent.MOUSE_UP,
    function(evt:MouseEvent):void {

    var swf2:String=’general.swf’;
    var requestSWF2:URLRequest=new URLRequest(swf2);
    var loader2:Loader=new Loader();
    loader2.load(requestSWF2);
    addChild(loader2);

    }
    );

    ….and I failed. Could you help me on this? Thx!

  78. David Stiller Says:

    Emily,

    You didn’t say what failed, but I see from what you’ve typed so far that your problem might be the duplicated variable declarations. In ActionScript 3.0, variables can only be declared once per scope, and if the above code all appears in frame scripts in the main timeline (which is my hunch), then you’re using var to make multiple declarations.

    Give the following a try, and let me know if it it doesn’t work for you:

    // First frame
    var swf2:String = "general.swf";
    var requestSWF2:URLRequest = new URLRequest(swf2);
    var loader2:Loader = new Loader();
    addChild(loader2);
    
    myButton.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        loader2.load(requestSWF2);
      }
    );
    
    // Last frame
    stop();
    loader2.load(requestSWF2);

    Note that each of the necessary variables is only declared once. Once they’re set up in the first frame (or wherever your button appears), all the button handler needs to do is invoke that load() — and that’s all that needs to happen on the last frame, too.

    Does that make sense?

  79. Emily Says:

    Thank you so much David!

    It does jump to next swf file “general.swf”, but the intro flash still playing at the back while the “general.swf” is loaded and overlapping on the intro flash… Now 2 swf files playing (overlapping) at the same time, but I just want the general.swf file playing after clicking the “Skip Intro” button.

    Would you help me again on this issue??? Thx!

  80. David Stiller Says:

    Emily,

    Gotcha. :) Well, the revision I just suggested doesn’t actually stop the main timeline, which it probably should. You could either change the MOUSE_UP handler to this:

    myButton.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        stop();
        loader2.load(requestSWF2);
      }
    );

    … or maybe replace it altogether with this:

    myButton.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        gotoAndStop(250);
      }
    );

    … where the number 250 represents the last frame of your SWF — which means the playhead will jump straight there and execute the load() on that last frame. The first approach might be better, though, because the playhead won’t be able to jump to the last frame if your SWF hasn’t fully loaded (if it hasn’t, the last frame won’t exist yet, y’know?).

  81. Emily Says:

    Thank you so much and it works with 2 approach. Thanks a lot!

    1 approach did stop stop the intro but not the bg sound(sorry, forgot to mention at the beginning.) So, I took the 2nd approach, and works fine, thank you so much for your quick and helpful response!!!

  82. Molly Says:

    HELP!!! I’ve just been rudely introduced to actionscript 3.0. i was using the older versions and now cannot make a button get a URL! The instance name of my button is btnInv. What code should I use? Thanks a million. Molly

  83. David Stiller Says:

    Molly,

    See my answer to Tomek on September 18, 2007. The only difference for you is that the instance name will be btnInv instead of myButton. :)

  84. la Swear Says:

    hello,

    I am having a hard time figuring out why a student’s .FLA keeps giving me this error:

    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at nelson03_fla::MainTimeline/resumeA_mcRollOut()

    when you’ve clicked into the About Me scene and click his resume MC (to go to the resume scene)

    here is the actionscript:

    resumeA_mc.buttonMode = true;
    resumeA_mc.addEventListener(MouseEvent.MOUSE_UP , scrollText1 );
    function scrollText1(event:MouseEvent):void {
    gotoAndPlay(”scrollbar” , “Resume”);
    }
    resumeA_mc.addEventListener(MouseEvent.ROLL_OVER , resumeA_mcRollOver );
    function resumeA_mcRollOver(event:MouseEvent):void {
    resumeA_mc.gotoAndPlay(”overResume”);
    }
    resumeA_mc.addEventListener(MouseEvent.ROLL_OUT,resumeA_mcRollOut);
    function resumeA_mcRollOut(event:MouseEvent):void {
    resumeA_mc.gotoAndPlay(”upResume”);
    }

    thank you!

  85. David Stiller Says:

    la Swear,

    Well … I have to say, that code looks just fine. The error seems to be indicating that there’s an issue specifically in the resumeA_mcRollOut() function — but from what I’m seeing, all your student’s “i”s are dotted and “t”s crossed.

  86. la Swear Says:

    Thank you for looking at that, someone else suggested putting everything in one scene, but
    it’s frustrating not to be able to help the kid or explain WHY he’s getting that error.

    Awesome blog and great, clear explanations, thanks so much for your help!

    ~la Swear

  87. Alex Says:

    Hey David (or anyone that can help). This’ll be a dumb question for you guys but I’m new with flash.

    Problem: Have a button with a movie clip in the OVER state set to play once and then stop. When the button is pressed it always goes back to the OVER state and plays the movie again. I only want the movie to play once and the user can press the button a zillion times and always go back to the DOWN state so that the movie won’t replay again until he takes his mouse off the clip.
    If I recall this didn’t happen in Flash 8 and now with CS3 it does. Any thoughts and thanks for the help!

    AlexW

  88. David Stiller Says:

    To la Swear …

    Thanks for the kind words! I wish I could have answered your question.

    To Alex …

    Honestly, I’m getting the same response from Flash 8 as I am from Flash CS3. In either authoring tool, button symbols behave like this: the Down state defines the visuals when the mouse is clicked over the symbol; the Over state defines the visuals when the mouse is over the symbol, but not clicked — and that includes when the mouse button has been released from a clicked state.

    In other words, the Up state is default. When you roll over the symbol, the Over state is displayed. When you click, the Down state is displayed. When you release again, the Over state is displayed. Finally, when you move the mouse away, the Up state is displayed.

  89. Alex Says:

    Hey David thanks for the reply! I’m clear on all the states of the button. I’ll try to rephrase my question:

    Up State: No Problems here
    Over State: I have a short movie clip here of a cloud exploding and text appearing
    Down State:The text changes colour (exciting!)
    Hit State: No problems here.

    What I am trying to do is have the cloud explode and text appear (over state) and after clicked the movie NOT to be replayed while the mouse is still over the button symbol. Basically the cloud has remained exploded even after the button has been pressed. Any ideas?

  90. Petra Says:

    I noticed that this blog is really good. I am new to flash and I can’t find the answer to my question online.
    I have a movie clip playing within the main movie and at the end I want this movie clip to stop and then go to main movie timeline. basically I want then my main movie to play. How do I make that happen? to refer to maintimeline within a movie clip?
    I hope you can help me with that. Or at least tell me where I could find the answer.

  91. Æli Manouchehri Says:

    Hi David,
    I have truble showing my flash movies in ie7, they work perfektly in Safari and Opera.

    Pulling my hair out over this :(

  92. David Stiller Says:

    Æli Manouchehri,

    I wonder if your HTML is incorrectly formatted? Are you using both <object> and <embed> tags?

  93. Kevin Says:

    Hi David,

    I’m trying to get a vertical popup menu that will have four menu items that will cause a change of an item on the stage being controlled by the clicking of one of the menu options. I just went to Flash and ActionScript 3.0 class last week and know just enough to give myself a headache. Do you have any suggestions on the best way to go about this?

  94. Akaliza Says:

    Thanks man, I’ve been trying to work this out for days!
    God bless you!

  95. Kenzie Says:

    David;

    I need your help. BTW your site has been very helpful!!

    I am using Action Script 3.0
    I have a music file in a frame and I am using a buttom that allows the user to skip forward to another frame. I have that working but the music still plays. I can’t get it to stop!! I want the button to stop the music and move forward to another frame. Here is the code I have to go forward to another frame but I can’t get the stop music to work for me.

    skipto.addEventListener(
    MouseEvent.MOUSE_UP,
    function(evt:MouseEvent):void {
    evt.target.parent.gotoAndPlay(1135);
    }
    );

    THANK YOU!!!!

  96. David Stiller Says:

    To Alex …

    What I am trying to do is have the cloud explode and text appear (over state) and after clicked the movie NOT to be replayed while the mouse is still over the button symbol.

    In ActionScript 3.0, button symbols are defined by the SimpleButton class, which is not a dynamic class. That means it can’t have properties added to it an runtime, which (I think) is the reason you can’t refer to a button symbol’s movie clip children by instance name.

    I tried a few approaches in which I put code into a nested movie clip’s own timeline, refering to its parent (the button), but things started getting pretty dicey. You’ve posed an interesting puzzle, and I’ll probably keep grappling with this one for a while, but in the mean time, I was able to work toward a solution — not an especially simple one — by replacing the button symbol with a movie clip instead. Inside this movie clip, I nested a second movie clip symbol, which was my version of your explosion. The outer movie clip only has one frame.

    Assuming the instance names myButton and myClip, even though myButton is actually a movie clip symbol, here’s a bit of code that gave me — I believe — what you’re after:

    myButton.mouseChildren = false;
    myButton.myClip.visible = false;
    myButton.myClip.stop();
    myButton.myClip.ready = true;
    
    myButton.addEventListener(
      MouseEvent.MOUSE_OVER,
      function(evt:MouseEvent):void {
        myButton.myClip.visible = true;
        myButton.myClip.play();
      }
    );
    
    myButton.addEventListener(
      MouseEvent.MOUSE_OUT,
      function(evt:MouseEvent):void {
        myButton.myClip.visible = false;
        myButton.myClip.gotoAndStop(1);
        myButton.myClip.ready = true;
      }
    );
    
    myButton.addEventListener(
      MouseEvent.MOUSE_DOWN,
      function(evt:MouseEvent):void {
        myButton.myClip.visible = false;
        myButton.myClip.gotoAndStop(1);
        myButton.myClip.ready = false;
      }
    );
    
    myButton.addEventListener(
      MouseEvent.MOUSE_UP,
      function(evt:MouseEvent):void {
        myButton.myClip.visible = false;
        myButton.myClip.gotoAndStop(1);
      }
    );

    That first line, addressing myButton’s mouseChildren, keeps myClip from responding to mouse events. That ready variable in myClip’s timeline is used by later code to decide when and when not to play myClip’s animation.

    To Petra …

    How do I make that happen? to refer to maintimeline within a movie clip?

    All you really need is to put a frame script in the last keyframe of your movie clip’s timeline, referencing the MovieClip.parent property of the movie clip:

    // Last frame of movie clip ...
    this.parent.play();

    However, given the way AS3 handles this particular reference, you’ll need to let ActionScript know that the timeline reference by this.parent is actually a MovieClip instance. You can do that by casting the reference as MovieClip:

    // Last frame of movie clip ...
    MovieClip(this.parent).play();

    To Kevin …

    I’m trying to get a vertical popup menu that will have four menu items that will cause a change of an item on the stage being controlled by the clicking of one of the menu options.

    There are a number of ways you might approach this, depending on the complexity of your goal (should the menu animate into place, or just suddenly snap into visibility? etc.). One simple approach could be to put your menu buttons inside a movie clip symbol. Give the movie clip symbol an instance name, and do the same for the nested buttons.

    In your main timeline frame script, wire up the buttons by referencing the movie clip’s instance name first, then each button in turn …

    myClip.myButtonA.addEventListener(...);
    myClip.myButtonB.addEventListener(...);
    myClip.myButtonC.addEventListener(...);

    … and also set the visibility of the movie clip to false.

    Wire up another button, also on the main timeline, to set the visibility of the movie clip to true when clicked.

    It gets more complicated, of course, because you’ll want the movie clip to disappear again when you mouse away from it. You could write a MOUSE_OUT event handler for that movie clip that would set itself back to invisible. Also bear in mind, the movie clip and its buttons will be active, even when they’re not visible, so you’ll want to introduce InteractiveObject.mouseEnabled — inherited by buttons and movie clips — and DisplayObjectContainer.mouseChildren — inherited by movie clips — into the equation (see my reply to Alex).

    To Akaliza …

    Thanks man, I’ve been trying to work this out for days!

    Glad to help! :)

    To Kenzie …

    I have a music file in a frame and I am using a buttom that allows the user to skip forward to another frame. I have that working but the music still plays. I can’t get it to stop!!

    My hunch is that your audio is attached directly to the main timeline (in a keyframe) and that it’s configured as an Event sound, which means the whole thing is triggered at once and plays all the way through. Select that keyframe and change it to Stream. Let me know if that helps, or if my hunch is totally off.

  97. Billy Says:

    hi there, wondering if you could help me? i recently started a job as a web designer, i’m 19 but taught myself html and graphics using photoshop etc from the age of 11. upon getting this job i was told i needed to learn flash (actionscript3.0), CSS, using DIVS and learning to write pages from raw HTML all over again rather than use dreamweaver or frontpage.

    The problem is I have made a layout in photoshop, cut up the images, lined them up in HTML using divs perfectly fine, but the layout has 2 flash elements. the first is a simple picture fader which is working fine, the second is the nav bar. I am using an IFrame for the pages, but can’t get my flash nav bar buttons to target the IFrame.

    In the flash file I have a layer for the background and a layer for each of the 3 nav buttons, this is the AS3.0 i have applied to each button…

    contact.addEventListener(MouseEvent.CLICK, bClick);
    function bClick(event:MouseEvent):void {
    navigateToURL(new URLRequest(”contact.html”), (”iframe”);
    trace(”I’m Clicked”);
    }

    It doesn’t work no matter what I try, please help!

    Regards
    Billy

  98. David Stiller Says:

    Billy,

    What’s the value of the name attribute of your <iframe> element? Whatever you use to target that <iframe> in your ActionScript — looks like you’re using “iframe” — that’s what you need to actually name that element in your HTML code (that second parameter doesn’t need to be in parentheses, by the way).

  99. Billy Says:

    the name of the iframe is actually just iframe but cheers for the help ill try it out shortly and get back to you
    cheers
    Billy

  100. David Stiller Says:

    Billy,

    I don’t know for sure, but my hunch is that naming an element the name of that element potentially confuses matters. How about naming it “externalContent”?

  101. billy Says:

    right i really am not getting anywhere with this, could you possibly re-write the AS3 for me with what you think will solve the problem? i don’t know if i need to use variables or anything. and also, am i right in having a seperate code for each button putting the actions on the keyframe of each button layer?

  102. David Stiller Says:

    Billy,

    You don’t really need any variables. Just a click handler and the proper parameters in your navigateToURL() call. Since your button seems to have the instance name contact, I used that in my own test of your endeavor. Here’s my ActionScript 3.0:

    contact.addEventListener(MouseEvent.CLICK, clickHandler);
    
    function clickHandler(evt:MouseEvent):void {
        navigateToURL(new URLRequest("http://www.adobe.com"), "externalContent");
    };

    am i right in having a seperate code for each button putting the actions on the keyframe of each button layer?

    Personally, I would put all three buttons in one layer (though a separate layer for each would be fine) and I’d put all my ActionScript in its own layer named “scripts.” In order for the above example to work, an <iframe> tag needs to be added to the HTML document — an <iframe> tag whose name attribute matches the second parameter of the navigateToURL() call:

    <iframe src="http://www.quip.net/" name="externalContent"></iframe>
  103. Kevin Says:

    Thanks David

  104. David Stiller Says:

    Kevin,

    Sure thing! :)

  105. billy Says:

    still no joy david. don’t know whats going wrong. my iframe is now called externalContent but it’s still not working. when i test movie or export movie i get the error “duplicate function definition” (twice) on the function clickhandler part.

  106. David Stiller Says:

    Billy,

    Ah! Then you’re defining your function more than once — whether you’re calling it bClick() or clickHandler(), something else.

    Does each of your separate functions send the <iframe> to a unique URL? If so, the easiest thing is to write three separate functions, such as clickHandlerA(), clickHandlerB(), and clickHandlerC() (or name them something more descriptive, like contactHandler(), aboutUsHandler(), etc.).

    If, instead, all three buttons are using the same function, then you only need to define the function once, and supply that same function as the second parameter to all three buttons’ addEventListener() call.

  107. Luke Says:

    Great tips!! however I am having a different difficulty I believe that others may also be having.

    I am working in Actionscipt3 and have flash document with a number of key frames each having different content. Buttons to click back and forth between different pages are repeated across these pages so that the user can navigate between the sections of the site. My difficulty is that I must be missing something in the transition from actionscript2. I wanted not to have to repeat the same code over and over to enable the button instances to function that are reused throughout the site to take the user to the appropriate section on release of the mouse. Sounds simple but it’s been a headache. I get compiler errors stating properties, methods & accessibility Properties are not defined.

    Please help!! Thank you…

    HERE IS PART OF THE PACKAGE CODE: (Only defines & listens for two buttons at moment)

    package

    {

    //IMPORT AC3 CLASSES NEEDED
    import flash.events.MouseEvent;
    import flash.net.URLRequest;
    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.Event;

    //DEFINE MAIN CLASS
    public class evulonMain extends MovieClip
    {

    //DEFINE FUNCTION & EVENT LISTENER

    //GENERAL NAVIGATION DEFINED & LISTENER

    //profilePage event handler, function name “clickProfile”
    function clickProfile(event:MouseEvent):void {
    //goto “profile” label
    gotoAndStop(”profile”);
    }
    //profilePage event listener: instance name “profilePage” & handler name “clickProfile”
    profilePage.addEventListener(MouseEvent.CLICK, clickProfile);
    //output text
    trace(”profile page button clicked”);

    //tutoringPage event handler, function name “clickTutoring”
    function clickTutoring(event:MouseEvent):void {
    //goto “tutoring” label
    gotoAndStop(”tutoring”);
    }
    //tutoringPage event listener: instance name “tutoringPage” & handler name “clickTutoring”
    tutoringPage.addEventListener(MouseEvent.CLICK, clickTutoring);
    //output text
    trace(”tutoring page button clicked”);
    }
    }

  108. Æli Manouchehri Says:

    So here is how my code looks:

  109. Billy Says:

    aha! progess! not quite there yet tho, but the links now work, only problem is theyre opening the page in a new window rather than the Iframe, which I named “externalContent” same as the parameter of the URLRequest in the AS3. any thoughts?
    cheers

  110. Billy Says:

    this is the current code

    home.addEventListener(MouseEvent.CLICK, clickHandlerA);

    function clickHandlerA(evt:MouseEvent):void {
    navigateToURL(new URLRequest(”index2.html”), “externalContent”);
    };

    prices.addEventListener(MouseEvent.CLICK, clickHandlerB);

    function clickHandlerB(evt:MouseEvent):void {
    navigateToURL(new URLRequest(”prices.html”), “externalContent”);
    };

    contact.addEventListener(MouseEvent.CLICK, clickHandlerC);

    function clickHandlerC(evt:MouseEvent):void {
    navigateToURL(new URLRequest(”contact.html”), “externalContent”);
    };

  111. David Stiller Says:

    To Luke …

    Off the top of my head, I see references to profilePage and tutoringPage that aren’t defined in this class, so that may be a good place to start troubleshooting. Is this a document class? Should you be declaring these button instances?

    To Æli …

    Your code didn’t come through, so I followed up with you via email. Fire back, and I’ll post your code. :)

    To Billy …

    At this point your AS3 looks fine. What’s the URL to this page? Maybe I can see something in the HTML.

  112. Luke Says:

    thank you for your feedback.

    with the following code below I am now getting 2 errors and cannot find help on the topic that makes sense to me.

    -error 1120 undefined property for applyPage & clickApply??
    -& error 5000 the class “applyForQuote” must subclass flash.display.SimpleButton??

    Secondly can you explain the purpose of the document class??

    Thankyou..

    package {

    //IMPORT AC3 CLASSES NEEDED
    import flash.events.MouseEvent;
    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.Event;
    //import flash.accessibility;

    //DEFINE APPLY FOR QUOTE BUTTON CLASS, FUNCTION, LISTENER
    public class applyForQuote extends MovieClip {
    //applyPage event handler, function name “clickApply”
    public function clickApply(event:MouseEvent):void {
    //goto “apply” label
    gotoAndStop(”apply”);
    }
    //applyPage event listener: instance name “applyPage” & handler name “clickApply”
    applyPage.addEventListener(MouseEvent.CLICK, clickApply);
    //output text
    trace(”apply page button clicked”);
    }
    }

  113. Anita Says:

    I’m having a problem with buttons (big surprice :-) ). Two buttons (first image alpha out and the next in, and vice versa) are placed in separate layers, and both buttons keep directing to the first URL (big mystery to me!).

    The code:

    maria.addEventListener(MouseEvent.CLICK, gotomaria);
    function gotomaria(event:MouseEvent):void {
    //navigateToURL(new URLRequest(”http://www.fef-aalborg.dk/testsite/sider/rapport/indien2008maria.html”), “_self”);
    }
    lisser.addEventListener(MouseEvent.CLICK, gotoingerlise);
    function gotoingerlise(event:MouseEvent):void {
    //navigateToURL(new URLRequest(”http://www.fef-aalborg.dk/testsite/sider/rapport/indien2008ingerlise.html”), “_self”);
    }

    I checked instance names, etc., but nothing has helped. They should be able to work, although they’re placed on top of each other (fading out/in), shouldn’t they?

    Anita :-)

  114. Kenzie Says:

    David.
    Just wanted to let you know that the fix you gave me for my music worked. thank you so much!!

  115. eli Says:

    So I found your page and used this code to write my menu successfully! Thank you! But a question: I have an event listener for MOUSE_OVER OUT and UP for such a small menu/submenu rollouts it just seems like so much code… Is there a shorter way to write the code?

    check it out here

    What do you think?

  116. Shane Says:

    Billy,

    I was having the exact same issue as you.

    It turns out your code is most likely perfect - try uploading it and testing it fromt he actual website.

    When I was testing the HTML pages locally I was having the issue where clicking the link didn’t open in the iframe, but in a new window. After uploading it to the live site the buttons opened the content correctly within the iframe.

    I hope that helps

    -Shane

  117. David Stiller Says:

    To Luke …

    -error 1120 undefined property for applyPage & clickApply??
    -& error 5000 the class "applyForQuote" must subclass flash.display.SimpleButton??

    The mention of “must subclass flash.display.SimpleButton” leads me to believe you’re using a linkage class, and that you’re adding linkage to a button symbol. If that’s the case, then you will indeed need to make your classs extend SimpleButton rather than MovieClip:

    public class applyForQuote extends Simplebutton { ... }

    I’m not sure (so far) why you’re using a custom class — not that there’s anything wrong with a custom class; it’s just that doing so adds a layer of complexity to your goal, which means you have more steps to troubleshoot. The “undefined” applyPage property, in particular, suggests to me that you haven’t given a button symbol the instance name applyPage, but if this class truly needs to extend SimpleButton, then all of this takes place inside a button symbol, and you wouldn’t have a nested button anyway.

    can you explain the purpose of the document class??

    Sure. :) Essentially, a document class is the FLA version of a linkage class. In AS3 documents, you can associate an external class file with the main timeline of the FLA. In affect, you can re-write the behavior of the main timeline — by extending MovieClip or Sprite — in the same way that you can re-write the behavior of a Library asset with a linkage class.

    These are all cool ideas, for sure, but none are necessary for wiring up buttons in AS3. I think it may help you, at this point, to save your current work and start a fresh set of files — very simple files, just enough to act as proofs of concept — and work your way through the various mechanics involved in a) wiring up a button from a frame script, b) attaching a button symbol at runtime from the library (both with and without an actual class file), c) using a linkage class to affect event handling for a button symbol.

    This is only a hunch, mind you, but it seems to me like you’re using a linkage class to handle a button’s events.

    To Anita …

    It sounds to me like one of these buttons is stacked on top of the other. When the top one is alpha-ed out, it should be removed from the timeline, otherwise it will continue to be present (even if invisible). Does that make sense?

    To Kenzie …

    Glad to hear that!

    To eli …

    In its simplest form, what you’ve shown is fine. Yes, it’s a lot of code, but coding is a complex discipline and often takes a lot of work. You could certainly reduce the sheer number of lines by writing a single function and using, say, a switch statement to evaluate the current button’s instance name, then make your decisions based on that.

    To Shane …

    Thanks for that insight. I was able to test locally, but that may have been due to the so-called “mark of the web” statement in my HTML document (I wouldn’t swear by that, but it’s a thought).

  118. Brandon Says:

    Hi,

    I’ve read through and tried to follow along with these problems, I’m still missing something. In my movie clip I want to stop and goto frame 2 in my Scene labled “Main Content”. So I have the following script:

    import flash.display.MovieClip;
    gotoAndPlay(2,”Main Content”);
    stop();

    When it does to do the “gotoAndPlay(2, “Main Content”);” I get this error:

    ArgumentError: Error #2108: Scene Main Content was not found.
    at flash.display::MovieClip/gotoAndPlay()
    at Untitled_fla::Background_1/Untitled_fla::frame76()

    I saw that somone else had the same error, but found a soultion. I need some help! Thanks a lot!

  119. Tristan Says:

    Hello there! Just trying flash cs3 for the first time. Just wandered if you wouldn’t mind setting me straight on something,….

    All I need is two buttons in the main timeline to navigate back and forward ( I’m putting together a presentation ) I searched through the flash help files and found this code..

    import flash.events.MouseEvent;

    mc1.stop();
    prevBtn.addEventListener(MouseEvent.CLICK, goBack);
    nextBtn.addEventListener(MouseEvent.CLICK, goForward);

    function goBack(event:MouseEvent):void {
    mc1.prevFrame();
    }

    function goForward(event:MouseEvent):void {
    mc1.nextFrame();
    }

    I’ve made two buttons and given them the instance names prevBtn and nextBtn but I think the main problem I’m having is defining where mc1 is? The movie doesn’t stop which is the first part of the code. How can I change the code to react to the main timeline? Any help would be appreciated! Many thanks

    Tristan

  120. David Stiller Says:

    To Brandon …

    Movie clips technically support scenes, but in actual practice, you can only create scenes in the main timeline (scenes are ultimately just sections of the same timeline anyway).

    When you say this:

    In my movie clip I want to stop and goto frame 2 in my Scene labled “Main Content”.

    … it almost sounds to me like you’re trying to send a particular movie clip symbol to another scene in the main timeline. I’m not sure that’s what you’re saying, but that wouldn’t work if so. Have you double-checked that you really created a scene in your main timeline named “Main Content”? Maybe you misspelled it or accidentally put a space character at the end?

    To Tristan …

    In the sample code shown, mc1 refers to the instance name of a movie clip in the same location as your buttons — some movie clip needs an instance name, just like you’ve given your buttons. If you want the main timeline to stop, instead of some movie clip, just drop that prefix reference:

    <