
Here I’ll be showing you how to create a menu in Flash that creates a navigation structure from an XML file. Each button can load various types of media (images, swfs, videos) or even open a web page. We will open Flash and create a new Movie Clip called “nav” and give it the same linkage id class name. Create a a box 40px tall and convert it to a Movie Clip with the instance name of “bg”. Create a new layer and create a new dynamic text field with the instance name of “title_txt”. Make sure to embed your fonts for your desired character set. Now here is one thing I figured out that is kind of important. Create another layer on top and copy your MC called “bg” and paste it into this new layer with the instance name of “trans” and set the Alpha property to zero. This will act as our hit state. Without this the cursor loses focus when it is located over the dynamic text.
Create a class file called “BuildMenu.as”. In Flash, change your Document Class to BuildMenu. Save.
Create an XML file called “menu.xml” and fill it with these contents:
<?xml version="1.0" encoding="utf-8"?>
<navigation>
<button title="Image" action="image1.jpg" />
<button title="Video F4V" action="video1.f4v" />
<button title="Video MPEG" action="video2.mpeg" />
<button title="SWF File" action="swf1.swf" />
<button title="Contact" action="http://www.google.com" />
</navigation>
Open BuildMenu.as and fill it with this code:
// ActionScript file
package {
import fl.transitions.Tween;
import fl.transitions.easing.*;
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class BuildMenu extends Sprite {
private var titles:Array = new Array();
private var actions:Array = new Array();
private var total:uint = 0;
private var xmlFile:String = "menu.xml";
private var loadMenuXML:URLLoader = new URLLoader();
private var fadeSpeed:Number = 0.2;
public function BuildMenu() {
var reqMenuXML:URLRequest = new URLRequest(xmlFile);
loadMenuXML.addEventListener(Event.COMPLETE, parseXML);
loadMenuXML.load(reqMenuXML);
}
private function parseXML(e:Event):void {
var menuXML:XML = new XML(loadMenuXML.data);
var container:Sprite = new Sprite();
container.name = "container";
container.x = 100;
addChild(container);
for (var i:int = 0; i<menuXML.*.length(); i++) {
titles.push(menuXML.button[i].@title);
actions.push(menuXML.button[i].@action);
var btn:MovieClip = new nav;
container.addChild(btn);
btn.y = i*40;
btn.title_txt.htmlText = titles[i];
btn.trans.addEventListener(MouseEvent.CLICK, navClick);
btn.trans.addEventListener(MouseEvent.ROLL_OVER, fadeDown);
btn.trans.addEventListener(MouseEvent.ROLL_OUT, fadeUp);
btn.trans.buttonMode = true;
btn.trans.ID = i;
}
}
private function fadeDown(e:Event):void {
var fDown:Tween = new Tween(e.currentTarget.parent.bg, "alpha", None.easeOut, e.currentTarget.parent.bg.alpha, 0.5, fadeSpeed, true);
}
private function fadeUp(e:Event):void {
var fUp:Tween = new Tween(e.currentTarget.parent.bg, "alpha", None.easeOut, e.currentTarget.parent.bg.alpha, 1, fadeSpeed, true);
}
private function navClick(e:Event):void {
determineLink(e.currentTarget.ID);
}
private function determineLink(id) {
//trace(titles[id]+" -> "+actions[id]);
var actionItem:String = actions[id].toString();
// Find file extension
var fileExtension:String = actionItem.substr(0,4);
if (fileExtension == "http") {
// this is a URL
} else {
fileExtension = actionItem.substr(actionItem.lastIndexOf('.')+1, actionItem.length);
// this is a file extension
}
var mediaType:String = fileExtension.toLowerCase();
switch (mediaType) {
case "http":
trace("Open URL -> "+actionItem);
openURL(actionItem);
break;
case "flv":
case "f4v":
case "mov":
case "mpeg":
case "mp4":
trace("Load video -> "+actionItem);
loadVideo(actionItem);
break;
case "jpg":
case "gif":
case "jpeg":
case "png":
trace("Load image -> "+actionItem);
loadImage(actionItem);
break;
case "swf":
trace("Load swf -> "+actionItem);
loadSWF(actionItem);
break;
default :
trace("Incorrect file type used");
break;
}
}
private function loadImage(file) {
// load Image
var assetLoader:Loader = new Loader();
addChild(assetLoader);
assetLoader.load(new URLRequest(file));
}
private function loadSWF(file) {
// load SWF
var assetLoader:Loader = new Loader();
addChild(assetLoader);
assetLoader.load(new URLRequest(file));
}
private function loadVideo(file) {
// load Video
}
private function openURL(url) {
// open URL
var loadURL:URLRequest = new URLRequest(url);
try {
navigateToURL(loadURL, "_blank");
} catch (e:Error) {
trace("Cannot load -> "+url);
}
}
}
}
To view the output, Test Movie in Flash.

