Website Components          jQuery Components          Flash Components          Website Templates          Image Galleries          Website Themes

Build an XML Banner Rotator in AS3 from Scratch

Published on May 28th, 2010 at 4:08 pm

FireCode

4 Comments »

In this tutorial we will use XML , URLLoader, URLRequest, Loader, Timer,  Events classes to develop the xml driven banner in AS3.  This is an easy-to-develop type of banner that you can use to showcase your products and services.

bras3

You can download the source code here.

Step 1: Preparing the files

The purpose of loading external files is to update our content without having to modify our .fla file and generate a new swf file and upload it each time we decide to change the images or the information about them.

First we will create a folder inside the project’s folder and we will name it images. Inside this folder we will have all our images we want to load. It’s a good idea to have all the images with the same dimensions.

Second, we create an XML file. Using XML is one of the best ways for structuring external content in a logical format that is easy to understand, process, and update. We will name it data.xml. Any simple text editor can create our XML file. The structure of our XML is shown below.

<?xml version="1.0" encoding="utf-8"?>
<slide DELAY="2">
<image URL="images/1.jpg" DESCRIPTION="Lorem ipsum dolor sit amet, consectetur adipiscing elit. " />
<image URL="images/2.jpg" DESCRIPTION="Nam blandit dictum nibh vel mattis" />
<image URL="images/3.jpg" DESCRIPTION="Cras a magna eu libero sodales luctus nec at nulla" />
<image URL="images/4.jpg" DESCRIPTION="Nulla sed nisi sit amet ante hendrerit ullamcorper id eu neque" />
<image URL="images/5.jpg" DESCRIPTION="Vivamus quis turpis libero." />
</slide>

Copy and paste then save the file.

Now we will create the .fla file.  Open the Flash IDE and go to File, New… and choose Flash File( actionscript 3 ). Press Ctrl+F3 to bring out the swf properties panel and set the values size to 450×370 px.

Save it in the same folder as your XML file and your images folder as BannerRotator.

Step 2: Load and process the XML file

Loading the data from our external xml file will require using the URLLoader and URLRequest classes, while processing it will require using the XML Class. First we will create the variables that we will be using in the entire program.

var _delay:int = 0;
var _total:int = 0;
var _images:XMLList = null;

Variable _delay will store the amount of data before the image changes to the next image. Variable _total will store the number of images. Variable _ images will store the data about our images.

Now we will prepare the program to load our external XML.

var _loader:URLLoader = new URLLoader();
_loader.load(new URLRequest("data.xml"));
_loader.addEventListener(Event.COMPLETE, Complete, false, 0, true);

We have declared a _loader variable that will handle the loading of our file. The COMPLETE event tells the program that our XML has been loaded in our variable and it’s ready to be processed.

function Complete(e:Event):void
{
var _xml:XML = new XML(e.target.data);
_loader = null;
_loader.removeEventListener(Event.COMPLETE, Complete);
}

All the information from our loader will be stored into the local variable _xml. As a good practice we should clear our _loader variable and remove it’s event listener.

Inside our Complete function we will add the following lines of code.

function Complete(e:Event):void
{
var _xml:XML = new XML(e.target.data);
_loader.removeEventListener(Event.COMPLETE, Complete);
_loader = null;
_delay = _xml.@DELAY;
_images = _xml.image;
_total= _images.length();
}

We will use the @ operator to retrieve the attribute value we need for the _delay variable.  Variable _images will store a list with every node with the image tag. The .length() method will retrieve the number of nodes with the name image tag. Now all our variables are set.

Step 3: Loading the external images

In order to load an image we will use the Loader class. Several instances of this class will be created with a loop and stored inside an array for easy referencing.

var _loaders:Array = new Array();
function LoadImages():void
{
for (var i:int = 0; i < _total; i++)
{
var _url:String = _images[i].@URL;
var _loader:Loader = new Loader();
_loader.load(new URLRequest(_url));
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ImageLoaded, false, 0, true);
_loaders.push(_loader);
}
}

This loop will cycle through the XML file, extract the URL attribute of every image node,   pass it to a Loader instance and then push that instance into our array. To every Loader instance we attach an event listener that will fire a function once the image has been loaded.

