Can someone help me to understand how to dynamically add clips on the stage

Hi,

Can some help me to improve the following code?

What I have here are three buttons that when clicked a new clip is added to the stage with a predefined position which means that when button1 is clicked the MovieClip will be added at the very top and when button2 is clicked the MovieClip will be added at second and when button3 is clicked the clip will be added at the very bottom and what I would like to do is to be able to dynamically position these objects based on how many clips exist, in other words if button3 is clicked first, I want the clip to be positioned at the very top and if later button1 is clicked the clip is positioned accordantly (at second place). I know this may be simple, in fact I could probably use a few IF statements but I know the code would look ugly (even more) and I may have add more buttons later. What I would like is to some-how use arrays or something that makes more sense.

Thanks a lot

button1.addEventListener(MouseEvent.CLICK, addItem1, false,0,true);
button2.addEventListener(MouseEvent.CLICK, addItem2, false,0,true);
button3.addEventListener(MouseEvent.CLICK, addItem3, false,0,true);

var rec:Sprite;
var rec2:Sprite;
var rec3:Sprite;
var itemsWidth=200;
var itemsHeight=20;

function addItem1(e:MouseEvent):void {
	rec = new Sprite();
	rec.graphics.beginFill(0xffff00,1);
	rec.graphics.drawRect(250,10, itemsWidth, itemsHeight);
	rec.graphics.endFill();
	addChild(rec);
}

function addItem2(e:MouseEvent):void {
	rec2 = new Sprite();
	rec2.graphics.beginFill(0xffff00,1);
	rec2.graphics.drawRect(250,(itemsHeight)+12, itemsWidth, itemsHeight);
	rec2.graphics.endFill();
	addChild(rec2);
}

function addItem3(e:MouseEvent):void {
	rec3 = new Sprite();
	rec3.graphics.beginFill(0xffff00,1);
	rec3.graphics.drawRect(250,(itemsHeight*2)+14, itemsWidth, itemsHeight);
	rec3.graphics.endFill();
	addChild(rec3);
}

Hope the following links will help you:

The Display List, The Stage, and “addChild” in Flash CS3
ActionScript 3 External Classes | Flash tutorials | CS5 | Actionscript | flash animation | HowTo

Thank you for the links but I’m already familiar with the display list.

Thanks