Build a XML Driven Horizontal Images Slider

Build a XML Driven Horizontal Images Slider

In this Actionscript 3 tutorial, learn step by step how to build a XML driven Horizontal World Cup Images Slider that the user controls with buttons or keyboard.

View DemoDownload Source

1. Create a new flash file (Actionscript 3.0) and save it as images-slider.fla.

2. Rename “layer 1″ to “buttons”. Create the previous and next buttons and give them respective instance names of “previous_btn” and “next_btn”.

Screenshot

3. Create a new layer named “loading infos”. With the Text tool, create a Dynamic text and give it an instance name of “loading_txt”. We’ll use it later to inform the user about the images’ loading progression.

4. Create a new layer named “container”.
First let’s create a mask that will use to display only 3 images on the screen. As our images are 260px*196px, and that we want to display 3 images and let some space between the images (10px), in our case we have drawn a Rectangle of 800px*196px. Adjust the rectangle size according to your needs. Convert it to a Movie Clip with an instance name of “slider_mc”. Enter this movie clip to edit it. Reselect the rectangle shape and convert it to a Movie clip with an instance name of “mask_mc”.

5. We’ll store the images’ datas in an XML file. Create an xml file that match the following structure and save it as datas.xml. Put all your images inside an “images” folder.

<?xml version="1.0" encoding="UTF-8" ?>
<images>
	<image src="1.jpg"/>
	<image src="2.jpg"/>
	<image src="3.jpg"/>
	<image src="4.jpg"/>
	<image src="5.jpg"/>
	<image src="6.jpg"/>
	<image src="7.jpg"/>
	<image src="8.jpg"/>
	<image src="9.jpg"/>
	<image src="10.jpg"/>
	<image src="11.jpg"/>
	<image src="12.jpg"/>
	<image src="13.jpg"/>
	<image src="14.jpg"/>
	<image src="15.jpg"/>
	<image src="16.jpg"/>
</images>

6. Create an “actions” layer. We’ll use the Tweenlite engine, so first go download its AS3 version. Open the actions panel.
First make the following imports in order to use the Twenlite engine and its easing properties.

import com.greensock.*;
import com.greensock.easing.*;

7. Next declare the following variables.

var xml:XML;
var images:Array = new Array();
var totalImages:Number;  
var nbDisplayed:Number = 3; // Number of images displayed on the screen
var imagesLoaded:int = 0;
var slideTo:Number = 0;
var imageWidth = 270;  // our images are 260px wide so we set to 270 to let some space when will position them

8. Create a new MovieClip where we’ll place all the images and set its mask property to the mask we’ve created before.

var container_mc:MovieClip = new MovieClip();
slider_mc.addChild(container_mc);
container_mc.mask = slider_mc.mask_mc;

9. Load the XML file by creating a loadXML funtion. When the load is complete, it will call the parseXML function.

function loadXML(file:String):void{
	var xmlLoader:URLLoader = new URLLoader();
	xmlLoader.load(new URLRequest(file));
	xmlLoader.addEventListener(Event.COMPLETE, parseXML);
}

10. Then we need to parse the XML. We set our xml variable to the xml data, get the total amount of images and call the loadImages function.

function parseXML(e:Event):void{
	xml = new XML(e.target.data);
	totalImages = xml.children().length();
	loadImages();
}

11. Inside the loadImages function, we create a “for” statement to loop through the xml datas to create a Loader for each image. We store the Loader inside our images Array variable, and we add listeners for the ProgressEvent.PROGRESS event and the Event.COMPLETE event.

function loadImages():void{
	for(var i:int = 0; i<totalImages; i++){
		var loader:Loader = new Loader();
		loader.load(new URLRequest("images/"+String(xml.children()[i].@src)));
		images.push(loader);
		loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
	    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
	}
}

12. The onProgress function is used to warn the user about the progression of the images’ loading.

function onProgress(e:ProgressEvent):void{
	loading_txt.text = "Loading " + imagesLoaded + " / " + totalImages;
}

13. The onComplete function checks whether all images are loaded. If so, it calls the createImages() function.

 
function onComplete(e:Event):void{
	imagesLoaded++;
	if(imagesLoaded == totalImages){
		loading_txt.text = "";
		createImages();
	}
}

