1. Code
  2. Coding Fundamentals
  3. XML

Create a Super Modern Elastic Menu in AS3

Scroll to top
16 min read

Sometimes you just want to be very modern about your website. And how better to show people how cool you are as a flash programmer than to make them experience it themselves? In this tutorial I will show you how to create a modern menu with spring-like buttons. We'll even make it customizable from xml!

Preview

Let's take a quick look at what we're working towards:

Step 1: Preparing the document

Create a new ActionScript 3 flash file and set the dimensions to 600 x 200 pixels. We're setting these dimensions in order to have space for the buttons to follow the mouse. Set the framerate to 25 and the DocumentClass to ElasticMenu, a class which we will create after the design.

Let's make a background gradient which will be the base for our button. Create a rectangle and make it 150 x 40px. The size doesn't matter at this time, because we will resize the rectangle to match the text size of the button.

I can hear you asking: why not create a rectangle programatically with Sprite.graphics.drawRectangle()? I'll show you why I chose this path. The reason behind making a movieclip on the stage is that we can actually cut through the rectangle to create a cool cut-out button like in this preview:

I'm not going into how to make this example here, but this method's better in case you want to spice up the background of the button. That's just a tip.

Step 2: Creating the Background Movieclip

Select the rectangle you just created and press F8 (Modify > Convert to Symbol) to make the background graphic and check Export for ActionScript. Give this movieclip the class name "GradBackground". We will use this class name from ActionScript.

Step 3: The XML File

Now we'll create the xml file to hold our configuration. From this file the flash movie will get the button name, the link location and the color. Create a new file next to the .fla source and name it menu.xml with the following:

1
2
<?xml version="1.0" encoding="utf-8"?>
3
    <menu>
4
    
5
        <button>
6
            <name>Home</name>
7
            <url>http://flash.tutsplus.com</url>
8
            <color>0xff0000</color>
9
        </button>
10
        
11
        <button>
12
            <name>About us</name>
13
            <url>https://code.tutsplus.com</url>
14
            <color>0xccff00</color>
15
        </button>
16
        
17
        <button>
18
            <name>Projects</name>
19
            <url>https://design.tutsplus.com</url>
20
            <color>0x446677</color>
21
        </button>
22
        
23
        <button>
24
            <name>News</name>
25
            <url>https://design.tutsplus.com</url>
26
            <color>0x004488</color>
27
        </button>
28
        
29
        <button>
30
            <name>Forum</name>
31
            <url>https://photography.tutsplus.com</url>
32
            <color>0x2244ff</color>
33
        </button>
34
        
35
        <button>
36
            <name>Contact</name>
37
            <url>https://music.tutsplus.com</url>
38
            <color>0x232323</color>
39
        </button>
40
    
41
    </menu>

What happens here? We're creating a <button> node for every button. You can add as many as you need, but not too many because they won't have space to "be elastic" :) In every button node there is a name tag, a url tag and a color tag, pretty basic.

Step 4: Begin the Programming

Now let's get to building the actual flash menu. Create a new ActionScript file and name it ElasticMenu.as. For speed I have used the wildcard * to import all the classes in the package. After you finish the flash menu, you can modifiy the imports to only include what you need, to make the filesize smaller. Create the usual package and class name ElasticMenu with the required variables:

1
2
package {
3
4
    import flash.display.*;
5
    import flash.text.*;
6
    import flash.net.*;
7
    import flash.events.*;
8
    import flash.utils.Timer;
9
10
	public class ElasticMenu extends MovieClip {
11
12
	var xml:XML;
13
	var buttons:Array;
14
	var tm:Timer;
15
	var maxdist:Number = 50;
16
17
	} 
18
19
}

The xml variable will hold the actual xml loaded from the menu.xml file. The buttons variable is an array that will hold the button references.

The tm is a timer that will take care of the actual check for distance.

The maxdist variable will define at what distance the button will break from the mouse and return to its place.

Step 5: XML Loading and Handling

Ok, let's create the constructor function, add the load operations and process the xml:

