Vertical Menu with Actionscript 3 and XML
April 19, 2009 by: smonteThis 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.
Document Properties
Set the following properties for the document:
Size: 350×300
Background: white
Frame rate: 30
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.
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 Instance Name
Give the mask movie clip an instance name of “myMask”.
New Layer for Menu Item
Create a new layer named “menu item”.
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 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 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 Alpha
Set the alpha to 30% for the “Menu Fill” movie clip.
Instance Name for the Menu Fill
Give the “Menu Fill” movie clip an instance name of “menuFill”.
Layer for the Menu Text
While still inside the “Menu Item” movie clip, create a new layer named “menu text”.
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
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.
Text Field Instance Name
Give the text field an instance name of “menuText”, so we’ll be able to access it through ActionScript.
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).
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.
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.
> 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/> > Label 5>> http://tutorials.flashmymind.com> > Label 6>> http://tutorials.flashmymind.com> > Label 7>> http://tutorials.flashmymind.com> > Label 8>> http://tutorials.flashmymind.com> > Label 9>> http://tutorials.flashmymind.com> > Label 10>> http://tutorials.flashmymind.com> > Label 11>> http://tutorials.flashmymind.com> > Label 12>> http://tutorials.flashmymind.com> > Label 13>> http://tutorials.flashmymind.com> > Label 14>> http://tutorials.flashmymind.com> > Label 15>> http://tutorials.flashmymind.com> > Label 16>> http://tutorials.flashmymind.com> > Label 17>> http://tutorials.flashmymind.com> > Label 18>> http://tutorials.flashmymind.com> > Label 19>> http://tutorials.flashmymind.com> > Label 20>> http://tutorials.flashmymind.com> > Label 21>> http://tutorials.flashmymind.com> > Label 22>> http://tutorials.flashmymind.com> > Label 23>> http://tutorials.flashmymind.com> > Label 24>> http://tutorials.flashmymind.com> > > >
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.
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 = "https://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 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
Related tutorials:
Comments
18 Responses to “Vertical Menu with Actionscript 3 and XML”Leave a Reply
You must be logged in to post a comment.
Hello Friends,
I found a small bug , if the number of menuItem is less than the mask height it make some buggy output, so i put one ‘if’ condition on enterFrameHandler()
function enterFrameHandler(e:Event):void {
if (mouseOverMenu && menuHolder.height>myMask.height) {
// Calculate the vertical distance from the mouse to the mask’s top left corner //(=registration point)
var distance:Number = mouseY – myMask.y;
……………….
…………………
………..
……..
}
Now it works well thank you
Very cool tool! One question…Could you please show how to loop through and unload the xml so a new xml can be loaded without duplicate nodes? Ie, in the createMenu function??? if count>0; How to loop through and remove all the nodes in the XML? Your response is appreciated. Again, very cool…Thank you, MC
Love this tutorial, but I am trying to get the XML list when you click it, it loads another variable called “menuInfo” that contains content that will be displayed outside on the main stage in a dynamic text box called “menuInfo”. Anyone know how you get it to do this? I know where to put the line at, just having issues with syntax or how to write it.
i was wondering how do i make this work with a dynamic gallery.
i have 4+ images for each button.
so if i click btn one it pulls 4 images from a external folder via XML
if i click btn two it removes the previous images and pulls new images out of a different folder via XML.
any one? thanks.
please help me out. i have been working on this for a very long time and i really like this Menu.
I love your tutorial but for the life of me i cannot get it to work except in flash. Whenever i try to embed it in dreamweaver it never works. It is driving me crazy! It looks so sweet but I just don’t get it. If anyone knows why please feel free to tell this n00b why.
This is a great tut, but I am looking for one with collapsible submenu. Does anybody know how to update this to allow submenus?
It’s so nice. Thanks for this
Thanks its so nice. I can do some other thing from this tutorial. Its so helpful
This is the first tutorial I’ve found that will even DISPLAY XML. Thank you for the source files with comments. I’m not even trying to create a menu just display some XML and I’m pretty sure this tutorial will help me to eventually figure out at least part of what I’m trying to do.
Is just fantastic.. but I have a question, when I click on the link open in a new window, how can I change or setup the tabs to open in main window???
how can i make menu like this one?
http://flashden.net/item/floating-navigator-menu/39669?ref=ryguy
how do i make a menu like this one http://flashden.net/item/floating-navigator-menu/39669?ref=ryguy
it look so nice
Brilliant!! Thanks for the tutorial. Simple and clear explanation. One of the best AS 3 tutorial I have ever seen.
its really excellent tutorial I ll wait other topics like this…
thx
how can I call external SWF file in to master movie clip. using in XML file
———————————————-
externla SWF
externals\external.swf
———————————————-
is it the solution?
That is just awesome – I needed exactly that. All I need to do now is build a real scrollbar for it. When I get that figured out I might do a quick tut and link from here.
nice tutorial, seems its always a good way to make things like that dynamic
Very cool. Thank you