1. Code
  2. XML

Build a Dynamic Flash Gallery with Slider Control


In this tutorial, we'll create a gallery which displays all image files in a given directory. A slider is used to browse easily through the images.

Step 1

Set up a new Flash AS3 document and a blank ActionScript file. We'll create the main class first; name it "Gallery" and save it as "". Below is the code to set up the first class:

In Flash we can now set this as the base class by entering the name in the input box under the Publish settings of the document. You can try a "trace('hello world')" in the Gallery function to test if it's working.

Step 2

Before we continue with the main class, it's best to start off with the slider. The code is fairly easy to understand and might shine some light on how things are done in AS3.

Create two new movieclips: a slider and a handle for the slider. The slider or seeker doesn't need to be exported for ActionScript as we only need to apply some functions to the handle. Set the class for the handle as "Handle". We can now create a new class called "Handle" and, if saved in the same directory, Flash will automatically use this class for the handle. Give both an instance name such as "slider" and "theHandle".

Step 3

The following is the full code for the handle which I will explain in steps. It should be saved as "" in the same directory as your .fla. This way, Flash will execute the code once an instance with a class name "Handle" is used.

In the first few lines we create a few variables to hold data we can use in every function in this class. The slider variable holds a reference to the instance called "slider" on the parent. We need it to correctly calculate the x position to which the handle should be moved. In the constructor we set "buttonMode" to true so a hand cursor shows up when hovering over the handle. Additionally, we add two eventlisteners to listen for mouse events.

Once a mouse down event occurs, an extra listener is added. This listener stays active as long as the drag movement isn't stopped and calls the "followHandle" function. It's removed again when the mouse click is over.

This last function actually moves the handle around. The variable "newPos" stores the new position to which the handle should move. If, however, this position is further than the far left or right of the slider, the position should be set to the maximum possible value. If the handle is moved, we dispatch a new custom event called "sliding", which we can later use to move around the images.

Step 4

If everything's gone well until now, you should have a nice functional slider like the one below. Add a dynamic textfield underneath it which will hold the image number. Give it an instance name like "countTxt" so we can address it later in ActionScript. Because there's nothing to display yet I filled it with the text "Loading" which will also display while the script loads the first image.

Step 5

Next we'll create the php backend script. Flash can't read the contents of a local directory, so we need to pass the information from php to Flash. We'll use XML since it's easy to output with php and even easier to read again in AS3.

The following is the php backend code, save it as "backend.php". The code loops through the directory "img" and writes a line of XML for each file in there. Before printing we need to filter out the "." and ".." directories. As the directory only contains images there's no further checking necessary.

This will output for example:

Step 6

Before we load this into Flash, let's create a class to hold our images individually. In the same way we created the Handle class we can now create an Img class. Start off with creating a movieclip about the size you want your images to be displayed. Give it a margin of a few pixels and save some space on the bottom for the description text. Add a dynamic text field for the description and give it an instance name of "descr". Make sure to set the registration point of the movieclip to the center so we can easily scale it later. Export it for ActionScript under the class name "Img". Now delete the instance from the stage as we'll call it directly from the library.

Step 7

Next we'll load the information the php file returns into our Flash project using ActionScript. Open up the Gallery class again. The following code adds two functionalities to our project. First off, it creates "imagesClip", an empty movieclip in which we'll store the actual images later. Using "addChild" here adds the movieclip to the stage. Anything added to imagesClip later will also appear on the stage. To actually load the xml data, we create a "URLLoader". This class can fetch the results and run a function when the results are in.

Here we use the load function of the URLLoader class. To prevent caching of the results we can add a simple date to the end of the url. The eventlistener checks when the URLLoader is finished and then runs the loadImages function.

This next function loops through all the <img> instances in the xml. For each of these it creates a new instance of the Img class. Next we add it to the imagesClip (this is just for testing as later on we only want the active images to be displayed).

Step 8

To give our Img instances more functionality, create an Img class and save it as "". In a similar way to loading the XML we can load the image itself and display it inside the Img movieclip. The loading should not occur in the constructor or all images would try to load at the same time; we'll create a separate function for doing this.

In the constructor, we set a reference to the main Gallery class so we can later access elements on the stage or public variables and functions of the main class. The string "load" will contain the path to the image which php returned, we'll save it to a variable so we can access it later.

The "loadImage" function loads the image and when finished runs the "displayImage" function.

The displayImage function checks the images array we created and loads the next image. It sets the smoothing to true on the Loader (by default, smoothing is set to false on dynamically loaded images). Once you start scaling or rotating an image it's important to set the smoothing so the image remains its quality. As the registration point of the Img movieclip is in the center we need to calculate the x and y position of where to place the image itself. In my example I've used a directory of images with the same width and height. If the width and height of the loaded image are variable this is the place to resize it on the fly. Just before adding it as a child we set the description text to "src", which holds the name of the image.

Step 9

After the changes we made to the Img class we need to update the way the instances are called in the loadImages function of the Gallery class. We now need to pass two arguments when calling new Img().

The first is the path name of the image that needs to be loaded, we get this from the xml. The second is a reference to the main Gallery class; we can use "this" which points to the class we're currently working in. Instead of adding the images with addChild to the imagesClip container we'll create a new function "goTo". This function will work out which images to place on the screen. The argument we need to pass is the id number of the image, the same number as the index key in the images array. When the images are loaded for the first time, we'll set the focus on the first image, of which the id number is zero.

Step 10

To use the goTo function we need to declare a variable "imagesToShow" first. This will set the amount of images we want to load at once on screen. To determine the direction in which the user is scrolling, we simply check if the image we're going to had a higher or lower id number than the last one.