1
2
public function ElasticMenu(){
3
	var req = new URLLoader();
4
	req.addEventListener( Event.COMPLETE, xml_loaded );
5
	req.load( new URLRequest('menu.xml') );
6
	buttons = new Array();
7
	tm = new Timer( 40 );
8
	tm.addEventListener( TimerEvent.TIMER, check_buttons );
9
}
10
		
11
private function xml_loaded( e:Event ){
12
	xml = XML( e.target.data );
13
	createButtons();
14
}

What's happening here? We create a URLRequest object and add a complete event handler that will trigger the xml_loaded function when the xml is loaded.

We initialize the buttons array and the timer, and we tie the TIMER event to the check_buttons() function. This is the function that will check for the distance of the buttons. Once the xml is loaded, we pass it to the xml variable and build the buttons with the createButtons() function, which we will create next.

Step 6: The createButtons Function

Continue by creating the buttons and position them on the stage programtically:

1
2
3
public function createButtons(){
4
	var sectw = (stage.stageWidth/(xml..button.length()+1) );
5
	for( var i=0; i< xml..button.length(); i++){
6
		var m = new ElasticButton();
7
		m.x = sectw + (sectw*i);
8
		m.y = stage.stageHeight/2;
9
		m.init( xml..button[i] );
10
		addChild( m );
11
		buttons.push( m );
12
	}
13
	tm.start();
14
}

Ok, so we are defining the sectw variable, which is the stage split into the number of buttons plus one. Why? Because we will arrange the buttons to be exacly the same distance from each other and occupy all the stage width. To better understand this, look at the following image:

Because we are centering the buttons on x and y axis, they will end up being at equal distances from one another. Then we are creating a for loop, insidew which we define every button as a new ElasticButton class, which we will code shortly. We place every button at sectw distance from one another and set their y to half the stage to center them. Then we add them to the stage and push them into the buttons array, for later use. But there is another function we call on the button which we'll define in the ElasticButton class, which we pass the current xml button node.

Step 7: The checkButtons Function

Let's continue with the main function triggered every 40 miliseconds by the timer:

1
2
3
private function check_buttons( e:TimerEvent ){
4
	for( var b in buttons ){
5
		if( buttons[b].dragging ){
6
			buttons[b].x = mouseX;
7
			buttons[b].y = mouseY;
8
			if( buttons[b].getDistance() > maxdist ){
9
				buttons[b].reset();
10
			}
11
		}
12
	}
13
}

Ok, let's quickly explain what's going on here so we can move on to the ElasticButton class:

First of all, we loop through all the buttons in the array and for each one we check if they have a dragging property with the value "true". Basically if the mouse is over the button and if "yes", we check if the getDistance() method of the ElasticButton class is higher than the maxdist variable. If it is higher, we call a reset() function on the button. We don't know anything yet about these functions.

Step 8: Making the ElasticButton Class

OK, finally the class we have all been waiting for, the button class. This is where all the important things happen: finding out the distance, creating the text, background and calling reset() to return the button to its location.

1
2
3
package {
4
	
5
	import flash.display.*;
6
	import flash.text.*;
7
	import flash.net.*;
8
	import flash.events.*;
9
	import flash.geom.ColorTransform;
10
	import fl.transitions.Tween;
11
	import fl.transitions.TweenEvent;
12
	import fl.transitions.easing.*;
13
	import fl.motion.Color;
14
	
15
	
16
	public class ElasticButton extends MovieClip {
17
		
18
		var origin:Object;
19
		var textfield:TextField;
20
		var tf:TextFormat;
21
		var dragging:Boolean = false;
22
		var bg:Sprite;
23
		var url:String;
24
		var twx:Tween;
25
		var twy:Tween;
26
		var padding:Number = 8;
27
		var color:uint;
28
		var msk:Sprite;
29
		
30
		public function ElasticButton(){
31
			//do nothing

32
		}
33
		
34
		
35
	}
36
}

Let me explain the lines:

