XML Pages with ActionScript 3

February 6, 2009 by: smonte

This tutorial will show you how to create multiple Flash pages using XML. In the Flash movie, all the content and image paths have been defined in a XML file. I will first give you a short intro to XML, then we set up the Flash movie and finally, we add some ActionScript 3 to provide the functionality.

Note: You need TweenLite to fully complete this tutorial. We use it for the animation.

Introduction to XML

XML stands for EXtensible Markup Language. It is just another markup language, such as HTML. XML basically just stores data. It doesn’t really do anything. Consider the following simple example:

>
        > Flash and ActionScript 3 tutorials >
        > https://flashmymind.com >
        > 316,914 >
>

Here we have a root called “flashmymind”. As you can see, this XML document stores data about the FlashMyMind website. Now we could do a Flash movie which loads this XML data and displays it on the screen in some interesting way. If you want to change the content of the Flash movie, you can simply modify this XML document rather than changing the .fla file. This is (IMHO) the biggest advantage of using XML. XML makes it really easy to update the content of a Flash movie.

The web is full of decent XML tutorials, so I won’t start writing about XML strucure, attributes etc. If you want to learn more about the subject, I suggest you start from the W3Schools tutorial.

Setting up the environment

1. Create a new Flash document of size 450×300.

2. Create two dynamic text fields on the left side of the stage. Type some text into them as I have done. Give them instance names of “titleText” and “contentText”.

Dynamic text fields

3. Create a new empty movie clip (Insert -> New Symbol). Give it a name “Image holder” and hit “OK”.

4. Drag the image holder from the library to the stage. Position it right after the title text field (refer to screenshot). Give the image holder an instance name of “imageHolder”

Image holder

5. Now we need to create the images that show up on the right side of each page. Feel free to use your own, or use the ones that I have. Remember the location where you save these images! You will need the path when we define the image sources in the XML document.

Page 1 ImagePage 2 ImagePage 3 Image

6. Now we need to create the three buttons. So draw a rectangle shape (I have rounded corners) and convert it into a movie clip. Name it “Button 1″.

7. Double click the “Button 1″ movie clip. Inside the movie clip, create a static text field and type in number 1. Position the number in the center of the button (refer to screenshot).

Button text

8. Now duplicate this movie clip twice (name the duplicates “Button 2″ and “Button 3″). You should now have three different button movie clips.

9. Drag all the button movie clips to the stage. Position them on the bottom right corner. Modify the other two buttons so that the static text fields have values “2″ and “3″.

10. Give the buttons instance names of “button1″, “button2″ and “button3″.

Buttons

11. One last thing before we move to coding. We need to create the “Loading content…” text. So create a new layer. Create a static text that says “Loading content…”. Position it to the center of the stage.

12. Convert the text into a movie clip. Name it to whatever you want. Give it an instance name of “loadingText”.

Moving into XML and ActionScript 3

13. Create a new .xml document. You can use which ever text editor you prefer. Type the following:

 version="1.0" encoding="utf-8"?>
>
        >
 
                 page_number="1">
                        >Page #1>
                        >This is the FIRST page. This text is loaded from the "my_site.xml" file.>
                        >https://flashmymind.com/SWF/page1.gif>
                >
 
                 page_number="2">
                        >Page #2>
                        >This is the SECOND page. You can modify this content by modifying the XML file. No need to modify your .fla file anymore!>
                        >https://flashmymind.com/SWF/page2.gif>
                >
 
                 page_number="3">
                        >Page #3>
                        >The images on the right side are also specified in the XML file!>
                        >https://flashmymind.com/SWF/page3.gif>
                >
 
        >
 
>

Note: Change the image paths according to your settings. You can also use my URLs if you want.

14. Save this file as “my_site.xml” in the same folder where your .fla file is.

15. Go back to your .fla file. Type the following code in the first frame:

//Import TweenLite
import gs.*;
import gs.easing.*;
 
//Create a holder that will contain the title, content and image.
var holder:MovieClip = new MovieClip();
holder.addChild(contentText);
holder.addChild(titleText);
holder.addChild(imageHolder);
 
//Add the holder to the stage
addChild(holder);
 
//Hide the holder at the beginning of the movie.
//We don't want to show any content before the title, content and image has
//been loaded.
holder.visible = false;
 