Ok, so I’m a little behind the curve in AS3 right now. But I’ve gotta get learning because I see a lot of AIR apps and other AS3 apps I need to build in the future. I’ve a had a little spare time today to follow Colin Moock’s Essential AS3 book. I’ve made it a goal to create a file that uses an ActionScript 3 class to load external text stored in an XML file that is styled with a CSS file.
myText.xml
<?xml version="1.0" encoding="utf-8"?>
<MYTEXT>
<TEXT><![CDATA[<p><span class='bigText'>This is my title</span></p><br /><p><b>Bold</b>, <i>italics</i>, <u>underline</u>, normal</p><br /><p><a href='http://www.google.com/'>Web link</a></p><br /><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque facilisis, metus ut commodo tempus, enim mi placerat justo, nec ornare sapien urna eu nisl. In hac habitasse platea dictumst. Integer suscipit, nisl id consectetur pharetra, velit quam accumsan diam, sit amet commodo nibh libero vitae neque. Donec neque dui, ultrices id, condimentum in, eleifend non, odio. Sed elit risus, hendrerit at, gravida quis, porttitor a, nisi. Pellentesque ullamcorper. Nulla facilisi. Maecenas sagittis. Phasellus nulla ipsum, varius non, bibendum vel, sollicitudin ac, nunc.</p><p>Integer id tortor sit amet odio fermentum dictum. Integer metus arcu, laoreet non, lobortis et, tincidunt sed, erat. Quisque porttitor nibh ac felis. Donec facilisis, purus sed eleifend dapibus, quam est ultrices turpis, vel dictum justo lectus ac ligula. Nullam diam tortor, suscipit sodales, porta at, vestibulum venenatis, ipsum. Nunc placerat, urna eu elementum dictum, odio metus lobortis justo, sit amet convallis lacus mauris sed sem.</p>]]></TEXT>
</MYTEXT>
styles.css
p {
font-family: Arial;
font-size: 12px;
color: #006600;
}
.bigText {
font-family: Arial;
font-size: 24px;
color: #0099FF;
letter-spacing:-1px;
}
a {
color:#FF0000;
text-decoration:none;
}
a:hover {
color:#0000FF;
text-decoration:underline;
}
CSS_XML.as
package {
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.net.*;
public class CSS_XML extends Sprite {
private var myText:XML;
private var urlLoaderXML:URLLoader;
private var paragraph:String;
private var CSSFile:String = "styles.css";
private var XMLFile:String = "myText.xml";
public function CSS_XML() {
var urlRequest:URLRequest = new URLRequest(XMLFile);
urlLoaderXML = new URLLoader();
urlLoaderXML.addEventListener(Event.COMPLETE, completeListenerXML);
urlLoaderXML.load(urlRequest);
}
private function completeListenerXML(e:Event):void {
myText = new XML(urlLoaderXML.data);
paragraph = myText.TEXT.toString();
loadCSS();
}
private function loadCSS() {
var urlLoaderCSS:URLLoader = new URLLoader();
urlLoaderCSS.addEventListener(Event.COMPLETE, completeListenerCSS);
urlLoaderCSS.load(new URLRequest(CSSFile));
}
private function completeListenerCSS(e:Event):void {
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS(e.target.data);
var t:TextField = new TextField();
t.multiline = true
t.autoSize = TextFieldAutoSize.LEFT;
t.width = 550;
t.wordWrap = true;
t.styleSheet = styleSheet;
t.htmlText = paragraph;
addChild(t);
}
}
}
Now the end-result isn’t amazing-looking. It definitely needs a scrolling utility, but it’s a good start.
Enjoy!
This is something I’ve been wanting to figure out for a while and just now had time to take it on. In this example we’re scrolling text in a MovieClip that uses a traditional scrollbar and the MouseWheel. MouseWheel scrolling only occurs while the mouse is hovering over the text area. If you use this and resize those components, you won’t need to edit any of this. It’ll know what to do, trust me.