You'll find that apart from importing the normal classes, we also import fl.transitions.Tween and TweenEvent, easing and the fl.motion.Color classes. We need the tween classes to tween the movie back to its origin and the color class to tint the background to the color in the xml.

We have a couple of variables here:

The origin object is an object which will hold the x and y position of the button. I could have made it a flash.geom.Point object but I'm too lazy to include another class for 2 variables!

We have a textfield variable which will hold the button label textfield, the tf variable which is a TextFormat object for text styling, the known dragging propery, a bg var which will be the background movieclip, a string with the url for the button, two variables to hold the tweens, a padding variable which will make the button a bit bigger, the color object and a msk var which will be a mask for the movieclip. We need this to make the rounded corner you saw in the preview!

Step 9: init() Function

Let's do the init function, triggered by our parent class:

1
2
public function init( node ){
3
	textfield = new TextField();
4
	tf = new TextFormat();
5
	tf.size = 14;
6
	tf.font = '_sans';
7
	tf.bold = true;
8
	tf.color = 0xffffff;
9
	tf.align = TextFormatAlign.CENTER;
10
	textfield.defaultTextFormat = tf;
11
	textfield.text = node..name;
12
	textfield.width = 65;
13
	textfield.height = 20;
14
	textfield.x = -(textfield.width / 2 );
15
	textfield.y = -(textfield.height / 2 );
16
	textfield.mouseEnabled = false;
17
	addChild( textfield );
18
	origin = new Object();
19
	origin.x = this.x;
20
	origin.y = this.y;
21
	color = node..color;
22
	createBG();
23
	url = node..url;
24
	dragging = false;
25
	this.buttonMode = true;
26
	this.addEventListener( MouseEvent.MOUSE_OVER, mouse_over );
27
	this.addEventListener( MouseEvent.CLICK, mouse_click );
28
}

There is a lot already!

We create the textfield, assign it a textformat with certain properties (I won't get into details here), set the colour to white, because the backgrounds will tend to be darker, we give it the text from the node passed as a parameter. Pretty standard.

It's best to create a width and align the text to center so that different words will be beautifully aligned. You just have to make sure not to include a very long word, or the button will look ugly!

Next we have an interesting positioning of the textfield. We set the x to minus half the width and the y to minus half the height of the textfield, thus aligning the textfield exactly in the center. We need this in order to have a uniform calculation of maximum distance.

We set mouseEnabled to false for the textfield, to disable the mouse rolling off the button. I looked for this property for a whole day when I first started AS3 :)

The origin object is initialized next and we create x and y properties with the x and y of the current movieclip (the ElasticButton class). When the button goes beyond the maxdist, we will return the button to these origin points.

There are a couple of more things going on here: We hold the color from the xml node in the color var, we hold the url of the button in the url var amd we call a createBG() function which we are yet to code.

We set dragging to false, buttonMode for the current ElasticButton to true and create the mouse over and click handlers.

Step 10: createBG Function

This function will take care of making the background and tint it according to the color in the xml:

1
2
public function createBG(){
3
	bg = new GradBackground();
4
	var dbpad = padding*2;
5
	bg.width = textfield.width+dbpad;
6
	bg.height = textfield.height+dbpad;
7
	bg.x = -( (textfield.width+dbpad)/2);
8
	bg.y = -( (textfield.height+dbpad)/2);
9
	addChild(bg);
10
	var col = new Color(1,1,1,1);
11
	col.setTint( color, 0.4 );
12
	bg.transform.colorTransform = col;
13
	setChildIndex( bg, 0 );
14
}

Here we make a GradBackground class, which is the movieclip we created in the fla source and give it the class name GradBackground. We set the width and height of the movieclip to the textfield width plus a variable dbpad. You'll notice that I defined this variable for speed, so that I don't type (padding * 2). Defining a new variable with the precomputed double padding is faster than calling this operation many times. We have to take care of the CPU too!

Why am I adding a padding variable? So that the button is bigger than the textfield. Look at this image to get a better understanding:

I am also centering the bg movieclip like I did with the textfield: I set the x to minus half the height and minus half the width of the bg movieclip.

