Colorful Menu with XML and ActionScript 3

April 23, 2009 by: smonte
Flash XML menu

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.

>
 
    >
 
        >
            >Home>
            >http://tutorials.flashmymind.com>
        >
        >
            >Tutorials>
            >http://tutorials.flashmymind.com/complete-list-of-flash-and-actionscript-3-tutorials/>
        >
        >
            >Forum>
            >http://tutorials.flashmymind.com/forum/>
        >
        >
            >About>
            >http://tutorials.flashmymind.com/about/>
        >
        >
            >Home>
            >http://tutorials.flashmymind.com>
        >
        >
            >Tutorials>
            >http://tutorials.flashmymind.com/complete-list-of-flash-and-actionscript-3-tutorials/>
        >
        >
            >Forum>
            >http://tutorials.flashmymind.com/forum/>
        >
        >
            >About>
            >http://tutorials.flashmymind.com/about/>
        >
        >
            >Home>
            >http://tutorials.flashmymind.com>
        >
        >
            >Tutorials>
            >http://tutorials.flashmymind.com/complete-list-of-flash-and-actionscript-3-tutorials/>
        >
        >
            >Forum>
            >http://tutorials.flashmymind.com/forum/>
        >
        >
            >About>
            >http://tutorials.flashmymind.com/about/>
        >
        >
            >Home>
            >http://tutorials.flashmymind.com>
        >
        >
            >Tutorials>
            >http://tutorials.flashmymind.com/complete-list-of-flash-and-actionscript-3-tutorials/>
        >
        >
            >Forum>
            >http://tutorials.flashmymind.com/forum/>
        >
        >
            >About>
            >http://tutorials.flashmymind.com/about/>
        >
        >
            >Home>
            >http://tutorials.flashmymind.com>
        >
        >
            >Tutorials>
            >http://tutorials.flashmymind.com/complete-list-of-flash-and-actionscript-3-tutorials/>
        >
        >
            >Forum>
            >http://tutorials.flashmymind.com/forum/>
        >
        >
            >About>
            >http://tutorials.flashmymind.com/about/>
        >
        >
            >Add more buttons with XML!>
            >http://tutorials.flashmymind.com>
        >
 
    >
 
>

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 = "https://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  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

  • Digg
  • Sphinn
  • del.icio.us
  • Mixx

Related tutorials:

  1. Vertical 3D Carousel with ActionScript 3 and XML
  2. Advanced XML Menu with ActionScript 3
  3. Creating a Menu via XML
  4. Vertical Menu with Actionscript 3 and XML
  5. Menu with ActionScript 3

Comments

3 Responses to “Colorful Menu with XML and ActionScript 3”
  1. nike shox says:

    Thanks for your nice post!!!

    Log in to Reply
  2. dragonfly says:

    Need help with animating the dynamic text field!

    The idea is next – when

    menuItem.addEventListener(MouseEvent.MOUSE_OVER, mouseOverItem);
    function mouseOverItem(e:Event):void {
    var item:MenuItem = e.target as MenuItem;
    TweenMax.to(item.menuFill, 0.5, {startAt:{scaleY:-0.5, tint:0xa3a276}, scaleY:1, ease:Quad.easeOut});
    }
    It’s ok with the menuFill object, but I guess the menuItem.mouseChildren = false; makes the task impossible.

    Please help! Mybe there’s some other term to make the text animated with button???

    Log in to Reply
  3. Connie H. says:

    Thanks — this straightened me out on what was happening with the URL links. Plus, it’s a very cute menu!

    Log in to Reply

Leave a Reply

You must be logged in to post a comment.