• home
  • forum
  • my
  • kt
  • download
  • Vertical Menu with Actionscript 3 and XML

    Author: 2009-07-14 08:03:25 From:

    This tutorial will teach you how to create a vertical menu with the help of XML and ActionScript 3. We will first set up everything ready in the Flash stage, then make the XML file and last, we add the functionality with ActionScript 3. Hope you enjoy the tutorial!

    Get TweenMax

    We will use TweenMax for the movement and animation of the whole menu. Therefore, download TweenMax for AS3. TweenMax will save us a lot of time from coding the animation ourselves! Save the “gs” folder to the same location where your .fla file will be located.

    New Document

    First create a new Flash ActionScript 3 document.

    Flash new do

    Document Properties

    Set the following properties for the document:

    Size: 350×300
    Background: white
    Frame rate: 30

    Flash document properties

    Mask for the Menu

    We will be using a mask for the whole menu so let’s create that first. With the rectangle tool, create a black rectangle of size 200×250 without any stroke. Align it to the center of the stage.

    flash align

    Mask to Movie Clip

    Convert the rectangle to a movie clip. Name it “My Mask” and set the registration point to the top left corner.

    Mask to Movie CLip

    Mask Instance Name

    Give the mask movie clip an instance name of “myMask”.

    Mask Instance Name

    New Layer for Menu Item

    Create a new layer named “menu item”.

    Flash new layer

    Menu Item Shape

    In the “menu item” layer, draw a rectangle of size 200×20 with a fill color of #330000 (no stroke).

    Menu Item Shape

    Menu Item Movie Clip

    Convert the rectangle to a movie clip named “Menu Item”. Set the registration point to the top left corner. As you may have guessed, this movie clip will be used as a single menu item in the menu.

    Menu Item Movie Clip

    Menu Fill

    Double click the “Menu Item” movie clip on the stage. You should now be “inside” the movie clip. Convert the rectangle shape to a movie clip named “Menu Fill”. Set the registration point to the center. We do this because we want to animate the fill color separately from the menu text which we’ll add later on in this tutorial.

    Menu fill movie clip

    Menu Fill Alpha

    Set the alpha to 30% for the “Menu Fill” movie clip.

    Menu Fill Alpha

    Instance Name for the Menu Fill

    Give the “Menu Fill” movie clip an instance name of “menuFill”.

    Menu fill instance name

    Layer for the Menu Text

    While still inside the “Menu Item” movie clip, create a new layer named “menu text”.

    Menu text layer

    Menu Text Field

    In the “menu text” layer, create a dynamic text field so that it’s positioned on top of the “menuFill” movie clip. Type some text in it and set the following properties:

    width: 180
    height: 18
    family: Arial Rounded MT Bold
    size: 12.0 pt
    color: white
    alighn: align left

    Menu text settings

    Embed Characters

    Since we will have dynamic text in the text fields (from XML), we must embed some characters to make the text look smooth. So click the “Character Embedding” button and select uppercase, lowercase and numerals.

    Character Embedding

    Text Field Instance Name

    Give the text field an instance name of “menuText”, so we’ll be able to access it through ActionScript.

    Menu text instance name

    Menu Item Properties

    Go back to the main timeline. Right click the “Menu Item” movie clip in the library and select “Properties” (might be “Linkage” in Flash CS3).

    Movie Clip Properties

    Linkage

    Link the movie clip to a class named “MenuItem” (don’t worry about the warning that appears when you hit ok). We link the movie clip to a class, because we’ll create all the menu items from ActionScript and therefore, we need a class that represents a menu item movie clip.

    Movie Clip Linkage

    Now remove the “Menu Item” movie clip from the stage, since we’ll create them from ActionScript.

    Preparing the XML

    Before we go into ActionScript, let’s first set up the XML file that will define the menu labels and where the menu items should link to. So with your favorite text editor, type the following.

     
    <menu>
     
        <buttons>
     
            <button>
                <label>Home</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Tutorials</label>
                <linkTo>http://tutorials.flashmymind.com/complete-list-of-flash-and-actionscript-3-tutorials/</linkTo>
            </button>
            <button>
                <label>Forum</label>
                <linkTo>http://tutorials.flashmymind.com/forum/</linkTo>
            </button>
            <button>
                <label>About</label>
                <linkTo>http://tutorials.flashmymind.com/about/</linkTo>
            </button>
            <button>
                <label>Label 5</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 6</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 7</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 8</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 9</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 10</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 11</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 12</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 13</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 14</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 15</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 16</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 17</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 18</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 19</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 20</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 21</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 22</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 23</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
            <button>
                <label>Label 24</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
     
        </buttons>
     
    </menu>

    Save the file as “menu.xml” in the same location where your .fla file is.

    Layer for ActionScript

    In the main timeline, create a new layer named “actions” and open the actions panel.

    Action panel

    ActionScript 3 - Load XML

    First let’s import TweenMax and load the XML data.

    //Import TweenMax
    import gs.*;
     
    //The path for the XML file (use your own here)
    var xmlPath:String = "http://flashmymind.com/SWF/menu.xml";
     
    //We will store the loaded XML to this variable
    var xml:XML;
     
    //Create a loader and load the XML. Call the function "xmlLoaded" when done.
    var loader = new URLLoader();
    loader.load(new URLRequest(xmlPath));
    loader.addEventListener(Event.COMPLETE, xmlLoaded);
     
    //This function is called when the XML file is loaded
    function xmlLoaded(e:Event):void {
     
    	//Make sure that we are not working with a null variable
    	if ((e.target as URLLoader) != null ) {
     
    		//Create a new XML object with the loaded XML data
    		xml = new XML(loader.data);
     
    		//Call the function that creates the menu
    		createMenu();
    	}
    }

    The code is quite straightforward. We specify which XML file we want to load, then load it and call the function xmlLoaded() when we have finished loading. In the xmlLoaded() function we create a XML object with the data that we just loaded. Then we call the function createMenu(), which is responsible for creating and positioning the whole menu.

    ActionScript 3 - createMenu()

    The following code sets up the menu.

    //Create a menu holder that will contain all the menu items
    var menuHolder:MovieClip = new MovieClip();
     
    //Give it the same position as the mask
    menuHolder.x = myMask.x;
    menuHolder.y = myMask.y;
     
    //Assign a mask for the menu
    menuHolder.mask = myMask;
     
    //Add the holder to the stage
    addChild(menuHolder);
     
    //We want to keep count how many menu items have been created
    var count:Number = 0;
     
    function createMenu():void {
     
    	//Loop through all the <button></button> nodes in the XML
    	for each (var button:XML in xml.buttons.button) {
     
    		//Create a new menu item
    		var menuItem:MenuItem = new MenuItem();
     
    		//Position the menu item with some padding (space between the items)
    		menuItem.x = 0;
    		menuItem.y = count * menuItem.height * 1.05;
     
    		//Add a menu text
    		menuItem.menuText.text = button.label.toString();
     
    		//Assign a "linkTo" variable. This contains the URL where the menu will link to when clicked.
    		menuItem.linkTo = button.linkTo.toString();
     
    		//We don't want the item text field to catch mouse events
    		menuItem.mouseChildren = false;
     
    		//Add listeners for the mouse over, mouse out and click.
    		menuItem.addEventListener(MouseEvent.MOUSE_OVER, mouseOverItem);
    		menuItem.addEventListener(MouseEvent.MOUSE_OUT, mouseOutItem);
    		menuItem.addEventListener(MouseEvent.CLICK, itemClicked);
     
    		//Add the item to the menu holder
    		menuHolder.addChild(menuItem);
     
    		//Update the count (how many items have been created)
    		count++;
    	}
     
    	//Call the function that adds listeners for the whole menu
    	addMenuListeners();
    }

    The comments should explain what we are doing in each step. Shortly, we create a menu holder which will contain all the menu items. We position the holder to the same coordinates where the “myMask” is and then assign the “myMask” to be its mask.

    In the createMenu() function we loop through all the button nodes found in the XML file. We create menu item for each button found in the XML. We position the menu items vertically with some space between them and then assign menu labels and links according to the XML data. Finally, we add event listeners for the menu items, which we’ll look at next.

    ActionScript 3 - Mouse Events for the Menu Items

    These functions handle the mouse events that come from individual menu items.

    //This function is called when the mouse is over an item
    function mouseOverItem(e:Event):void {
     
    	//Get the item that dispatched the event
    	var item:MenuItem = e.target as MenuItem;
     
    	//Tween the alpha
    	TweenMax.to(item.menuFill, 0.5, {alpha: 1});
    }
     
    //This function is called when the mouse moves out from an item
    function mouseOutItem(e:Event):void {
     
    	//Get the item that dispatched the event
    	var item:MenuItem = e.target as MenuItem;
     
    	//Tween the alpha
    	TweenMax.to(item.menuFill, 1, {alpha: 0.3});
    }
     
    //This function is called when an item is clicked
    function itemClicked(e:Event):void {
     
    	//Get the item that dispatched the event
    	var item:MenuItem = e.target as MenuItem;
     
    	//Navigate to the URL that's assigned to the menu item
    	var urlRequest:URLRequest = new URLRequest(item.linkTo);
    	navigateToURL(urlRequest);
    }

    ActionScript 3 - Mouse Events for the Menu

    As you may have noticed, we have called the addMenuListeners() function in the createMenu() function. So let’s create that function and the event handlers that we need for the created event listeners.

    //This function adds mouse event listeners for the whole menu
    function addMenuListeners():void {
     
    	//Add mouse over and out listeners
    	menuHolder.addEventListener(MouseEvent.MOUSE_OVER, mouseOverMenuF);
    	menuHolder.addEventListener(MouseEvent.MOUSE_OUT, mouseOutMenuF);
     
    	//Add an ENTER_FRAME listener for the animation
    	addEventListener(Event.ENTER_FRAME, enterFrameHandler);
     
    }
     
    //We want to know when the mouse is over the menu
    var mouseOverMenu:Boolean = false;
     
    //This function is called when the mouse is over the menu
    function mouseOverMenuF(e:Event):void {
     
    	//Set mouseOverMenu to true
    	mouseOverMenu = true;
    }
     
    //This function is called when the mouse moves out from the menu
    function mouseOutMenuF(e:Event):void {
     
    	//Set mouseOverMenu to false
    	mouseOverMenu = false;
    }

    As you can see, we only want to know when the mouse is over and out from the menu. We need this, because we only want to animate the menu when the mouse is over it. Next we’ll add the last piece of code, which is the enterFrameHandler() function.

    ActionScript 3 - enterFrameHandler()

    The enterFrameHandler() is called in each frame. In that function we move the menu up and down according to the mouse position. So when the mouse is at the bottom of the menu, we move the menu holder up and vice versa.

    //This function is called in each frame
    function enterFrameHandler(e:Event):void {
     
    	//Check if the mouse is over the menu
    	if (mouseOverMenu) {
     
    		//Calculate the vertical distance from the mouse to the mask's top left corner (=registration point)
    		var distance:Number = mouseY - myMask.y;
     
    		//Calculate the percentage
    		var percentage:Number = distance / myMask.height;
     
    		//Calculate the new target y coordinate (remember that y reduces as we go up)
    		var targetY:Number = -((menuHolder.height - myMask.height) * percentage) + myMask.y;
     
    		//Tween to the new coordinate
    		TweenMax.to(menuHolder, 0.2, {y: Math.round(targetY)});
    	}
    }

    Final words

    This technique is incredibly useful in creating menus. It’s really easy and fast to change the links and menu labels by just modifying the XML file. The looks of the menu is also easily customizable to fit your needs! Check out the .fla file if you want to take a closer look at the movie. And if you have any question, pls post them in the forum, not in the comments!

    Download .fla

    discuss this topic to forum

    relation tutorial

    No information

    Category

      3D (36)
      Math Physics (18)
      3rd Party (10)
      Navigation (70)
      Actionscripting (245)
      Optimization (17)
      Animation (185)
      Projector (11)
      Audio (54)
      Special Effects (173)
      Backend (26)
      Text Effects (93)
      Drawing (34)
      Tips and Techniques (58)
      Dynamic Content (38)
      Tricks (8)
      Games (114)
      Utilities (24)
      Getting Started (99)
      Video (59)
      Interactivity (48)
      Web Design (37)

    New

    Hot