The next "for loop" loops all images needed on screen. For example: if we set imagesToShow to 5, it will loop from -2 to 2. This means that if we pass the value of i to the Img class we can determine where on the screen it should be positioned (-2 being far left, 0 center and 2 the far right). Therefore, we can scale the images larger the more centrally they are positioned.

There's an additional check included so we don't activate non-existing images (it stops at the first and the last one). For each of the active images we'll run the "makeActive" function, which we'll create later on.

Right after placing the images we need on screen, we'll check which ones shouldn't be there any more and get those off the stage. Since all images are added to the imagesClip container, we can easily loop through all children of that movieclip. If their id is not within those that should be active, we run the "deActive".

The next line updates the text of the dynamic textfield we created earlier. Since the ids of the images start their count at 0 we add + 1 to the imgId so the first image is actually number 1 etc. We can get the total number of images from accessing the length of the images array.

Finally, we'll set "orgImgId" so the next time the function is run, the direction being scrolled can be determined.

Step 11

We now need the "makeActive" and "deActive" functions in the Img class. These will either add the image to the stage, or take it off. For now we'll just add them and place them correctly. Later on we'll also tween them to their correct place.

The makeActive function first checks if it is added to the imagesClip already. If there is no parent found, it adds itself to to imagesClip container. The parent is then the imagesClip. Next we set the visible property to true. When deactivating, we set it to false so it's only normal we want our image to show again when it's made active.

There's a chance that the image itself hasn't yet loaded. To check this, I check if the amount of children is smaller than 3. This number can depend on the amount of shapes or other movieclips in your Img. If you feel uncertain about this method, a safer option would be to declare a boolean at the start and set it to true in the displayImage function.

There's no depth in AS3, but once we start scaling and rotating our images we need to make sure the image in the center is on top of the others. Because we passed the position as an argument in the goTo function we can now use it to set the index of the image in the imagesClip. The index of a child can be compared to a depth, but there won't be any issues when changing it since the other movieclips will move an index up or down. This step is unnecessary if you don't plan to overlap the images.

Lastly, we determine the position of the image. The "extra" variable is used here to find out by how much the current image is away from the center. "DefaultWidth" and "spaceBetween" are public variables set in the main Gallery class so we can access them from anywhere. Since all the images in my directory have the same width, I set defaultWidth at 195 and spaceBetween to 20. To actually move the image to the new position we set the x property to the newly found x value.

Step 12

The deActive function is pretty straight forward, it changes the visibility to false. The direction is already set as an argument since we'll need it later to know in which direction to send the image when taking it off the stage.

Step 13

By now, the first few images should appear on stage. There's only one functionality still missing. The slider is not connected to the goTo function yet. However, since we already dispatch a custom event once the handle is dragged, it's not very hard to connect the two.

Add the following line to the Gallery constructor function. This eventlistener will run the slide function every time the "sliding" event is called by the handle.

All we need the slide function to do is to calculate which image should be shown in the center depending on where the handle is. In the function "slider" and "theHandle" are the instance names we set earlier on the movieclips on the stage. To find out which image to go to we first determine the percentage of the handle's position over the slider's length. Then, multiplying that by the total of images brings us to the right image id.

Step 14

If you've managed to follow this far and kept track of which classes to import and which variables to declare (or followed the source files) you should by now have a working example.

Step 15

To finish this tutorial we'll add tweening to the images using TweenLite, a free and lightweight tweening engine. The standard tweening classes provided by Adobe do not perform well when there's a lot going on. When trying those out they used to crash or freeze a lot, while I have yet to discover such problems with TweenLite. The syntax of TweenLite is very easy. I'll demonstrate this by comparing it to a normal Flash tween; tweening an object from its current x to 100 and changing the alpha to 0:

Now here's the TweenLite alternative syntax:

Step 16

Let's create a new function in which we can place all of the tweening actions. Name it "flyTo" and place it in the Img class.

There are 3 arguments needed for this function: the x value we calculated earlier, whether it should be removed after the tween and the scale. The "removedAfter" parameter will be used in the deActive function, so the visibility of the image can be set to false once it's reached the end of the stage. The scaling parameter is only used for the center image; we'll display it slightly larger than the rest.

Let's check out the tweening options for when the image is removed from the stage. First we choose an easing option, in this case "Linear.easeIn" which gives normal, linear movement. Secondly, we fade the alpha value to zero so the image fades away. Then we scale it to only a small percentage of its width and height so it becomes smaller as it reaches the end. Lastly, when the tween is completed, we set the visibility to false.

When an image is made active, the tweening options are different. We set the easing to "Back.easeOut" so the images seem to fly slightly too far and then bounce back; a very subtle effect. Next we change the alpha back to 1 and scale the image to the scale value we passed to the function. Lastly, we set a random rotation of -10 to 10 degrees. If your description text fails to load after this action you need to make sure the font is embedded.

Step 17

Now we need to update the makeActive and deActive functions so they make use of the new flyTo function.

In the makeActive function we need to add an x value to the image so it can be tweened from that original value. The defaultWidth needs to be set in the main Gallery class and contains the width of the stage.

In the deActive function all we need to add is a moveTo value which contains the x value to which the image should tween. If we locate this to outside the stage width, the image will disappear just outside the stage.

Step 18

After updating everything, we now have a functional gallery. To see the movieclips disappearing from the stage check out the full version.


The final version is still low on functionality. The loaded images all need to be the same size and do not have a larger preview. You could add a resizing function and an option to view a larger preview of the image when clicked. Furthermore, an option to browse left or right with buttons or with a keyboard event could be added.

Once you understand the concept of using classes to separate and structure your code it will help in development and make things easier in the long run. I hope you enjoyed following along!

Looking for something to help kick start your next project?

Envato Market has a range of items for sale to help get you started.