Building a Basic Menu in ActionScript 3.0 Tutorial – Part 1 – Array

7 Sep

Today I have decided to build a simple ActionScript 3.0 horizontal menu based on an array. This is a fairly common practice in Flash development as we are often using data provided from a XML file to dynamically update content within our movies. To simplify this tutorial I am going to use an array that is written within my code instead of parsing it from a XML file.

The following example will demonstrate how to loop through an array and draw a button for each item in that array. Each button will have a label, an up state and an over state. I have read that it is good practice to use the SimbleButton object whenever possible, but I am not going to use the it in this tutorial because I am interested in learning more about addChild(), getChildByName(), currentTarget, mouseChildren and other features of ActionScript 3.0 that could be avoided using the SimpleButton.

package ca.flashdev.example {		

  import flash.display.Sprite;
  import flash.display.Shape;
  import flash.events.MouseEvent;
  import flash.text.TextField;
  import flash.text.TextFieldAutoSize;
  import flash.text.TextFormat;

  public class BasicMenu extends Sprite {		

    // Create the array of button names.
    private var __MenuArray:Array = new Array("Button 0",
                                              "Button 1",
                                              "Button 2",
                                              "Button 3",
                                              "Button 4");		 

    /**
     * The constructor. This method is fired automatically
     * when the class is instantiated.
     */
    public function BasicMenu():void {
      drawMenu();
    }

    /**
    * Draw the menu.
    */
    private function drawMenu():void {

      // This variable will hold the x position
      // of the next button in the menu.
      var xPos:Number = 0;

      // Create a holder that will contain the menu.
      var menuHolder:Sprite = new Sprite();

      // Add the holder to the stage.
      addChild(menuHolder);			

      // Create text formatting for the text fields in the menu.
      var format:TextFormat = new TextFormat();
      format.font = "Verdana";
      format.color = 0x000000;
      format.size = 12;
      format.bold = true;

      // Loop through the array.
      //Create each item listed in the array.
      for (var i in __MenuArray) {

        // Create the button.
        var button:Sprite = new Sprite();
        button.name = "button"+i;

        // Disable the mouse events of all the
        // objects within the button.
        button.mouseChildren = false;

        // Make the sprite behave as a button.
        button.buttonMode = true;

        // Create the label for the down button state.
        var label:TextField = new TextField();
        label.autoSize = TextFieldAutoSize.LEFT;
        label.selectable = false;
        label.defaultTextFormat = format;
        label.text = __MenuArray[i];

        // Create an up state for the button.
        var up:Sprite = new Sprite();
        up.graphics.lineStyle(1, 0x000000);
        up.graphics.beginFill(0x00FF00);
        up.graphics.drawRect(0, 0, 100, 30);
        up.name = "up";

        // Create an over state for the button.
        var over:Sprite = new Sprite();
        over.graphics.lineStyle(1, 0x000000);
        over.graphics.beginFill(0xFFCC00);
        over.graphics.drawRect(0, 0, 100, 30);
        over.name = "over";

        // Adder the states and label to the button.
        button.addChild(up);
        button.addChild(over);
        button.addChild(label);				

        // Position the text in the center of the button.
        label.x = (button.width/2) - (label.width/2);
        label.y = (button.height/2) - (label.height/2);

        // Add mouse events to the button.
        button.addEventListener(MouseEvent.MOUSE_OVER,
                                displayActiveState);
        button.addEventListener(MouseEvent.MOUSE_OUT,
                                displayInactiveState);
        button.addEventListener(MouseEvent.CLICK,
                                displayMessage);

        // Add the button to the holder.
        menuHolder.addChild(button);

        // Position the button.
        button.x = xPos;

        // Increase the x position for the next button.
        xPos += button.width + 2;

        // Hide the over state of the button.
        over.alpha = 0;
      }

      // Postion The Menu.
      menuHolder.x = 20;
      menuHolder.y = 20;

    }

    /**
     * Show the active state of the button.
     */
    private function displayActiveState(event:MouseEvent):void {

      // Show the over state of the button.
      event.currentTarget.getChildByName("over").alpha = 100;
    }

    /**
    * Hide the active state of the button.
    */
    private function displayInactiveState(event:MouseEvent):void {

      // Hide the over state of the button.
      event.currentTarget.getChildByName("over").alpha = 0;
    }

    /**
     * Display a message in the Output window.
     */
    private function displayMessage(event:MouseEvent):void {

      // Output the name of the clicked button.
      trace(event.currentTarget.name)
    }
  }
}

Save this file as BasicMenu.as in a folder structure of ca.flashdev.example.
Create a new movie and add ca.flashdev.example.BasicMenu to the ActionScript 3.0 Settings Document class field. Save this file as basicMenu.fla in the same directory as your ca folder. Publish (Ctrl+Enter) your movie and you should see the menu.

Download the source files