Now we will create our function that will be fired with every image that has been loaded. But before that we will create a variable that it will check how many images have been loaded. Once we got all the images loaded we can start to slide the images.

var _counter:int = 0;
function ImageLoaded():void
{
_counter++;
if ( _counter ==  _total)
{
SetupSlider ();
}
}

Step 4: Setup the slider

First we’re going to declare some variables that we will need and import some extra classes.

import fl.transitions.Tween;
import fl.transitions.easing.Strong;
var _next:int = 0;
var _timer:Timer = null;
var _tween:Tween = null;
var _container:Sprite= new Sprite();

Tween class it will be responsible for our animation and Strong it will be our effect class. Variable _next will store the current image id in the array and it will help us to select the next one. In order to have our slides running, we will use the Timer class to have our code executed repeatedly. The _tween variable will be used to store our transition effect. The _container will store our actual image to be displayed.

Let’s modify our Complete function so we can add our _container to the dis.

Now we will create our SetupSlider function:
[codesyntax lang=“actionscript”]
function SetupSlider():void
{
addChild(_container);
NextImage();
_timer = new Timer(_delay*1000);
_timer.addEventListener(TimerEvent.TIMER, TimerListener);
_timer.start();
}

We will add our container to the diplay list of our swf so later we can add images. the NextImage function will display our first image from the array. Then a timer will count how long until the next image will appear. We are going to set the speed, which is stored in the _delay variable,  at which the Timer intervals are triggered when instantiating the class. The Timer receives its speed in milliseconds, so we have to multiply our speed value by 1000.  Our timer will run its code through a separate event listener. Finally, we need to start the Timer by using the .start() method.

Now let’s create our TimerListener function.

function TimerListener(e:TimerEvent):void
{
_next++;
if (_next == _total)
{
_next =0;
}
NextImage();
}

Inside this function we set our next image to be displayed. If _next variable will be equal to the total amount of images the _next variable will be reset to start all over.

Finally we got to the part where we build our NextImage function.

function NextImage():void
{
if(_container.numChildren>0)
{
_container.removeChildAt(0);
}
_loaders[_next].alpha = 0;
_container.addChildAt(_loaders[_next],0);
_tween = new Tween(_loaders[_next],"alpha",Strong.easeOut,0,1,1,true);
}

This function is responsible with displaying the current image set by the TimerListener function.  We check if there are any child objects inside our _container. If there is any we will remove it and clean our container then set the current image alpha to 0 ( making it invisible) so we can add a nice effect to it.  The Tween class will get this image and animate it’s alpha by making it appear slowly.

Now it’s time to hit Ctrl+Enter keys so we can test our movie. If everything is good with our code it should display some images that change after some time.

If everything is ok we should now add some info about the images that are being displayed. We will add a textfield that will contain the image description.

We will create a variable _text that will hold our data. Let’s modify our SetupSlider function by adding the following code.

var _text:TextField = new TextField();
function SetupSlider():void
{
addChild(_container);
_text.selectable=false;
_text.width = 450;
_text.height = 50;
_text.x = 0;
_text.y = 300;
addChild(_text);
NextImage();
_timer = new Timer(_delay*1000);
_timer.addEventListener(TimerEvent.TIMER, TimerListener);
_timer.start();
}

Then we modify our NextImage function to add the information of the image.

function NextImage():void
{
if(_container.numChildren>0)
{
_container.removeChildAt(0);
}
_loaders[_next].alpha = 0;
_container.addChildAt(_loaders[_next],0);
_tween = new Tween(_loaders[_next],"alpha",Strong.easeOut,0,1,1,true);
_text.text = _images[_next].@DESCRIPTION;
}

The last line will get the DESCRIPTION attribute of the current image being displayed and add it to our textfield.

Hit Ctrl+Enter key again to test our movie. Each time the image changes our text field will display the description of the current image being displayed.

Note: A working online version should include also a preloader for the images. If they are to big the user should know that an image is being loaded and the program is working correctly.

-----------------------------------------------

FireCode is a promising project created by a couple of passionate Flash developers. Our purpose is  to help you understand how Flash works and show you how to develop or customize your components. We hope you enjoyed this tutorial. Don’t forget to visit our portfolio here and to send us your questions or suggestions!

Share

4 Responses to “Build an XML Banner Rotator in AS3 from Scratch”

Leave a Reply: