| |
Create a Flash Actionscript 3.0 Slideshow with XML |
|
This tutorial shows you how to create a simple slideshow using as3/flash and xml like this one. In order to complete this tutorial you can download the source files here. In our xml file, we want to store the path to the slides and a description for each of it. So let’s take a look at the example file
<?xml version="1.0" encoding="UTF-8"?> <slideshow> <image src="images/fly.jpg" desc="Fly"/> <image src="images/mouse.jpg" desc="Computer mouse"/> <image src="images/country.jpg" desc="Country"/> <image src="images/rope.jpg" desc="Rope"/> <image src="images/flower.jpg" desc="Flower"/> </slideshow>
On the first line we describe the version and the encoding of the file. Flash uses UTF-8 for encoding, so we should edit the file in UTF-8 only to avoid character encoding problems.
The first node defines the root node of the xml file and contains further nodes. These are the images with the attributes src and desc. Okey, that’s how the structure of the xml looks like, let’s move on to the flash file.
The stage has a movieclip which contains the textfields which will show us the description of the slides, the loading process and the slide count later. Under it you will find a mask layer which masks an empty movieclip, where our slides will be loaded into. And on our first layer we have the whole script, at wich we’ll take a look now.
As always, we need to import the necessary librarys first. In our case, we only have caurinas tweener engine which will later be used to fade in the slides.
import caurina.transitions.Tweener;
Then we define two constants. One for the delay between the slides in milliseconds and the other one for the fade time between the slides in seconds. You can change them freely according to your needs
const TIMER_DELAY:int = 5000; const FADE_TIME:int = 1;
Now we need to set some variables for the slideshow. We’re beginning with a variable, that holds a reference to the current container which holds the slide and is in the front
var currentContainer:Sprite;
To know which slide is currently active, we set a integer. We start at -1 because the function switchSlide will go to the first slide, which is 0.
var intCurrentSlide:int = -1;
The total count of the slides will be stored in a integer variable
var intSlideCount:int;
Then we need to define a timer, which calls the switchSlide function after the delay time we set in the constant
var slideTimer:Timer;
To have a nice fade effect, we need two containers for the slides. Each one will contain one slide
var sprContainer1:Sprite; var sprContainer2:Sprite;
Next we set a variable for loading our slides
var slideLoader:Loader;
The next variable defines the path to the xml file
var strXMLPath:String = "slideshow-data.xml";
xmlLoader will be used to load the xml file
var xmlLoader:URLLoader;
And finally we need a variable to store the xml stuff
var xmlSlideshow:XML;
Now we need to initialize the whole slideshow. First, we create a new urlloader for the slideshow xml file, add an event listener when it’s completely and load it
xmlLoader = new URLLoader(); xmlLoader.addEventListener(Event.COMPLETE, onXMLLoadComplete); xmlLoader.load(new URLRequest(strXMLPath));
Then we create the time with the delay from the constant and add an event listener for the timer event
slideTimer = new Timer(TIMER_DELAY); slideTimer.addEventListener(TimerEvent.TIMER, switchSlide);
Next we create 2 container sprite which will hold the slides and add them to the masked movieclip
sprContainer1 = new Sprite(); sprContainer2 = new Sprite(); mcSlideHolder.addChild(sprContainer1); mcSlideHolder.addChild(sprContainer2);
And last of all, we keep a reference of the container which is currently in the front
currentContainer = sprContainer2;
Once our xml file is fully loaded, the function onXMLLoadComplete will be called. This function assigns the received data to xmlSlideshow, gets the total slide count and stores it in the variable intSlideCount. Then it’ll call the function switchSlide which will immediately load the next slide without waiting on the timer event.
xmlSlideshow = new XML(e.target.data); intSlideCount = xmlSlideshow..image.length(); switchSlide(null);
Ok, let’s move on to the switchSlide function. This function will be called every time the timer has reached the delay and fires the timer event. First of all, we check, if the timer is running and stop it, because we need to wait until the next slide will be loaded and faded in. Then we check if there are any slides left. If not, we go back to the beginning. Now we need to figure out, wich container is currently in the front and assign currentContainer to the one, that’s in the back containing the old slide. Next we hide the old slide and bring it to the front.
if(slideTimer.running) slideTimer.stop(); if(intCurrentSlide + 1 < intSlideCount) intCurrentSlide++; else intCurrentSlide = 0; if(currentContainer == sprContainer2) currentContainer = sprContainer1; else currentContainer = sprContainer2; currentContainer.alpha = 0; mcSlideHolder.swapChildren(sprContainer2, sprContainer1);
Then we create a new loader for the slide. We add an event listener when it’s loaded and an event listener for the progress of the loading. Next we load the picture with a urlrequest that contains the source path to the current image. And last of all, we show the description of the slide on the lbl_description and update the current number of the slide on lbl_count.
slideLoader = new Loader(); slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, fadeSlideIn); slideLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress); slideLoader.load(new URLRequest(xmlSlideshow..image[intCurrentSlide].@src)); mcInfo.lbl_description.text = xmlSlideshow..image[intCurrentSlide].@desc; mcInfo.lbl_count.text = (intCurrentSlide + 1) + " / " + intSlideCount + " Slides";
The showProgress function is quite small. It’s just one line that calculates the percentage of the bytes loaded from the current slide and displays it on the lbl_loading
mcInfo.lbl_loading.text = "Loading..." + Math.ceil(e.bytesLoaded * 100 / e.bytesTotal) + "%";
The last function is fadeSlideIn and will be called once the picture is fully loaded. First, we add the loaded slide from the slideLoader to the current container. Then we clear the preloader text. And finally, we fade the current container in with caurinas tweener engine and start the slide timer when the tween is finished. Like this, we’ll have an endless loop, which will switch the slides.
currentContainer.addChild(slideLoader.content);
mcInfo.lbl_loading.text = "";
Tweener.addTween(currentContainer, {alpha:1, time:FADE_TIME, onComplete:function(){ slideTimer.start();} });
}
That was already it. I hope you enjoyed reading the tutorial. Please feel free to ask questions or leave a feedback.
Full code with comments
// import tweener
import caurina.transitions.Tweener;
// delay between slides
const TIMER_DELAY:int = 5000;
// fade time between slides
const FADE_TIME:int = 1;
// reference to the current slider container
var currentContainer:Sprite;
// index of the current slide
var intCurrentSlide:int = -1;
// total slides
var intSlideCount:int;
// timer for switching slides
var slideTimer:Timer;
// slides holder
var sprContainer1:Sprite;
var sprContainer2:Sprite;
// slides loader
var slideLoader:Loader;
// url to slideshow xml
var strXMLPath:String = "slideshow-data.xml";
// slideshow xml loader
var xmlLoader:URLLoader;
// slideshow xml
var xmlSlideshow:XML;
function init():void {
// create new urlloader for xml file
xmlLoader = new URLLoader();
// add listener for complete event
xmlLoader.addEventListener(Event.COMPLETE, onXMLLoadComplete);
// load xml file
xmlLoader.load(new URLRequest(strXMLPath));
// create new timer with delay from constant
slideTimer = new Timer(TIMER_DELAY);
// add event listener for timer event
slideTimer.addEventListener(TimerEvent.TIMER, switchSlide);
// create 2 container sprite which will hold the slides and
// add them to the masked movieclip
sprContainer1 = new Sprite();
sprContainer2 = new Sprite();
mcSlideHolder.addChild(sprContainer1);
mcSlideHolder.addChild(sprContainer2);
// keep a reference of the container which is currently
// in the front
currentContainer = sprContainer2;
}
function onXMLLoadComplete(e:Event):void {
// create new xml with the received data
xmlSlideshow = new XML(e.target.data);
// get total slide count
intSlideCount = xmlSlideshow..image.length();
// switch the first slide without a delay
switchSlide(null);
}
function fadeSlideIn(e:Event):void {
// add loaded slide from slide loader to the
// current container
currentContainer.addChild(slideLoader.content);
// clear preloader text
mcInfo.lbl_loading.text = "";
// fade the current container in and start the slide timer
// when the tween is finished
Tweener.addTween(currentContainer, {alpha:1, time:FADE_TIME, onComplete:function() { slideTimer.start(); }});
}
function switchSlide(e:Event):void {
// check, if the timer is running (needed for the
// very first switch of the slide)
if(slideTimer.running)
slideTimer.stop();
// check if we have any slides left and increment
// current slide index
if(intCurrentSlide + 1 < intSlideCount)
intCurrentSlide++;
// if not, start slideshow from beginning
else
intCurrentSlide = 0;
// check which container is currently in the front and
// assign currentContainer to the one that's in the back with
// the old slide
if(currentContainer == sprContainer2)
currentContainer = sprContainer1;
else
currentContainer = sprContainer2;
// hide the old slide
currentContainer.alpha = 0;
// bring the old slide to the front
mcSlideHolder.swapChildren(sprContainer2, sprContainer1);
// create a new loader for the slide
slideLoader = new Loader();
// add event listener when slide is loaded
slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, fadeSlideIn);
// add event listener for the progress
slideLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
// load the next slide
slideLoader.load(new URLRequest(xmlSlideshow..image[intCurrentSlide].@src));
// show description of the next slide
mcInfo.lbl_description.text = xmlSlideshow..image[intCurrentSlide].@desc;
// show current slide and total slides
mcInfo.lbl_count.text = (intCurrentSlide + 1) + " / " + intSlideCount + " Slides";
}
function showProgress(e:ProgressEvent):void {
// show percentage of the bytes loaded from the current slide
mcInfo.lbl_loading.text = "Loading..." + Math.ceil(e.bytesLoaded * 100 / e.bytesTotal) + "%";
}
// init slideshow
init();
Other Posts You Might Like
Hi, Thank you Rafael for this article, but I have to admit that it's a little bit to much for me, I got a lots of errors and I gave up. Recently, I found a website with a lot of slideshows based on xml, here: http://www.flashxml.net/components .I recommend it
JohnS Hey man,
Thanks for sharing the link, really nice collection of components. I know I should really "code my own" :-D, but it's nice that you can just use one out of the box and works great, too.
You could have mentioned that they're really easy to use, everything is done with their demo control panel...
Added my images, image comments and links in a couple of minutes. Had it running on my friend's site in less than half an hour. I really recommend this too!
www.flashxml.net/image-scroller.html
gabriel duboisJohnS
Hi, Thank you for FlashXML website, I'm ashamed to admit that I didn't knew about it but now I can't get apart of it. I am so glad that you share this. Bless you!
Hi i have problem with load external swf trough xml
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at banner_fla::MainTimeline/init()
at banner_fla::MainTimeline/frame1()
Images work ok, but swf crash
Thx for reply
Hi there,
having trouble with mc errors... any ideas?
thanks
1120: Access of undefined property mcSlideHolder.mcSlideHolder.addChild(sprContainer1);
mcSlideHolder.addChild(sprContainer2);
etc
Halloooo....
Can you tell me how to put slideshow on Gaia Framework?
Thank you so much
Here my email: wiyono04@yahoo.com
Regard
Wiyono
How can I add a call-to-action button that corresponds with each image fade in with each image and have the button text change with a description
Has anyone realized that the browser plugin-container.exe keeps incrementing? If left on long enough, it will cause the sideshow and browser to crash... Any ideas on how to fix?
Hi,
great tutorial. But I noticed (even in your files without any modification) that the first image is always visible a short moment during the fading. How that can be fixed?
Hi, this one is very nice!!
but how can I make 3 thumbnails (or slideshows) in a row with this code in one .swf, so they do the same work and get files and descriptions from one xml?
thank you!!
Is there any way to make the different images clickable with this? Add different links to each picture ?
This is my XML file......
Name : Vikrant Aggarwal
DOB : August 25 1982
Sex : Male
City : Dehradun
an1.jpeg
This is my AS.........
function loadXMLData(loaded) {
if (loaded) {
_root.abc = this.firstChild.childNodes[0].childNodes[0].firstChild.nodeValue;
abc_txt.text = _root.abc;
_root.abcd = this.firstChild.childNodes[0].childNodes[1].firstChild.nodeValue;
abcd_txt.text = _root.abcd;
_root.abcde = this.firstChild.childNodes[0].childNodes[2].firstChild.nodeValue;
abcde_txt.text = _root.abcde;
_root.abcdef = this.firstChild.childNodes[0].childNodes[3].firstChild.nodeValue;
abcdef_txt.text = _root.abcdef;
var path:String = this.firstChild.childNodes[1].childNodes[0].firstChild.nodeValue, imageLoader;
trace(path);
loadMovie(path, imageLoader);
}
else {
}
}
xmlFile = new XML();
xmlFile.ignoreWhite = true;
xmlFile.onLoad = loadXMLData;
xmlFile.load("data.xml");
i want to load an1.jpeg but i think im doing wrong.....i put my xml,and fla and jpeg in same folder........help me
My bad. My images were the wrong size and sucking up the memory. Thanks again for a great tutorial. I resized and saved for the web and it WORKS!!!
Thanks for the great tutorial. I have customized it, not changing any code. I added addtional images to the xml. When it plays, it shows all slides and captions up to #8, then the image doesn't change but the description text does change and then hangs up. In my test slideshow the counter works up to 9 of 20. it even changes the description again, 10 different captions but only 8 of the 20 images. Then it stops. Eventually, I have 52 lides with captions I want to load from the XML. Is there a restriction on the number of slides somewhere? I can't seem to figure it out.
Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type. Any help is most appreciated.
has anyone tried this with images that arent the same size?
it works great but when an image that is smaller than the previous one shown is faded in, the last image is still visible in the background.
ive been trying to just make the image disappear when the new one fades in but i just cant find the way, can someone please help me here
if picture1 is showing, picture2 fades in and picture1 goes to the back, how do you make picture1 fadeout?
Is it possible to reload the XML file after all the slides have passed?
I tried to add a reload function with a timer, but when it reloads the XML file it also skips an image...
Kind regards,
Niels
Great tutorial! I am looking to add an extra layer to your code... I have the slideshow in a movieclip and I have my navigation on the main timeline (home, aboutus,etc) I am trying to change the xml file based on where you are at. For example show a differnt slide show for HOME and another for ABOUT US. I tried passing a variable to the child movie clip, but I am not having any luck! Any direction would be appreciated.
Hello all !
probably not the place to ask this.... I adapted this flash and it works perfectly...on my computer. When i trto insert the code on my website y get this message and nothing appears:
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: slideshow-data.xml
at slideshow_fla::MainTimeline/init()
at slideshow_fla::MainTimeline/frame1()
somebody has an idea ?
thx
Created a script to create the xml file
to use copy it and save it with a .py extension and put it in the root of the directory of the slide show:
import os
import re
# relative path to the pictures
image_path = "./images/"
# files to search for to change add the file extension in () with |
# ie add |(file_type)
images_re = re.compile(r'\.(jpg)|(jpeg)', re.I)
# file name to write the xml date to
xml_file_name = "slideshow-data.xml"
def PathTrue(path):
if (os.access(image_path, os.F_OK) == True):
return path
def GetImages(image_path):
images=[]
files = os.listdir(image_path)
for f in files:
if (images_re.search(f) != None):
images.append(f)
return images
def MakeXmlString(image_list):
image_list.sort()
xml_string = "\n\t"
for image in image_list:
xml_string += "\n\t" % (image, image)
xml_string += ""
return xml_string
def CreateXMLFile(xml_string, xml_file_name):
file = open(xml_file_name, 'w', 100)
file.write(xml_string)
file.close()
if (image_path == PathTrue(image_path)):
image_list = GetImages(image_path)
if (len(image_list) > 1):
xml_string = MakeXmlString(image_list)
CreateXMLFile(xml_string, xml_file_name)
else:
print "No Images Found"
else:
"The Image Director is not found"
i got this error
D:\WORK2Flash\caurina\transitions\Tweener.as, Line 1 5007: An ActionScript file must have at least one externally visible definition.
Hi!
Really great site all in all!
and Great Tutorial!
View mine at http://www.fabian-irsara.com/blog/2010/05/as3-xml-...
Best regards,
Fabian
The tutorial is good but shitty... it allows a ghost image to appear during the transition. I only was able to fix it thanks to Leonardo's comment, but the OP should fix this confusing article too.
hi, THANKS
its good and this tutorial is very useful for me,
u done a great job please tell me how can i change the different image transistion.
Please tell me, how can i integrate a slideshow with the following flash template: http://www.flashmo.com/preview/flashmo_175_photo_g... ? I've been trying stuff for 7 hours, but i just can't figure it out. Please help me, i am kinda new to as3, so your help will be greatly appreciated.
Cheers,
Johan
any way to customize this so it works with actionscript 2.0?
I'm building a website, and everything else I need to be in 2.0 because of the way I have coded it, so this slideshow doesn't even show up.
Any ideas would be awesome, thanks!
This is a great script, I made a few modifications for a project I was working on. I used this as the base for a manual slide show.
I created two movie clips on the stage and respectively named them:
"forward_btn" and "back_btn"
MODIFIED SCRIPT BELOW
__________________________________________________
// import tweener
import caurina.transitions.Tweener;
// delay between slides
const TIMER_DELAY:int = 5000;
// fade time between slides
const FADE_TIME:int = 1;
// reference to the current slider container
var currentContainer:Sprite;
// index of the current slide
var intCurrentSlide:int = -1;
// total slides
var intSlideCount:int;
// slides holder
var sprContainer1:Sprite;
var sprContainer2:Sprite;
// slides loader
var slideLoader:Loader;
// url to slideshow xml
var strXMLPath:String = "slideshow-data.xml";
// slideshow xml loader
var xmlLoader:URLLoader;
// slideshow xml
var xmlSlideshow:XML;
function init():void {
// create new urlloader for xml file
xmlLoader = new URLLoader();
// add listener for complete event
xmlLoader.addEventListener(Event.COMPLETE, onXMLLoadComplete);
// load xml file
xmlLoader.load(new URLRequest(strXMLPath));
// create 2 container sprite which will hold the slides and
// add them to the masked movieclip
sprContainer1 = new Sprite();
sprContainer2 = new Sprite();
mcSlideHolder.addChild(sprContainer1);
mcSlideHolder.addChild(sprContainer2);
// keep a reference of the container which is currently
// in the front
currentContainer = sprContainer2;
}
function onXMLLoadComplete(e:Event):void {
// create new xml with the received data
xmlSlideshow = new XML(e.target.data);
// get total slide count
intSlideCount = xmlSlideshow..image.length();
// switch the first slide without a delay
switchSlide(null);
}
function fadeSlideIn(e:Event):void {
// add loaded slide from slide loader to the
// current container
currentContainer.addChild(slideLoader.content);
// clear preloader text
mcInfo.lbl_loading.text = "";
// fade the current container in and start the slide timer
// when the tween is finished
Tweener.addTween(currentContainer, {alpha:1, time:FADE_TIME});
}
function switchSlide(e:Event):void {
// check if we have any slides left and increment
// current slide index
if(intCurrentSlide + 1 0)
intCurrentSlide--;
// if not, start slideshow from beginning
else
intCurrentSlide = 0;
// check which container is currently in the front and
// assign currentContainer to the one that's in the back with
// the old slide
if(currentContainer == sprContainer2)
currentContainer = sprContainer1;
else
currentContainer = sprContainer2;
// hide the old slide
currentContainer.alpha = 0;
// bring the old slide to the front
mcSlideHolder.swapChildren(sprContainer2, sprContainer1);
// create a new loader for the slide@src
slideLoader = new Loader();
// add event listener when slide is loaded
slideLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, fadeSlideIn);
// add event listener for the progress
slideLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
// load the next slide
));
// show description of the next slide
mcInfo.lbl_description.text = xmlSlideshow..image[intCurrentSlide].@desc;
// show current slide and total slides
mcInfo.lbl_count.text = (intCurrentSlide + 1) + " / " + intSlideCount + " Slides";
}
// init slideshow
init();
/**********************
Here I am adding forward and backward button
functionality I have removed the timer code.
***********************/
forward_btn.addEventListener(MouseEvent.CLICK, switchSlide);
back_btn.addEventListener(MouseEvent.CLICK, switchSlideBack);
Cool tut, but one question, how do you remove the descripton bar? For the porpouse that i want, i don't need the description bar. Can you help me? and how can resize it?
Thank you Very much, es a great tut,
Good Tut man!!, but one question, this works with Flash 8? 'cause i use the flash 8.
And there's any way to change the size of the movie?. or the pictures do it...
I just want to leave a note and tell you how much I appreciate your code and tutorial. Very nice and useful! Thanks a lot!
Brad: Try to download the tut-file: http://www.thetechlabs.com/tutorials/files/flash/r...
And see how thing is done...
So, I'm a bit confused, trying to do this tutorial with almost no knowledge of what goes where ;) .. is there any beginner guides that would cover something like this? I'm just not seeing where to put the code at. (I seriously just started using flash within the last week.) Also, I got the xml thing down, that was as simple as can be, I just don't know my way around Flash Pro CS4. I use dreamweaver daily however.
Great tutorial! I have the same question as Amanda. I noticed the link in xml works on an image, but how would I go about link to text within the description so that just a portion of the text is link? I scoured the web and they say to use CDATA but I get parsing errors when I try that.
Thanks again!
Hehe :) Simple slideshow, but it's not enouth, imho :) Nice tutorial, thow :)
I have coded a smooth xml picture gallery with slideshow functionality, check it out here: bit.ly/7aWzXt
Okay I got it all functioning well but the images are terribly pixelated. What suggestion do you have to fix the compression. Seeing as they are pulled in through XML I am not sure how to set the compression for the images.
Thank you for this good code. At some point I will transform it to become object orientated, with the XML loading separate from the slide engine, so that it can be called from any project as an encapsulated entity..
But this does the trick just fine!
Best,
Sebastian.
Can you help me...I keep getting this error message:
Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
Here is part 2:
http://www.thetechlabs.com/tutorials/xml/extending...
Become a TTL VIP Member & Get Notified of The Best Changes in Technology, Plus Win Prizes in Our VIP Only Contests...









hello, all
i wanted to help and add in something important for the images - smoothing! just add this code after the line i have noted; enjoy, jodi :)
currentContainer.addChild(slideLoader.content);
/****** smoothing ******/
var smoother_bm=Bitmap(slideLoader.content);
smoother_bm.smoothing=true;
- spam
- offensive
- disagree
- off topic
Like