• home
  • forum
  • my
  • kt
  • download
  • Colorful Menu with XML and ActionScript 3

    Author: 2009-07-14 09:12:50 From:

    I decided that there is still room for at least one more Flash menu tutorial in the web. So in this tutorial I’ll show you how you can create a nice colorful Flash XML menu with ActionScript 3. Check out the end result!

    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

    Start your Flash and create a new Flash ActionScript 3 document.

    New Flash document

    Menu Item Shape

    Draw a rectangle on the stage with the following properties.

    width: 350 px
    height: 45 px
    stroke: none
    fill: 0xffffff

    Menu item shape

    Menu Item Movie Clip

    Convert the rectangle to a movie clip. Name it “Menu Item” and set the registration point to the top left corner. Also link the movie clip to a class named “MenuItem”. We linkage the movie clip so we can dynamically create these movie clips via ActionScript 3.

    Menu item movie clip

    Menu Item Background

    Double click the menu item movie clip on the stage. You should now be “inside” the “Menu Item” movie clip.

    Inside Menu Item

    Convert the rectangle shape to a movie clip. Name it “Menu Item Fill” and set the registration point to the top left corner. As you might have guessed, this movie clip acts as the background of a menu item. It needs to be a movie clip because we’ll be animating it via ActionScript later on the tutorial.

    Menu fill movie clip

    Background Instance Name

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

    Menu Item Fill instance name

    Menu Item Text Field

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

    Menu Text Layer

    In the “menu text” layer, create a new dynamic text field so that it’s positioned on top of the item fill movie clip (”itemBackground”). Set the following properties.

    instance name: itemText
    width: 340 px
    height: 30 px
    family: Berlin Sans
    size: 18 pt
    color: #000000
    format: align center

    Menu Item text properties

    Character Embedding

    We need to embed some characters so the text will look smooth in the movie. So click the “Character Embedding” button and select lowercase, uppercase and numerals. If you need more characters in your movie select them also.

    Flash Character embedding

    Final Stage Adjustment

    Go back to the main timeline and remove the “Menu Item” movie clip from the stage (so now your stage should be all empty).

    The XML file

    Before we move to ActionScript 3, 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>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>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>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>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>Add more buttons with XML!</label>
                <linkTo>http://tutorials.flashmymind.com</linkTo>
            </button>
     
        </buttons>
     
    </menu>

    The XML structure is simple. We simply give each button (= “Menu Item”) a label and an URL where the button should link to. Save this file as “colorful_menu.xml”. Feel free to change the labels and URLs!

    ActionScript - Actions Panel

    Open up the actions panel (hit F9 if it’s not visible).

    Frame for ActionScript

    ActionScript - Loading XML

    First we need to load the XML file into our Flash movie. In the actions panel, type the following.

    //Import TweenMax
    import gs.*;
     
    //The path for the XML file (use your own here)
    var xmlPath:String = "http://flashmymind.com/SWF/colorful_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 should be pretty straightforward. We first import TweenMax so we can use it later on. Then we use a URLLoader to load the XML. We call the function xmlLoaded() when the loading is done. In the xmlLoaded() function we create an XML object from the loaded data and call the function createMenu(). Let’s look at that next.

    ActionScript - createMenu()

    Here is the code for the createMenu() function.

    //Create a menu holder that will contain all the menu items
    var menuHolder:MovieClip = new MovieClip();
     
    //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
    		menuItem.x = 0;
    		menuItem.y = count * menuItem.height;
     
    		//Add a menu text
    		menuItem.itemText.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();
    }

    Before the function we create a holder that will contain all the menu items that we will create. In the function we loop through the “button” nodes found in the XML data. For each button found we create a menu item and set a menu text and assign an URL. We position the menu items vertically. Next we look at the event handlers for the mouse events assigned to each menu item.

    ActionScript - Mouse Events for the Menu Items

    The following function catch different mouse events for the 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 color
    	TweenMax.to(item.itemBackground, 0.5, {tint: Math.random()*0xffffff});
    }
     
    //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 color
    	TweenMax.to(item.itemBackground, 1.5, {tint: 0xffffff});
    }
     
    //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);
    }

    So when the cursor moves over or out of an item we tween the background color. Note that we tween to a random color when the mouse is over an item! When an item is clicked we navigate to the assigned URL. Not hard, eh?

    ActionScript - addMenuListeners()

    Remember that we called the function addMenuListeners() in the createMenu() function. Let’s look at that.

    //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 also want to catch when the mouse is over or out of the whole menu. We do this because we only want to animate the menu when the mouse is actually over it. We use a boolean value mouseOverMenu to tell when the mouse is over the menu. Finally, let’s look at the function enterFrameHandler() where all the movement happens!

    ActionScript - enterFrameHandler

    Type the following code for the animation.

    //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 top of the stage
    		var distance:Number = mouseY;
     
    		//Calculate the percentage
    		var percentage:Number = distance / stage.stageHeight;
     
    		//Calculate the new target y coordinate (remember that y reduces as we go up)
    		var targetY:Number = -((menuHolder.height - stage.stageHeight) * percentage);
     
    		//Tween to the new coordinate
    		TweenMax.to(menuHolder, 0.2, {y: Math.round(targetY)});
    	}
    }

    Here we calculate how far the mouse is from the top of the stage. Then we animate the holder according to the mouse position. So when the mouse moves down, we animate the holder up and vice versa.

    Final words

    That’s it for this tutorial. Hope you liked it! Check out the .fla file for further assistance. Remember that if you have any questions, post them in the forum, not in comments!

    Download .fla

    discuss this topic to forum

    relation tutorial

    No information

    Category

      3D (36)
      Math Physics (18)
      3rd Party (10)
      Navigation (70)
      Actionscripting (247)
      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