//We don't want the user to be able to click the text fields inside the buttons
button1.mouseChildren = false;
button2.mouseChildren = false;
button3.mouseChildren = false;
 
//Make the buttons look like buttons (hand cursor appears on hover)
button1.buttonMode = true;
button2.buttonMode = true;
button3.buttonMode = true;
 
//Specify the path to the XML file.
//You can use my path or your own.
var xmlFilePath:String = "https://flashmymind.com/SWF/my_site.xml";
 
//We save the loaded XML data into a variable
var XMLData:XML;
 
//Load the XML file.
//We call the xmlDataLoaded() function when the loading is complete.
var loader = new URLLoader();
loader.load(new URLRequest(xmlFilePath));
loader.addEventListener(Event.COMPLETE, xmlDataLoaded);
 
//This function is called when the XML file is loaded
function xmlDataLoaded(e:Event):void {
 
        //Create a new XML object from the loaded XML data
        XMLData = new XML(loader.data);
        XMLData.ignoreWhitespace = true;
 
        //Call the function that adds event listeners for the buttons
        addEventListeners();
 
        //We dispatch a mouse click event for the first button,
        //so we start the movie with the first page (without user having to select it).
        button1.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
}
 
 
 
//This function adds event listeners for the buttons
function addEventListeners():void {
        button1.addEventListener(MouseEvent.CLICK, buttonClicked);
        button2.addEventListener(MouseEvent.CLICK, buttonClicked);
        button3.addEventListener(MouseEvent.CLICK, buttonClicked);
}
 
//This function removes event listeners from the buttons
function removeEventListeners():void {
        button1.removeEventListener(MouseEvent.CLICK, buttonClicked);
        button2.removeEventListener(MouseEvent.CLICK, buttonClicked);
        button3.removeEventListener(MouseEvent.CLICK, buttonClicked);
}
 
//This function is called when a button has been clicked
function buttonClicked(e:Event):void {
 
        //Make the holder invisible while we are loading data
        holder.visible = false;
 
        //Show the loading text
        loadingText.visible = true;
 
        //Save the clicked button to a local variable
        var clickedButton:MovieClip = (MovieClip)(e.target);
 
        //Set the wanted page number according to which button the user clicked
        var pageNumber:uint;
        if (clickedButton == button1) {
                pageNumber = 1;
 
        } else if (clickedButton == button2) {
                pageNumber = 2;
        } else {
                pageNumber = 3;
        }
 
        //Loop through the pages found in the XML file
        for each (var page:XML in XMLData.pages.page) {
 
                //Check if the page number that we're looking is found from the XML data.
                //The "page.@page_number" refers to the page's "page_number" attribute in the XML file.
                if (page. @ page_number == pageNumber) {
 
                        //Set the title from the XML
                        titleText.text = page.title;
 
                        //Set the content from the XML
                        contentText.text = page.content;
 
                        //Load the image (the image path is specified in the XML)
                        var imageLoader = new Loader();
                        imageLoader.load(new URLRequest(page.image));
 
                        //Listen when the image is loaded
                        imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
 
                        //We can exit the loop now
                        break;
                }
        }
}
 
//This function is called when the image is loaded
function imageLoaded(e:Event):void {
 
        //We can set the holder visible again now that the image is loaded
        holder.visible = true;
 
        //Hide the loading text
        loadingText.visible = false;
 
        //Remove the previous image from the image holder if there is one
        if(imageHolder.numChildren > 0) {
                imageHolder.removeChildAt(0);
        }
 
        //Add the loaded image to the image holder
        imageHolder.addChild(e.target.content);
 
        //Tween the holder. We call the function tweenComplete() when tween is finished.
        TweenLite.from(holder, 1, {alpha:0, y: -50, ease:Elastic.easeOut, onComplete: tweenComplete} );
 
        //Remove the listeners when we are tweening
        removeEventListeners();
}
 
//This function is called when the tween is complete
function tweenComplete():void {
 
        //We can add the event listeners again
        addEventListeners();
}

