Creating a Menu via XML

February 6, 2009 by: smonte

In this tutorial, I’ll cover a basic XML technique, that you can use when building a menu. With XML, it’s very easy and fast to modify the menu labels etc.

Intro

In this tutorial, I’ll cover a basic XML technique, that you can use when building a menu. With XML, it’s very easy and fast to modify the menu labels etc.

Setting up the environment

1. First, let’s create the XML file. Download the XML file site.xml.

2. Let’s move to Flash IDE. Create a new document of the size you want.

3. Let’s create a menu button. Draw a rectangle of size 100×30. Convert it into a movie clip named “menuItem”. Set the registration point to the top left corner.

4. In the movie clip, create a new layer and add a text field like in the pictures below.

Output

Output

5. Give the text field an instance name of “menuLabel”. Apply same settings as below.

Output

6. Remove the movie clip from the stage, so that it’s empty. Now we are ready for some ActionScripting.

7. Linkage the movie clip to a class “MenuItem”.

Moving into ActionScript 3

8. Create an actions layer. First we set up some variables and load the XML. Type the following.

//Imports needed for animation
import fl.transitions.Tween;
import fl.transitions.easing.*;
 
//XML file path
//You can use the following path as well if you want...
var xmlPath:String = "https://flashmymind.com/SWF/site.xml";
 
//The XML data will be inserted into this variable
var settingsXML:XML;
 
//Array used for the tween so they won't get garbage collected
var tweensArray:Array = new Array();
//Used later when we animate the buttons
var buttonTween:Tween;
 
// Load the XML file
var loader = new URLLoader();
loader.load (new URLRequest(xmlPath));
loader.addEventListener (Event.COMPLETE, xmlLoaded);

9. Nothing hard here, eh? Now let’s add the xmlLoaded function.

//This function is called when the XML file is loaded
function xmlLoaded (e:Event):void {
 
        //Make sure we're not working with a null loader
        if ((e.target as URLLoader) != null ) {
                //Insert the loaded data to our XML variable
                settingsXML = new XML(loader.data);
                settingsXML.ignoreWhitespace = true;
                //Call the function that creates the whole menu
                createMenu ();
        }
 
}

The comments should explain enough about what’s happening. The createMenu() function is where all of the magic happens.

Creating the Menu

10. Now that we have loaded our XML, type the following.

function createMenu ():void {
        //This will be used to represent a menu item
        var menuItem:MenuItem;
        //Counter
        var i:uint = 0;
 
        //Loop through the links found in the XML file
        for each (var link:XML in settingsXML.links.link) {
 
                menuItem = new MenuItem();
 
                //Insert the menu text (link.@name reads the link's "name" attribute)
                menuItem.menuLabel.text = link.@name;
 
                //If the text is longer than the textfield, autosize so that the text 
                //is treated as left-justified text
                menuItem.menuLabel.autoSize = TextFieldAutoSize.LEFT;
 
                //Insert the menu button to stage
                menuItem.x = 20;
                menuItem.y = 30 + i*40;
 
                //Make the button look like a button (hand cursor)
                menuItem.buttonMode = true;
                menuItem.mouseChildren = false;
 
                //Add event handlers (used for animating the buttons)
                menuItem.addEventListener (MouseEvent.MOUSE_OVER, mouseOverHandler);
                menuItem.addEventListener (MouseEvent.MOUSE_OUT, mouseOutHandler);
 
                addChild (menuItem);
 
                //Increment the menu button counter, so we know how many buttons there are
                i++;
        }
}

11. Now we have our menu buttons set up in the stage. One more thing to do, the animation when the user rolls over and out! Type the following.

//Function is called when the mouse is over a menu button
function mouseOverHandler (e:Event):void {
 
        //Double the width
        buttonTween = new Tween(e.target, "scaleX", Elastic.easeOut, 1, 2, 1, true);     
}
 
//Function is called when the mouse moves out from the menu button
function mouseOutHandler (e:Event):void {
 
        //Tween back original scale
         buttonTween = new Tween(e.target, "scaleX", Elastic.easeOut, e.target.scaleX, 1, 1, true);
 
}

You’re done! Test your movie. You should have similar menu as in the previous page

Final Words

As you can see, loading and using XML is not hard at all. If you want to change the menu labels, you just need to modify the XML file and you’re done.

Update 1.7.2008

There have been some questions about how to add mouse click functionality to the menu items. Check out this thread to see how to use these buttons as links.

Final Code

//Imports needed for animation
import fl.transitions.Tween;
import fl.transitions.easing.*;
 
//XML file path
//You can use the following path as well if you want...
var xmlPath:String = "https://flashmymind.com/SWF/site.xml";
 
//The XML data will be inserted into this variable
var settingsXML:XML;
 
//Array used for the tween so they won't get garbage collected
var tweensArray:Array = new Array();
//Used later when we animate the buttons
var buttonTween:Tween;
 
// Load the XML file
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 we're not working with a null loader
        if ((e.target as URLLoader) != null ) {
                //Insert the loaded data to our XML variable
                settingsXML = new XML(loader.data);
                settingsXML.ignoreWhitespace = true;
                //Call the function that creates the whole menu
                createMenu ();
        }
 
}
 