This is the meat of the code that runs the scroller. The text info populates target_mc.main_txt. Invoke scrollInfo() to start the scrolling.
import mx.transitions.Tween;
import mx.transitions.easing.*;
track_mc._visible = false;
drag_mc._visible = false;
mouseListener = new Object();
function scrollInfo() {
// If scrolling is not needed, hide scrolling assets
track_mc._visible = false;
drag_mc._visible = false;
// Find height of the target_mc
var clipheight:Number = target_mc._height;
// Find y position of target_mc
var starty:Number = 0;
target_mc._y = 0;
// Find height of mask over target_mc
var maskheight:Number = mask_mc._height;
// Limit scrolling
var maxscroll:Number = maskheight-clipheight+starty;
// Start dragging position
var startposition:Number = drag_mc._y=track_mc._y;
// Find y position of scrollbar face
var startdragT:Number = drag_mc._y;
// Limit var for scrollbar face
var startdragB:Number = track_mc._height-drag_mc._height+track_mc._y;
// Calculation for scrolling clip
var diff:Number = (clipheight-maskheight)/(track_mc._height-drag_mc._height);
// Var for activating the MouseWheel scrolling
var mScroll:Boolean = false;
// Disable all this if scrolling isn't necessary
if (target_mc._height<mask_mc._height) {
track_mc._visible = false;
drag_mc._visible = false;
mScroll = false;
mouseWheelScroll();
} else {
track_mc._visible = true;
drag_mc._visible = true;
mScroll = true;
mouseWheelScroll();
}
// drag_mc on press
drag_mc.onRollOver = function() {
this.gotoAndPlay("start");
};
drag_mc.onRollOut = function() {
this.gotoAndPlay("end");
};
drag_mc.onPress = function() {
// Start dragging, limit the dragging to parameters
startDrag(this, false, this._x, track_mc._y, this._x, (track_mc._height+track_mc._y)-this._height);
// Update scrolling clip in conjunction with the y position of the drag_mc
this.onMouseMove = function() {
difference = Math.abs(startposition-this._y);
target_mc._y = -Math.round(difference*diff+starty);
};
};
// On release, kill function
drag_mc.onRelease = function () {
stopDrag();
delete this.onMouseMove;
};
drag_mc.onReleaseOutside = function () {
stopDrag();
this.gotoAndPlay("end");
delete this.onMouseMove;
};
// Mouse Wheel Scrolling
function mouseWheelScroll() {
mouseListener.onMouseWheel = function(delta) {
// Only do it if the mouse is hovering over the text area
if (_xmouse > mask_mc._x && _xmouse < mask_mc._x+mask_mc._width && _ymouse > mask_mc._y && _ymouse < mask_mc._y+mask_mc._height) {
if (delta<0 && mScroll == true) {
if (target_mc._y>maxscroll+20) {
target_mc._y += delta*10;
} else {
target_mc._y = maxscroll;
}
}
if (delta>0 && mScroll == true) {
if (target_mc._y<starty-20) {
target_mc._y += delta*10;
} else {
target_mc._y = starty;
}
}
drag_mc.gotoAndPlay("end");
}
// Move the scroll button to correspond with the position of the text (this was the hard part)
difference = Math.abs(startposition-target_mc._y);
var mT:Tween = new Tween(drag_mc, "_y", Regular.easeOut, drag_mc._y, difference/diff+starty, 0.2, true);
};
Mouse.addListener(mouseListener);
}
}
Use it however you want, Enjoy!

We were tasked with creating a full Flash website to showcase user-generated video content for a contest that a local restaurant chain (Rosa’s Cafe) is currently running. Any patron to their restaurant is encouraged to film themselves going crazy for Rosa’s. They can upload their video at www.crazyforrosas.com and be eligible for $5000 or a FlipVideo camera.
When tasked with this we decided to use YouTube for the actual storage of the video content. To do this, sign up for a YouTube account and begin uploading some content to begin testing. You can easily take advantage of the YouTube API and RSS feeds to pull the information in Flash.