Note: You can change your XML file path in the code or you can use the one that I have used
(https://flashmymind.com/SWF/my_site.xml).

Don’t get scared of the amount of code, there is more than enough comments there! Go ahead and test your movie, we are done.

  • Digg
  • Sphinn
  • del.icio.us
  • Mixx

Related tutorials:

  1. Creating a Menu via XML
  2. Colorful Menu with XML and ActionScript 3
  3. Vertical Menu with Actionscript 3 and XML
  4. Advanced XML Menu with ActionScript 3
  5. 3D Carousel with XML and ActionScript 3

Comments

28 Responses to “XML Pages with ActionScript 3”
  1. Diana says:

    Noticed other people were getting this same error and thought I would post the fix here.

    If “Variable TweenLite is not defined” error occurs, choose: File > Publish Settings, AS3 Settings button, under Source Path tab click the + (Add New Path) button and type a period, click OK.

    Log in to Reply
  2. Aaron says:

    Great tut!

    I have 2 issues…

    When clicking on the buttons you are inable to click on another one or it does not do anything until the first one fully loads. Any way to make it restart even if the first click has not fully finished loading and load whatever page you click on?

    Also how would i go about adding buttons? I am going to have about 13 or 14?

    Any help would be sooooo greatly appreciated!!!

    Thanks in advance!!!! :)

    Log in to Reply
  3. Dmitry says:

    Nice tutorial, thnx!
    But can you give the complete fla source, please? O:-)

    Log in to Reply
  4. Oto Bakım says:

    sdasdas

    Log in to Reply
  5. Oto Bakım says:

    hello wi gehts bitte

    Log in to Reply
  6. Remmy says:

    Mine works (yey)…
    In the xml file, I change the path to my jpg file into : C:\MyComp\Flash\ArtGallery\pic1.jpg (obviously, you have to put in your own path)
    You have to take the “gs folder” from the greensock-tweening-platform-as3 and place it in the same folder as your image files, your .fla and your .xml Putting the greensock-tweening folder is not enough, The script looks for gs folder
    Change the coding in action script into : var xmlFilePath:String = “my_site.xml”;
    For others who find that their oversized image is blocking the text, try to re arrange the layer placement in the .fla Put the imageHolder symbol beneath the text and buttons
    I want the image to fade away smoothly when i clicked on other button, not just zapped suddenly. Any idea on how to script this?
    thanks smonte for posting

    Log in to Reply
  7. trickk says:

    it works.. if there is an error because the url : when the swf file finds the my_site.xml don not tipe any kind of c:\ .. the swf file just need that location where itself is.. so type only: “\my_site.xml”
    and the tweener folder (gs folder) also in the folder where the swf is.. in xml the pics linked by myself like this: images\page01.gif . if the tweener is too slow,than try a higher number in modify/document-framerate. if the exported swf isn’t work, than maybe it’s because of the flashplayer 9.. but when you export like a html in export settings , it works in explorer.. but exactly i dont know why it doesn’t work in the exported swf file.. am i right , it’s need to be exported by flash player10?
    because i exported in cs3..
    thanks

    Log in to Reply
    • Simon says:

      Did anyone have any luck with the gs.* error? Im running cs3 but cant get to work.

      Log in to Reply
  8. Irfan says:

    Great man, thanks a lot!

    Log in to Reply
  9. smonte says:

    You could try using two loaders and then add them on the stage. It looks like you are only using one loader now … ?

    Log in to Reply
  10. delugeon says:

    Thank you, this is such a useful and widely applicable tutorial. I am using it in my project with a couple alterations, but I have a question. On page 2 of my Flash movie, I have two images loading into separate image holders rather than just one.

    How do I adjust my Actionscript tutorial to add two images at a time to page 2? I have my XML set up correctly, but my code is having problems. Here is my code…what am I doing wrong?:

    //This function is called when all images are loaded
    function imagesLoaded(e:Event):void {

    //We can set the holder visible again now that the image is loaded
    holder.visible = true;

    //Hide the loading text
    loadingText.visible = false;

    //Remove the previous image from image holder 1 if there is one
    if(imageHolder1.numChildren > 0) {
    imageHolder1.removeChildAt(0);
    }

    //Remove the previous image from image holder 2 if there is one
    if(imageHolder2.numChildren > 0) {
    imageHolder2.removeChildAt(0);
    }

    //Add the loaded image to image holder 1
    imageHolder1.addChild(e.target.content);

    //Add the loaded image to image holder 2
    imageHolder2.addChild(e.target.content);

    }

    Log in to Reply
  11. Simon says:

    Hi guys,

    Thanks for the tutorial – really straightforward and a handy skill to have when beginning in Flash.
    One thing though, is it possible for the images loaded in to the imageLoader to take up the entire stage area? I’ve tried to do this but when publishing, the images load over the text and buttons….

    Is there a simple solution for this?

    Any help would be appreciated,

    Thank again!

    Log in to Reply
  12. LoveFlash says:

    Hi love your tutorial, but i’m also getting the same error : The name of package ‘gs’ does not reflect the location of this file. Please change the package definition’s name inside this file, or move the file. C:\Documents and Settings\admin\Desktop\Darryl\gs\TweenLite.as

    Please let me know what i’m doing wrong I downloaded the GS folder and have it the same folder where all my .fla, .swf files.

    I would really appreciate more help on this
    You can email me @

    Thanx a million

    Log in to Reply
  13. dracea says:

    i have a problem … i just used your code on my website but it won`t work … i have changed the buttons name … added more buttons but … the error is something else… where can i send you the fla file so you can take a look at it?! thanks

    Log in to Reply
  14. igrek says:

    Hi,

    Was the issue with double clicking resolved?
    I have similar problem using this tutorial: in my case pictures randomly load on buttons click i.e. I can click let’s say on button 2 and nothing will happen, then on button 3 – nothing, then again on button 2 – picture will change.

    Any idea why it is happening?
    Thanks

    Log in to Reply
  15. Steve says:

    Hi All!
    I need to have text over image…How can I do???
    Thanks!

    Log in to Reply
  16. Slake says:

    For some reason, it is requiring double clicks half the time for the image to change. Anyone able to explain how to fix this? http://www.e7studios.com click on web development.

    Log in to Reply
  17. Ajay says:

    Any one can help me:
    for (i=0; i<4; i++) {
    var loader:Loader = new Loader();
    addChild(loader);
    loader.x =loader.y = i*100;
    loader.load(new URLRequest(img));
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageNotFound);

    }
    function imageNotFound(ev) {
    //Here what code I have to write for load default image if img not found?

    }

    Log in to Reply
  18. Slake says:

    Issue solved. Sorry for the several posts.

    Log in to Reply
  19. Slake says:

    Update: I found that if I take the default page 1 off, and click any of the buttons, it will load the image properly. However, when I try to click another one, the image will not change. I think the problem is in unloading whatever image is already loaded.

    Still working on it..

    Log in to Reply
  20. Slake says:

    To be more specific, my site can be found at e7studios.com. Click on Web development, and that is where I’m trying to get it to work. I want the projects below to bring up a separate image when clicked.

    http://www.e7studios.com/AS3Code.txt (My AS3 code that I’m using)
    http://www.e7studios.com/gallery.txt (My XML file)

    Again, it’s loading the first page perfectly, but it won’t change to the second page when the apollo_btn is clicked. Any help would be VERY appreciated!!

    Thanks,
    Slake

    Log in to Reply
  21. Slake says:

    Does the button have to be a MovieClip? I changed mine to SimpleButton, but for some reason the default (page1) image shows, but my buttons (that are not MovieClips) do not cause the page to change to page 2 or 3.

    Thanks,
    Slake

    Log in to Reply
  22. Gil says:

    mmm… nice nice
    The same idea was already created by http://www.wix.com it’s based on XML.
    If you thought about it 4 years ago, you might have opened a startup :-)

    Log in to Reply
  23. smonte says:

    Add the TweenLite “gs” folder to the same place where your .fla file is. That should solve the problem.

    Log in to Reply
    • coraguo says:

      Same problem :(
      Exactly the same code as yours, and paste the “gs” folder to the same place where the .fla exists, but still reported “URL not found”.
      What happened?

      Let me know if i did something wrong or ignored something else. ^^

      Thanks a lot, I appreciate it.

      Log in to Reply
  24. Hello:

    First of all you have very nice tutorials.

    This AS3 with XML pages tutorial is not working. I did 100% as written on your site.
    It can not find path to the TweenLite. I unzipped it and kept all the *.as files in the same folder.

    Please let m e know where should I put all the files and what will be the folder name.
    Will it be a separate folder?

    Please explain in details, I will really appreciate it.

    Thanks and regards,

    Log in to Reply

Leave a Reply

You must be logged in to post a comment.