14. Inside the createImages() function, create a “for” statement to loop through the images array in order to create a bitmap object. We set the x property of the bitmap by multiplying the i variable with our imageWidth variable. And we add the bitmap to the container_mc.

function createImages():void{
	for(var i:int = 0; i < images.length; i++){
		var bm:Bitmap = new Bitmap();
		bm = Bitmap(images[i].content);
		bm.smoothing = true;
		bm.x = i*imageWidth;
		container_mc.addChild(bm); 
	}
}

15. At this point, we’ve finished loading our images. Now let’s take care about the buttons to slide left and right.
Add the CLICK event listeners for both buttons.

previous_btn.addEventListener(MouseEvent.CLICK,slideLeft);
next_btn.addEventListener(MouseEvent.CLICK,slideRight);

16. At the beginning, we’ve created a slideTo variable. We’ll use it to store the number of the image we want to slide to (the one that we see on the left).
In the slideLeft function we want to go 3 (nbDisplayed = 3) images to the left whereas in the slideRight function we want to go 3 images to the right.

function slideLeft(e:MouseEvent):void{
	slideTo -= nbDisplayed;
	slideContainer();
}

function slideRight(e:MouseEvent):void{
	slideTo += nbDisplayed;
	slideContainer();
} 

17. The slideContainer() functions checks at first if we can actually move that far to the left or right so that there’s always 3 images displayed. If not we set the slideTo variable to the appropriate value. Then we use the Tweenlite engine to animate the x property of “container_mc”.

function slideContainer():void{
	if(totalImages - slideTo < nbDisplayed)
		slideTo = totalImages - nbDisplayed;
	if(slideTo < 0)
		slideTo = 0;
		
	TweenLite.to(container_mc,.5,{x:-slideTo*imageWidth,ease:Quad.easeIn});	
}

18. Next we add keyboard functionnality to allow the user to navigate with the right and left arrow keys.

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyHandler);

function keyHandler(evt:KeyboardEvent) {
	if(evt.keyCode == Keyboard.LEFT)  slideLeft(evt);
	else if(evt.keyCode == Keyboard.RIGHT) slideRight(evt);
}

19. Finally, don’t forget to call the loadXML function to make all that works.

loadXML("datas.xml");

20. Here’s the final code, test your movie to see it in action.

import com.greensock.*;
import com.greensock.easing.*;

var xml:XML;
var images:Array = new Array();
var totalImages:Number;
var nbDisplayed:Number = 3;
var imagesLoaded:int = 0;
var slideTo:Number = 0;
var imageWidth = 270; 

var container_mc:MovieClip = new MovieClip();
slider_mc.addChild(container_mc);
container_mc.mask = slider_mc.mask_mc;

function loadXML(file:String):void{
	var xmlLoader:URLLoader = new URLLoader();
	xmlLoader.load(new URLRequest(file));
	xmlLoader.addEventListener(Event.COMPLETE, parseXML);
}

function parseXML(e:Event):void{
	xml = new XML(e.target.data);
	totalImages = xml.children().length();
	loadImages();
}

function loadImages():void{
	for(var i:int = 0; i<totalImages; i++){
		var loader:Loader = new Loader();
		loader.load(new URLRequest("images/"+String(xml.children()[i].@src)));
		images.push(loader);
		loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
	    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
	}
}

function onProgress(e:ProgressEvent):void{
	loading_txt.text = "Loading " + imagesLoaded + " / " + totalImages;
}

function onComplete(e:Event):void{
	imagesLoaded++;
	if(imagesLoaded == totalImages){
		loading_txt.text = "";
		createImages();
	}
}

function createImages():void{
	for(var i:int = 0; i < images.length; i++){
		var bm:Bitmap = new Bitmap();
		bm = Bitmap(images[i].content);
		bm.smoothing = true;
		bm.x = i*imageWidth;
		container_mc.addChild(bm); 
	}
}

previous_btn.addEventListener(MouseEvent.CLICK,slideLeft);
next_btn.addEventListener(MouseEvent.CLICK,slideRight);

function slideLeft(e:MouseEvent):void{
	slideTo -= nbDisplayed;
	slideContainer();
}

function slideRight(e:MouseEvent):void{
	slideTo += nbDisplayed;
	slideContainer();
} 