function createMenu ():void {
        //This will be used to represent a menu item
        var menuItem:MenuItem;
        //Counter
        var i:uint = 0;
 
        //Loop through the links found in the XML file
        for each (var link:XML in settingsXML.links.link) {
 
                menuItem = new MenuItem();
 
                //Insert the menu text (link.@name reads the link's "name" attribute)
                menuItem.menuLabel.text = link.@name;
 
                //If the text is longer than the textfield, autosize so that the text is 
                //treated as left-justified text
                menuItem.menuLabel.autoSize = TextFieldAutoSize.LEFT;
 
                //Insert the menu button to stage
                menuItem.x = 20;
                menuItem.y = 30 + i*40;
 
                //Make the button look like a button (hand cursor)
                menuItem.buttonMode = true;
                menuItem.mouseChildren = false;
 
                //Add event handlers (used for animating the buttons)
                menuItem.addEventListener (MouseEvent.MOUSE_OVER, mouseOverHandler);
                menuItem.addEventListener (MouseEvent.MOUSE_OUT, mouseOutHandler);
 
                addChild (menuItem);
 
                //Increment the menu button counter, so we know how many buttons there are
                i++;
        }
}
 
//Function is called when the mouse is over a menu button
function mouseOverHandler (e:Event):void {
 
        //Double the width
        buttonTween = new Tween(e.target, "scaleX", Elastic.easeOut, 1, 2, 1, true);     
}
 
//Function is called when the mouse moves out from the menu button
function mouseOutHandler (e:Event):void {
 
        //Tween back original scale
         buttonTween = new Tween(e.target, "scaleX", Elastic.easeOut, e.target.scaleX, 1, 1, true);
 
}
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx

Related tutorials:

  1. Advanced XML Menu with ActionScript 3
  2. Colorful Menu with XML and ActionScript 3
  3. XML Pages with ActionScript 3
  4. Creating a Web Portfolio
  5. Vertical 3D Carousel with ActionScript 3 and XML

Comments

20 Responses to “Creating a Menu via XML”
  1. hohon says:

    how to link this button to link another swf file….sory im noob..LOL

    Log in to Reply
  2. Lacey says:

    Great tutorial, thank you.

    Log in to Reply
  3. frood says:

    I don’t get this tutorial. It’s a menu tutorial, but nowhere does it explain how to set the links to make the menu work…..

    How do i add the links to the xml file?
    Any help would be grateful.
    thanks

    Log in to Reply
  4. Jimmy says:

    This was the worst tut I’ve ever seen.

    Log in to Reply
  5. Rebu says:

    I have a question.

    Why does the text move along with the orange menu backgorund? (the tween is only attached to the menuItem)

    And why does it only move a little bit, not 2 times like the orange background?

    Thank You!

    Log in to Reply
  6. Machillax says:

    TypeError: Error #1010: A term is undefined and has no properties.
    at menu_fla::MainTimeline/createMenu()
    at menu_fla::MainTimeline/xmlLoaded()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

    I got this in the output, could You please help

    Log in to Reply
  7. Justin says:

    Will,

    its not working for you becuase you skipped a step:
    7. Linkage the movie clip to a class “MenuItem”.

    you have to set the linkage properties in your library
    for the menuItem clip. Its an important step.

    Mike,

    do you know what the “bugs” are? cause it worked fine for
    me, if you follow the steps correctly. Perhaps offering some
    of your knowledge of ActionScript would be better than negativity
    towards someone who is putting up good tutorials on how to learn
    an otherwise tough language.

    Log in to Reply
  8. mike says:

    well.this tut is quite dumb. you could correct at least those bugs. or you don’t understand where they are…don’t ya?

    Log in to Reply
  9. Wil says:

    Hi,

    Thanks for the tutorial.

    I seem to be getting the following errors. I have copied all the code from above and still seem to get the error. Any ideas / help/ advice much appreciated

    Scene 1, Layer ‘actions’ 1, Frame 1, Line 38 1046: Type was not found or was not a compile-time constant: MenuItem.

    Log in to Reply
  10. Erik says:

    ey all, I am upgrading myself to AS3 so these simple tutorials really help me along,

    I came across the click function somewhere in the topics on the forum, i will post it here since it is something people really want to know when doing this tut.

    change in XML:

    Change in AS (MouseEvent, type this in the createMenu() function)

    //Assign an url to a menu item
    menuItem.linkTo = link.@url;
    menuItem.addEventListener (MouseEvent.CLICK, mouseClicked);

    Change in AS (event function, put it underneath the other functions)

    function mouseClicked(e:Event):void {
    var targetURL:String = e.target.linkTo;
    var urlRequest:URLRequest = new URLRequest(targetURL);
    navigateToURL(urlRequest);
    }

    Log in to Reply
  11. smonte says:

    Hey,

    Check out external classes tutorial to see how to linkage a movie clip (step 4).

    Log in to Reply
  12. mrstex says:

    Hi i’m not understanding what does it mean to “link to a class name MenuItem” i’m not so good in ActionScript can u explain that for me please?

    Thanks A lot
    Stex

    Log in to Reply
  13. smonte says:

    Nice that you got it working. I checked your link. I would definitely change the frame rate to 30, it would feel much smoother! Take care.

    Log in to Reply
  14. smonte says:

    Hmm, sounds like you have some issues with the URLs. So maybe try to insert full paths, e.g. “http:://domain.com/your_path”. Hope it helps!

    Log in to Reply
    • Thanks, but it was more complex than that with this particular movie. I had to place the links in the xml file and put the add URL part into the create function,
      //Assign an url to a menu item
      menuItem.linkTo = link.@url;
      menuItem.addEventListener (MouseEvent.CLICK, mouseClicked);
      then I had to get the mouseClicked function in the right place. Misplaced that at first and got an entirely different error about null object or loader.

      It is now working here:
      http://www.spiderpost.com/

      I still need to change the names and make the links what I actually want them to be. Thanks.

      Log in to Reply
  15. Hi. Great tutorials! I have been having some of my students devour this stuff and they love it. I am having issues with inserting the flash movies into web pages. Some of the files won’t work when embedded in the page. However, when launched directly in the flash player and under test they work fine. Am I missing something here?

    Thanks for any insight you can provide.

    Log in to Reply

Leave a Reply

You must be logged in to post a comment.