Next I create a new Color with default attributes (rgb and alpha 1) and later use the setTint() function to make it a shade of the xml color. Because the Color class is a subclass of ColorTransform class, we can pass this colour directly to the movieclip transform.colorTransform object.

Lastly, we set the bg movieclip the depth 0, so everything will be above the background.

Step 11: Event Handlers

I'll quickly go through the event handlers:

1
2
private function mouse_over( e:MouseEvent ){
3
	dragging = true;
4
}
5
6
7
8
private function mouse_click( e:MouseEvent ){
9
	navigateToURL( new URLRequest( url ) );
10
}

The event handlers are pretty simple: I set the dragging to true when the mouse hovers over the button. For the click handler I use the navigateToURL() function to go to the url requested. If you are building a flash site, this is where the action for page change would go.

Step 12: The getDistance Function

This is the most important function in the menu. Remember, we're calling the getDistance function to see if it's bigger than the maxdist var so we can reset the button. We're using the algebraic equation of Pitagora to find the distance between 2 points:

1
2
public function getDistance(){
3
	return Math.sqrt( (this.x-origin.x)*(this.x-origin.x) + (this.y-origin.y)*(this.y-origin.y) );
4
}

This will give us the distance between the button x and y and the origin x and y. That's why we hold the origin variable.

Step 13: The Reset Function

This function is triggered when the distance from the origin is too high. At that point we tween the button back to its origin:

1
2
3
public function reset(){
4
	dragging = false;
5
	twx = new Tween( this, 'x', Elastic.easeOut, this.x, origin.x, 0.4, true );
6
	twy = new Tween( this, 'y', Elastic.easeOut, this.y, origin.y, 0.4, true );
7
}

We set the dragging to false and create two tweens; one for the x and one for the y. We could have used another tweening library, used only one tween and passed an array to the tweening function, but the built-in Tween class from AS3 doesn't support multiple properties, as far as I'm aware.

Step 14: Rounding the Buttons

Let me show you, as a bonus, how to make the first and last button round, like you saw in the preview. We create a new function makeStartButton() where we will build the rounded mask:

1
2
public function makeStartButton(){
3
	msk = new Sprite();
4
	msk.graphics.beginFill(0x000000,1);
5
	msk.graphics.moveTo( 0, padding );
6
	msk.graphics.curveTo( 0, 0, padding, 0 );
7
	msk.graphics.lineTo( (padding*2)+textfield.width, 0 );
8
	msk.graphics.lineTo( (padding*2)+textfield.width, (padding*2)+textfield.height );
9
	msk.graphics.lineTo( 0, (padding*2)+textfield.height );
10
	msk.graphics.lineTo( 0, padding );
11
	msk.graphics.endFill();
12
	msk.x = bg.x;
13
	msk.y = bg.y;
14
	addChild( msk );
15
	bg.mask = msk;
16
}

Ok, this has to be explained:

We create a new Sprite and use the graphic's class beginFill() to make a fill, the colour doesn't matter. In order to understand what is going on let's look at this image:

We construct the rounded background mask and add it to the displayList, setting it as a mask for the bg movieclip

Step 15: Rounding the Second Button

We use the same procedure, now with the curve on the right:

1
2
public function makeEndButton(){
3
	var dbpad = padding*2;
4
	msk = new Sprite();
5
	msk.graphics.beginFill(0x000000,1);
6
	msk.graphics.lineTo( textfield.width + padding, 0 );
7
	msk.graphics.curveTo( textfield.width + dbpad, 0, textfield.width + dbpad, padding );
8
	msk.graphics.lineTo( dbpad + textfield.width, dbpad + textfield.height );
9
	msk.graphics.lineTo( 0, dbpad + textfield.height );
10
	msk.graphics.lineTo( 0, padding );
11
	msk.graphics.endFill();
12
	msk.x = bg.x;
13
	msk.y = bg.y;
14
	addChild( msk );
15
	bg.mask = msk;
16
}

You'll see that it's the same technique, we just make the curve on the right and we add the mask to the bg movieclip.