function slideContainer():void{
	if(totalImages - slideTo < nbDisplayed)
		slideTo = totalImages - nbDisplayed;
	if(slideTo < 0)
		slideTo = 0;
		
	TweenLite.to(container_mc,.5,{x: -slideTo*imageWidth,ease:Quad.easeIn});	
}

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyHandler);

function keyHandler(evt:KeyboardEvent) {
	if(evt.keyCode == Keyboard.LEFT)  slideLeft(evt);
	else if(evt.keyCode == Keyboard.RIGHT) slideRight(evt);
}

loadXML("datas.xml");

15 thoughts on “Build a XML Driven Horizontal Images Slider

  1. Ash baby

    the tutorial sounds good mate,

    bt theres is sum problem with folder structure of

    “import com.greensock.*;
    02.import com.greensock.easing.*;”

    or please provide the proper as tween structure in source file DUDE!

    thnx

  2. Sean

    I LOVE this example! i want to take it a step further and add Title and Descriptions, and i’m having a hard time figuring out how to do that, any help would be appreciated.

  3. px87

    Hi!! great page and great tutorial, 1000 thanks for it!!!

    I have a cuestion… How can I do this slide infinite?

    greetings.

  4. wolfgang

    Hi mate,

    your tutorial is great. it really help flash newbies a lot. by the way im just curios on how to make the image slider loop on the images when it reaches the end of the line.. what i mean is that when it reaches the last image by pressing the next button, it will continue again with the first image as if it has an infinite loop. it looks like it is a carousel where in the last image is connected with the first image..

    million thanks…

    best regards

  5. scot

    nice site,
    as above. Also I would also like to know how to add individual buttons to allow you to skip to random images?? Maybe you could do another tutorial or maybe not?

    greetings

    Scot

  6. Cat

    Hi- I like the demo.

    New to all the coding and I am not clear on a lot of this. Visuals would help me coordinate
    the code with what’s going on the stage through the process.

    Where is the best place to download the Tweenlite?

    I realize these are probably basic questions.
    As I said I’m new and just learning. I can follow directions but I feel I need more info here. More specifics.

    Would like to continue with trying to set this up – need some guidance.
    Thanks

  7. Pingback: Build a XML Driven Horizontal Images Slider « GuarniBlog

  8. Elena

    May i please ask you how can i create a slider for the interactive Flashcards (for learning foreign languages)? I have learned how to create the interactive Flashcard (each card is with multiple layers and buttons on it) and each finished Flashcard is in the separate fla document.

    Now i realize i need a slider with the button to go from one Flashcard to the next, and somehow bundle all the Flashcards into one fla document. And then publish it.

    I can see many sites where people have language flashcards where they click to see “the flip side of the card” or the translation of separate sections of the Flashcard(like a quiz), and then click to slide to the next Flashcard, can that be done with Flash 8??

    Your guidance is greatly appreciated. Thank you.

  9. Fabian

    I also have to thank you for the great description. I also wondered about how to add titles to the pictures and a restart function to the slide after the last image. But the biggest problem I try to solve at the moment is this:
    I created the *swf and imported it in my dreamweaver site. When I look at the preview in the browser the slider works just fine, but when I upload the files on my server and try out the page I just see the buttons of the *smf but no pictures?! The path to the picture should be right, as it worked in the preview or not? Do i have to change any code? Where?
    It would be great to here if you have any idea what to do.
    Sorry, i´m also a beginner.
    Thank you very much for your help in advance.
    Fabian

  10. Medriloth

    Hey :)

    I was wondering, if it were possibly to make the images link to frames in flash? Meaning, when one click a image, it would gotoAndPlay a frame in flash?

    Any ideas?

  11. LostMind

    Hello Riacodes

    It’s a vary great image slider! I like it :D, but how can I make it, when I click of an image, it’s open in new window? If that function is in it, than it’s can working like image slider gallery. It would be awesome.

    Please help to make it :)

    LostMind

  12. Axel

    Why doesn’t it load the images?

    My file structure is as follows:

    - Folder: flash file is here. Images folder is here. dtas.xml file is here. com folder is here.
    - Images folder: my actual images are here (same names as in the xml file).

    Flash Output window gives me this message: Error #2044 IOErrorEvent: text=Error # 2035: URL not found

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>