29 Responses to “Building a Basic Menu in ActionScript 3.0 Tutorial – Part 1 – Array”

  1. John Depersis September 11, 2006 at 10:31 am #

    Great article! However, for the lazy like me I prefer FMF.

    See: http://www.flashmenufactory.com/

  2. screamingworld February 9, 2007 at 10:56 am #

    Hallo,

    if I compile this sample with flashDevelop, then I get the following error msg.

    Anybody know whats wrong with it?

    TypeError: Error #1009: Der Zugriff auf eine Eigenschaft oder eine Methode eines null-Objektverweises ist nicht möglich.
    at appClasses::BasicMenu/::displayActiveState()

    bye
    Markus

  3. bluelife March 19, 2007 at 3:35 am #

    hi,Markus .u must change the code:
    over.name = “down”;
    to
    over.name = “over”;
    I think it’s a little mistake by author.
    or u can download the source files,it works fine.

  4. Fraser Crosbie March 29, 2007 at 9:36 am #

    Thanks BlueLife… I fixed the code.

  5. Are April 24, 2007 at 3:17 am #

    I’m a student familiar with java-programming and I decided to get some flash skills, but things didn’t go as smooth as I expected. Luckily I found your site. Your tutorials are simple and very understandable. Thanks and keep up the good work :)

  6. Chris May 4, 2007 at 7:21 am #

    Hi, thanks for this tutorial code. Its nicely formatted and easy to understand. It would be even nicer if you could include the completed Flash Object on the page as an example of how it will look.

  7. Fraser Crosbie July 13, 2007 at 2:19 pm #

    Thanks for the suggestion Chris. I have added the Flash movies for my tutorials throughout the site.

  8. Roustalski August 21, 2007 at 12:17 pm #

    Thanks for this example.

  9. CLS August 23, 2007 at 8:15 am #

    I have been looking for help in making a single play button that I would use to play my Flash animation. I am extremly new to Actionscript and am still learning what certain things mean. Is there anyway anyone can help me understand how to create a play button that would actually link to the rest of my animation?
    Thank you,
    CLS

  10. Fraser Crosbie August 23, 2007 at 9:03 am #

    Hi CLS,

    1) Create your animation on the timeline.
    2) Add another layer and draw a play button in it. Select the button and hit F8. Choose Button.
    3) Select the play button and look in the Properties panel (bottom of screen).
    4) Type play_mc where you see Instance Name.
    5) Create a new layer in the timeline. Click into the new layer and press F9 (Actions Panel).
    6) Add the following code to the Actions panel:
    play_mc.addEventListener(MouseEvent.MOUSE_DOWN, playAnim);
    function playAnim(event:MouseEvent):void {
    play();
    }
    stop();

    I emailed you my test file. LMK if you have any questions.

  11. KJ September 18, 2007 at 4:54 am #

    It’s taken me at least 2 hours to find a decent tutorial on creating a navigation from an Array and finally I’ve found one that helped. Cheers! I’ve modified your code to work with multidimensional arrays, I hope you don’t mind.

  12. Fraser Crosbie September 18, 2007 at 8:11 am #

    Not at all.

  13. Aris January 13, 2008 at 6:06 am #

    ya, god, why does it have to be so hard to find something so simple >_<.. thanks a bunch Crosbie, works great

  14. sun January 17, 2008 at 12:41 am #

    thank you for tutorial

  15. DMC February 18, 2008 at 5:35 am #

    2 hours? You’re lucky, I’ve found this after 3 weeks of searching. Not even anything on Adobe livedocs.

    Maybe someone can tell me why there is SO little documentation around, even for common things like this?

  16. karakul April 7, 2008 at 5:15 am #

    Great thank’s!!!
    I’ve spend several hour to find the menu quite simple and clear to use. Because I’m not a big expert in programing this tutorial suite’s me the best.

  17. Kapitaine February 25, 2009 at 11:37 am #

    Hi this is a great site – consider it bookmarked! Your ActionScript 3 stuff is really helpful for me as I’m just learning and you keep things rather straightforward.

    One thing I would recommend is to allow for a bigger area to display your example code…the textarea right now (at least in IE6) is very small and scrolling through a large amount of lines is tricky. Other than that the site is great!

    Keep up the good work.

    Thanks,
    Mikey.

    PS – Only using IE6 because I’m on a locked-down network.

  18. Fraser Crosbie February 25, 2009 at 9:29 pm #

    Thanks Mikey! I recently updated the theme of this blog and never realized that the height of the code samples shrunk.

  19. Tawhid June 9, 2009 at 7:44 pm #

    How can I change the text color while on Mouse_Over. I see you are changing the sprite only, what would be the best way to change the Text Format on Mouse Over to each Menu.

    Thanks,

  20. jeff June 12, 2009 at 9:48 am #

    Thank you for this well thought out tutorial!!!

    I wish all programmers would comment like you. Kudos!

  21. newton January 8, 2010 at 1:36 pm #

    This is the most simple, clear and understandable Menu-AS3-Tutorial I found.
    Thanks very much.

  22. Leo February 19, 2010 at 3:00 am #

    Ok so we need to build a Menu in Flash, lets hire someone for a ridiculous hourly wage, pffftt please.

    Basic Menu, complicated code. AS3 is not for designers, that is all.

  23. Joel March 20, 2010 at 3:16 am #

    Thanks Fraser, this was the exact thing I have been looking for the last three day.

    Excellent! thanks for doing a tutorial on this topic. Very helpful.

  24. Alain April 8, 2010 at 2:18 pm #

    Great menu,
    how can I do to have the clicked button as inactive ? thanks…

  25. chetan April 21, 2010 at 11:01 pm #

    how to animate button to use As3?

  26. VictorArias August 27, 2010 at 12:43 pm #

    My question is:

    It’s a menu, probably to navigate.

    How is programmed the actions of each button?

  27. September 21, 2010 at 9:37 am #

    Hi, compliments for the optimal job. I would want to know how to connect menu’s buttons to some movieclip that are collocated on the stage. Sorry for my english and please help me!

  28. luisyucra December 3, 2010 at 10:20 am #

    thanks, very much.

    good code

  29. Boston Terrier January 6, 2011 at 10:53 pm #

    Thanks for the codes. It is so helpful with this array looping code tutorials.

Leave a Reply