Nav Tree Menu
/**
* Copyright shapevent ( http://wonderfl.net/user/shapevent )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/aPP1
*/
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
public class NestedNav extends MovieClip {
private var menu:XML;
private var elements:Array;
public function NestedNav(){
// init
menu=<nav>
<element label="one">
<element label="a" />
<element label="b" />
<element label="c" />
</element>
<element label="two">
<element label="three">
<element label="aa" >
<element label="zevan" />
</element>
<element label="bb" />
<element label="cc" />
</element>
</element>
</nav>;
elements = new Array();
setupMenu();
}
// private methods
private function setupMenu():void {
parse(menu);
// hide child elements
for (var i:int = 0; i<elements.length; i++) {
var mc:MovieClip = elements[i];
if (mc.parents != 1) {
removeChild(mc);
}
}
arrangeY();
}
private function parse(m:XML):void {
for each (var d:XML in m.children()) {
makeBtn(d, numParents(d));
parse(d);
}
}
private function makeBtn(d:XML, offsetX:int):void {
var btn:MovieClip = new MovieClip();
btn.x = offsetX * 20;
btn.y = numChildren * 20;
btn.data = d;
btn.parents = offsetX;
btn.value = d.@label;
var txt:TextField = new TextField();
txt.text = d.@label;
txt.selectable = false;
txt.border = true;
txt.width = 100;
txt.mouseEnabled = false;
txt.height = 19;
btn.addChild(txt);
btn.buttonMode= true;
addChild(btn);
// store references to btn
elements.push(btn);
elements[d.parent().@label+"_"+d.@label] = btn
btn.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(evt:MouseEvent):void {
showHide(MovieClip(evt.currentTarget));
arrangeY();
trace(evt.currentTarget.value);
}
private function showHide(btn:MovieClip, forceHide:Boolean=false):void {
for each (var d:XML in btn.data.children()) {
var mc:MovieClip = elements[btn.data.@label+"_"+d.@label];
if (contains(mc)) {
removeChild(mc);
showHide(mc, true);
} else if (forceHide == false) {
addChild(mc);
}
}
}
private function arrangeY():void {
var inc:Number = 0;
for (var i:int = 0; i<elements.length; i++) {
if (contains(elements[i])) {
elements[i].y = inc * 20;
inc++;
}
}
}
private function numParents(e:XML):int {
var num:int = 0;
while (e.parent()!= null) {
num++;
e = e.parent();
}
return num;
}
}
}