Step 16: The Final Touch

We need to modify the ElasticMenu class to call these two functions on the first and the last buttons. In the createButtons() we make the following modifications (lines 8 - 13):

1
2
public function createButtons(){
3
	var sectw = (stage.stageWidth/(xml..button.length()+1) );
4
	for( var i=0; i< xml..button.length(); i++){
5
		var m = new ElasticButton();
6
		m.x = sectw + (sectw*i);
7
		m.y = stage.stageHeight/2;
8
		m.init( xml..button[i] );
9
		if( i == 0 ){
10
			m.makeStartButton();
11
		}
12
		if( i == xml..button.length()-1){
13
			m.makeEndButton();
14
		}
15
		addChild( m );
16
		buttons.push( m );
17
	}
18
	tm.start();
19
}

So if the variable i is 0 (if it's the first button) or if i is the xml..button.length() - 1 (if it's the last) we call the respective function.

Just remember, if you encounter any error, that the functions we call from the parent class, ElasticMenu have to be public in the ElasticButton class, otherwise you will get an error that the function does not exist!

That's it! This is the whole code for the ElasticMenu class:

1
2
package {
3
	import flash.display.*;
4
	import flash.text.*;
5
	import flash.net.*;
6
	import flash.events.*;
7
	import flash.utils.Timer;
8
	
9
	
10
	public class ElasticMenu extends MovieClip {
11
		
12
		var xml:XML;
13
		var buttons:Array;
14
		var tm:Timer;
15
		var maxdist:Number = 50;
16
		var line:Sprite;
17
		
18
		public function ElasticMenu(){
19
			var req = new URLLoader();
20
			req.addEventListener( Event.COMPLETE, xml_loaded );
21
			req.load( new URLRequest('menu.xml') );
22
			buttons = new Array();
23
			tm = new Timer( 40 );
24
			tm.addEventListener( TimerEvent.TIMER, check_buttons );
25
		}
26
		
27
		private function xml_loaded( e:Event ){
28
			xml = XML( e.target.data );
29
			createButtons();
30
		}
31
		
32
		public function createButtons(){
33
			var sectw = (stage.stageWidth/(xml..button.length()+1) );
34
			for( var i=0; i< xml..button.length(); i++){
35
				var m = new ElasticButton();
36
				m.x = sectw + (sectw*i);
37
				m.y = stage.stageHeight/2;
38
				m.init( xml..button[i] );
39
				if( i == 0 ){
40
					m.makeStartButton();
41
				}
42
				if( i == xml..button.length()-1){
43
					m.makeEndButton();
44
				}
45
				addChild( m );
46
				buttons.push( m );
47
			}
48
			tm.start();
49
		}
50
		
51
		private function check_buttons( e:TimerEvent ){
52
			for( var b in buttons ){
53
				if( buttons[b].dragging ){
54
					buttons[b].x = mouseX;
55
					buttons[b].y = mouseY;
56
					if( buttons[b].getDistance() > maxdist ){
57
						buttons[b].reset();
58
					}
59
				}
60
			}
61
		}		
62
	}	
63
}

And for the ElasticButton class:

1
2
3
package {
4
	
5
	import flash.display.*;
6
	import flash.text.*;
7
	import flash.net.*;
8
	import flash.events.*;
9
	import flash.geom.ColorTransform;
10
	import fl.transitions.Tween;
11
	import fl.transitions.TweenEvent;
12
	import fl.transitions.easing.*;
13
	import fl.motion.Color;
14
	
15
	
16
	public class ElasticButton extends MovieClip {
17
		
18
		var origin:Object;
19
		var textfield:TextField;
20
		var tf:TextFormat;
21
		var dragging:Boolean = false;
22
		var bg:Sprite;
23
		var url:String;
24
		var twx:Tween;
25
		var twy:Tween;
26
		var padding:Number = 8;
27
		var color:uint;
28
		var msk:Sprite;
29
		
30
		public function ElasticButton(){
31
			//do nothing

32
		}
33
		
34
		public function init( node ){
35
			textfield = new TextField();
36
			tf = new TextFormat();
37
			tf.size = 14;
38
			tf.font = '_sans';
39
			tf.bold = true;
40
			tf.color = 0xffffff;
41
			tf.align = TextFormatAlign.CENTER;
42
			textfield.defaultTextFormat = tf;
43
			textfield.text = node..name;
44
			textfield.width = 65;
45
			textfield.height = 20;
46
			textfield.x = -(textfield.width / 2 );
47
			textfield.y = -(textfield.height / 2 );
48
			textfield.mouseEnabled = false;
49
			addChild( textfield );
50
			origin = new Object();
51
			origin.x = this.x;
52
			origin.y = this.y;
53
			color = node..color;
54
			createBG();
55
			url = node..url;
56
			dragging = false;
57
			this.buttonMode = true;
58
			this.addEventListener( MouseEvent.MOUSE_OVER, mouse_over );
59
			this.addEventListener( MouseEvent.CLICK, mouse_click );
60
		}
61
		
62
		public function createBG(){
63
			bg = new GradBackground();
64
			var dbpad = padding*2;
65
			bg.width = textfield.width+dbpad;
66
			bg.height = textfield.height+dbpad;
67
			bg.x = -( (textfield.width+dbpad)/2);
68
			bg.y = -( (textfield.height+dbpad)/2);
69
			addChild(bg);
70
			var col = new Color(1,1,1,1);
71
			col.setTint( color, 0.4 );
72
			bg.transform.colorTransform = col;
73
			setChildIndex( bg, 0 );
74
		}
75
		
76
		public function getDistance(){
77
			return Math.sqrt( (this.x-origin.x)*(this.x-origin.x) + (this.y-origin.y)*(this.y-origin.y) );
78
		}
79
		
80
		public function reset(){
81
			dragging = false;
82
			twx = new Tween( this, 'x', Elastic.easeOut, this.x, origin.x, 0.4, true );
83
			twy = new Tween( this, 'y', Elastic.easeOut, this.y, origin.y, 0.4, true );
84
		}
85
		
86
		private function mouse_over( e:MouseEvent ){
87
			dragging = true;
88
		}
89
		
90
		private function mouse_click( e:MouseEvent ){
91
			navigateToURL( new URLRequest( this.url ) );
92
		}
93
		
94
		public function makeStartButton(){
95
			msk = new Sprite();
96
			msk.graphics.beginFill(0x000000,1);
97
			msk.graphics.moveTo( 0, padding );
98
			msk.graphics.curveTo( 0, 0, padding, 0 );
99
			msk.graphics.lineTo( (padding*2)+textfield.width, 0 );
100
			msk.graphics.lineTo( (padding*2)+textfield.width, (padding*2)+textfield.height );
101
			msk.graphics.lineTo( 0, (padding*2)+textfield.height );
102
			msk.graphics.lineTo( 0, padding );
103
			msk.graphics.endFill();
104
			msk.x = bg.x;
105
			msk.y = bg.y;
106
			addChild( msk );
107
			bg.mask = msk;
108
		}
109
		
110
		public function makeEndButton(){
111
			var dbpad = padding*2;
112
			msk = new Sprite();
113
			msk.graphics.beginFill(0x000000,1);
114
			msk.graphics.lineTo( textfield.width + padding, 0 );
115
			msk.graphics.curveTo( textfield.width + dbpad, 0, textfield.width + dbpad, padding );
116
			msk.graphics.lineTo( dbpad + textfield.width, dbpad + textfield.height );
117
			msk.graphics.lineTo( 0, dbpad + textfield.height );
118
			msk.graphics.lineTo( 0, padding );
119
			msk.graphics.endFill();
120
			msk.x = bg.x;
121
			msk.y = bg.y;
122
			addChild( msk );
123
			bg.mask = msk;
124
		}
125
		
126
	}
127
	
128
}

Conclusion

Now, that was a pretty long tutorial! I hope I didn't bore anybody. If you have any ideas about how we could improve the menu, add them to the comments.

Thank you for reading!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.