To access YouTube’s RSS feed, you’ll need to create an intermediary to avoid the cross-domain security protection. We used a PHP script to snag our RSS feed so we can display it on our server.
<?php
#readxml.php
$file = "http://www.youtube.com/rss/user/username/videos.rss";
$handle = @fopen($file, "r");
if ($handle) {
while (!feof($handle)) {
echo fgets($handle, 4096);
}
fclose($handle);
}
?>
In Flash, you’ll need to call readxml.php (the above script) as XML and parse it out accordingly. It helps to have a real strong knowledge of XML parsing to get your way through it since there’s a lot of info in the feed that you won’t need. It will give you thumbnail locations, titles, descriptions, video links, etc. One problem that I found is that it’s very difficult to use the YouTube ActionScript API. There is not very much documentation. Opening one video is fine, open another one and Flash will crash. The API says to use the destroy(); command prior to opening another video, but it does not work. I found some help on their forums to help us – but the solution was not some handy ActionScript. It was to use a free component called ToobPlayer. This was most certainly a life saver after spending hours on YouTube’s API and not getting anywhere. The ToobPlayer component can easily use a YouTube video url and be skinned. A big thanks goes out to those folks!
This site also features a full administration panel using CakePHP to administer video submissions and a Flash front-end video upload feature.
Visit Crazy for Rosa’s

Download includes versions for 4×3 and 16×9 aspect ratios.
I’ve created a video player that you can use for free that is easily customizable. The cool thing is you don’t need to open Flash to change the video you want it to display. Just write is as a variable in your embed code like this:
<script type="text/javascript" language="javascript">
var so = new SWFObject("/examples/videoplayer/video_4x3.swf", "mymovie", "500", "405", "8", "#000000");
so.addParam("menu", "false");
so.addParam("scale", "noscale");
so.addParam("allowFullScreen", "true");
so.addVariable("myVideo", "vid1.flv");
so.write("flash");
</script>
Note so.addVariable(“myVideo”, “vid1.flv”); All you need to do is change vid1.flv to the video of your choice.
Enjoy!
My Flash/XML Portfolio Template is getting some nice words and it sits atop the Flashden top files of the week. Check out my file
Here’s a freebie – Flash source code to use fullscreen scaling images that maintain their aspect ration when scaling (AS2). I am using smoothImageLoad to convert the loaded png, jpg or gif to a smooth bitmap. Enjoy!

// Use Tween class to fade in the image
import mx.transitions.Tween;
import mx.transitions.easing.*;
var stageListener:Object=new Object();
stageListener.onResize=function(){
position();
};
Stage.align="TL";
Stage.scaleMode="noScale";
Stage.addListener(stageListener);
// Reposition objects when the movie is resized
function position() {
// Find new value of stage size
var W:Number = Stage.width;
var H:Number = Stage.height;
// Find center of stage
var centerX:Number = W/2;
var centerY:Number = H/2;
// Center main bg clip
background_mc._x = centerX;
background_mc._y = centerY;
// Center target clip inside the main bg clip
background_mc.target_mc._x = -_global.BGW/2;
background_mc.target_mc._y = -_global.BGH/2;
var imageRatio:Number;
var imageXRatio = W/_global.BGW;
var imageYRatio = H/_global.BGH;
// Determine if the width is larger than the height
if (imageXRatio>imageYRatio) {
imageRatio = imageXRatio;
} else {
imageRatio = imageYRatio;
}
// Scale the image to fit fullscreen
background_mc._xscale = background_mc._yscale=imageRatio*100;
}
// Function for smoothing resizable bitmaps
function smoothImageLoad(imgURL, targetMovie) {
var i = 0;
do {
i++;
} while (eval("_root.smoothImageLoadTemp"+i) != undefined);
tmc = targetMovie.createEmptyMovieClip("smoothImageLoadTemp"+i, targetMovie.getNextHighestDepth());
tmc.createEmptyMovieClip("ti",tmc.getNextHighestDepth());
tmc.tm = targetMovie;
with (tmc) {
tmcl = new MovieClipLoader();
tmcl.onLoadComplete = function() {
var fadeBG:Tween = new Tween(targetMovie, "_alpha", None.easeOut, 0, 100, 1, true);
ti.onEnterFrame = function() {
pixelData = new flash.display.BitmapData(ti._width, ti._height);
_global.BGW = ti._width;
_global.BGH = ti._height;
pixelData.draw(ti);
tm.attachBitmap(pixelData,1,true,true);
tm.smoothImageLoadComplete();
_parent._parent._parent.position();
removeMovieClip(ti._parent);
};
};
tmcl.loadClip(imgURL,tmc.ti);
}
}
// Load your image
smoothImageLoad("image.jpg",background_mc.target_mc);
© 2010 Aaron Benson. All rights reserved.