Sunteți pe pagina 1din 84

Making a Dynamic Image Gallery

Overview

Before starting to buid your image gallery, there is a little planning to be done, because this is in
fact a small application. Let's see the elements that make up this gallery:

I. The elements of the SWF movie

1. The gallery menu. This is the interface which will enable the user to browse through the
galleries. It will be made of buttons dynamically pulled out from the Library and then
nested inside an empty movie clip. The menu will have two buttons, which will make
possible for the user to scroll through the menu, up and down. A mask will be made
inside this menu, to limit its visible area. You must do this because if you are going to
have many galleries (let's say 40, 50 or even more), their respective buttons cannot be all
over your movie — that would look bad.
2. The thumbnail MovieClip. This is a movieclip symbol stored inside the Library, into
which a single thumbnail (small image) will be loaded. It contains:
o a white background, just to make it nicer, and to be able to add a drop shadow
effect to it later,
o an empty MovieClip inside which the external JPEG thumbnail will be loaded
and
o a dynamic text field which will serve to show the preloader (a simple percentage
preloader).
3. The big image holder MovieClip. This MovieClip symbol will also be stored in the
Library and will be pulled out of it dynamically, via ActionScript. It is nearly the same as
the thumbnail MovieClip, except bigger in size. It contains the same three elements as the
one above:
o a white background,
o an empty MovieClip inside which the big external JPEG image will be loaded
and
o a dynamic text field for the preloader.
4. A placeholder for thumbnails and big images. This is an empty MovieClip, placed
directly on the stage, which will have two empty MovieClips created inside it at runtime
(meaning while your SWF is running), like this:
o When the user clicks on a gallery in the menu, an empty MovieClip will be
created inside the placeholder. This MovieClip is going to receive several copies
of the thumbnail MovieClip attached to it, depending on the number of images
in the gallery that the user has selected.
o When the user clicks on a thumbnail, a new empty MovieClip will be created
inside the placeholder, which will have the big image holder MovieClip attached
to it. The preloading of the big JPEG image will start, and when it reaches 100%,
the image will fade in nicely and hide the thumbnails. When the user click on the
image, it will disappear and the thumbnails will appear again.
5. A dynamic text field. This is where the descriptions for all the galleries and images will
appear.
6. Your website logo. This is just a graphic element, which will appear above the gallery.

II. The XML file

The XML file will store all the data related to the images:

 The name of each gallery. This name will appear as the label on each gallery button in
the menu. Also, this same name is the name of the folder (directory, file folder, as it is
also called) inside which that particular gallery will be stored on your web server.
 The description of each gallery. This is the text that will appear in the dynamic text
field when the user clicks on a gallery button and the thumbnails for it are shown.
 The description of each image. This is the text that will show up in the same dynamic
field mentioned above when a big image has been loaded.

III. The images and the thumbnails

All the images will have to be stored according to an exact hierarchy and precise naming
rules. Each gallery will be placed in a folder which will have the same name as the title of the
gallery as it appears in the XML file. Inside each folder, the images will have to be named as
1.jpg, 2.jpg, 3.jpg and so on. Furthermore, each gallery folder will have a subfolder inside it,
called thumbs, where the thumbnails for the gallery will be stored. The thumbnails will have the
same file names as their bigger counterparts (1.jpg, 2.jpg, etc). All the galleries will be placed in
a single folder, named gallery.

You have to abide by this naming/folder hierarchy system if you want your dynamic image
gallery to function properly. Once you want to insert new images inside the gallery, the only
thing you will have to do is to update the XML file, create new folders according to the gallery
names inside this XML file, and place the images and their respective thumbs inside them. You
will then upload the new images and the XML file to your web server and they will
automatically appear inside the menu.

Sounds great — a fully automated image gallery system. I will start by showing you how to
create the SWF movie, after that you will download the XML file and modify it according to
your needs, make all the necessary folders and place the images and thumbnails inside them, and
last but not least (in fact, the most important) you will create the ActionScript code that runs the
whole thing. Let's get started!

1. Setting up your document

1.1. Open a new Flash document (File > New > Flash Document).

1.2. Select Modify > Document. Set the dimensions of your Flash movie to 760 by 540 pixels
and set the speed (frame rate) to 30 fps. Click OK.
1.3. Save your document in a separate folder — make a new folder just for this lesson. A lot
of files are going to be needed for the creation of the image gallery, so it is a wise thing to keep
them all in one place, instead of putting them together with any other Flash files that you may be
working on.

NOTE Just a little bit about the dimensions of your document here: The document's size (width
and height) is just a suggestion, like all of the dimensions and element positioning (menu, main
images, thumbnails, etc) involved in this lesson. I recommend that you use my dimensions until
the end of the tutorial, so that you can more easily follow my instructions. Later, once that you
grasp the way the gallery works, you can change the dimensions and the general layout of the
gallery to suit your needs.

2. Creating the gallery menu

2.1. Call the first layer in your document gallery menu.

2.2. Select Insert > New Symbol. In the window that appears, do the following:

 Select Movie clip as type,


 enter empty movie clip as the name of the new symbol
 click OK.

2.3. You will now find yourself working inside the new MovieClip symbol. Since you need an
empty MovieClip, don't draw anything here, just click the Scene 1 link above the timeline.
Your newly made empty movie clip symbol is now stored inside the Library. You can access the
Library by selecting Window > Library. Keep the Library window open, because you are going
to need it frequently, especially to place instances of the empty movie clip symbol on the stage at
various points during this lesson.

Now you are going to create the main MovieClip for the image gallery menu. The first thing that
you're going to make is a mask for the menu buttons.

2.4. Select the Rectangle tool (R). In the Colors section of the Tools panel, block the stroke
color, because you won't need it. Do this by selecting the stroke color first — click on the little
pencil icon to do it (see 1 in the image below). Next, click on the No color button (see 2 in the
image below). You can choose any fill color that you like.

Also, turn off the Object Drawing and Snap to Objects options (both icons are shown below —
you can find them at the bottom of the Tools panel while the Rectangle tool is still selected).

2.5. Click and start dragging your mouse to draw a rectangle. Make it any size you want.
2.6. Select the rectangle by clicking on it with the Selection tool (V). Go to the left side of the
Property inspector and find the width and height options (W and H, respectively) for the shape.
Enter 200 pixels for the width and 390 pixels for height.

2.7. While the rectangle is still selected, select Modify > Convert to Symbol. Make the
following choices:

 Select Movie clip as type of symbol.


 Name the symbol menu holder.
 Select the upper left registration point for the new symbol (see image below).
 Click OK.

This last point is very important. You will do the same thing for every single symbol that you are
going to create in this lesson. This is done in order to facilitate the positioning and resizing of
elements on the stage via ActionScript (dynamically) later.

If you had made some other choice for the registration point, you would have had to know and
use the width and height for each symbol to be able to position them properly. By selecting the
upper left corner for the registration point, the positioning is pretty straightforward and there is
no fuss at all.

2.8. Double-click on the newly made menu holder MovieClip on the stage (using the Selection
tool) to enter inside it. If you take a look above the stage, you'll see that Flash nicely informs you
that you are working inside the menu holder MovieClip now.

2.9. The rectangle vector shape inside the movie clip should be selected by default. If this isn't
the case, click on it with the Selection tool (V) to select it.
2.10. Select Modify > Convert to Symbol. Once again, select Movie clip as type, choose the
upper left corner for the registration point, call it menu mask and click OK.

2.11. The new MovieClip will be selected by default immediately after you have clicked the OK
button in the previous step. Now go to the Property inspector and give an Instance name to this
MovieClip: call it galleryMask_mc.

2.12. Lock the current layer and call it mask. Create a new layer and call it placeholder.
Remember that all of this is done inside the menu holder movie clip — you are still inside it.

2.13. Go to the Library (Window > Library), click and drag an instance of the empty movie
clip symbol onto the stage, inside the placeholder layer that you created a moment ago.

This movie clip has no graphical content, and so it is represented by its registration point only.
This is the small circle with the cross inside it that showed up once you dragged the movie clip
from the Library onto the stage. If ever in doubt which movie clip you are tinkering with, just
look at the Property inspector while it is selected. You can see this in the screenshot below.

2.14. With the instance of the empty movie clip on the stage still selected, open the Align panel
by selecting Window > Align. Do this:

 Turn on the Align/Distribute to Stage button (see 1 below).


 Click the Align left edge button (see 2 below).
 Click the Align upper edge button (see 3 below).
The empty movie clip will now be perfectly aligned with the menu holder movie clip's
registration point, as you can see.

This is just what you need, since this empty movie clip which you have just positioned will be
the placeholder for all the menu buttons. That being said, you must prepare it properly to be able
to load the buttons inside it later. Follow the next step to see how :-).

2.15. The empty movie clip must still be selected. Go to the Property inspector and enter the
Instance name for this movie clip: call it buttonsHolder_mc.

2.16. Lock the placeholder layer and drag it under the mask layer.

2.17. Right-click on the mask layer and select the Mask option from the menu that pops up (also
called the contextual menu). The mask layer will instantly turn into a mask, masking the
placeholder layer beneath it.

2.18. Click on the Scene 1 link above the layers to go back to the main timeline.

2.19. The menu holder movie clip will be selected by default, which you can see in the Property
inspector. Go right there and give at an Instance name: call it galleryMenu_mc.
You have probably noticed that this movie clip is almost invisible — it is represented by its
registration point (see1 in the screenshot below) and central point (see 2) only. This is because
the mask inside it isn't visible, which is normal.

Fine — the menu is pretty much ready now, it can receive the buttons. But you have to actually
make a button that is going to be pulled out of the Library at runtime (while the Flash SWF
movie is running, that is) and placed inside the menu, as many times as there will be sections
inside your gallery.

3. Creating the menu button and setting it up for use at runtime

3.1. You should be on the main timeline now. Lock the gallery menu layer and create a new
layer. You don't have to gave any specific name to this new layer at all, because it will serve as a
temporary layer only, to create the menu button specimen, after which you will remove it.

3.2. Select the Rectangle tool (R). The settings for this tool should have remained unchanged
from the previous use of it: the stroke color (outline) should be blocked, the Object Drawing and
Snap to Object options turned off.

You can select any color you like for the fill. I chose a nice hue of blue, #00789F. Now draw a
200 by 20 pixel rectangle anywhere on the stage. You can draw any rectangle at first and then
set these exact dimensions in the Property inspector after.
These exact dimensions are important, especially the width, because the mask that you made in
the previous section is also 200 pixels wide. They have to match (or the mask can eventually be a
little wider than the button) if you want your menu to look professionally designed — clean and
sharp.

3.3. Select the rectangle and choose Modify > Convert to Symbol. Select Movie clip as type,
call it gallery section button and click OK.

A small note here: the movie clip that you just made is called gallery section button, although it
is a movie clip. Don't let that confuse you. I chose to give it such a name because it will in fact
serve as a button. Why a movie clip then? Because a movie clip symbol is far more versatile and
usable than a button — its possibilities of creation and manipulation are far greater than those of
a button symbol. And even if in this particular project a button symbol would maybe serve as
well as a movie clip for all purposes, I have just acquired a habit of making movie clips instead
of buttons :-).

3.4. Choose the Selection tool (V) and double-click on the gallery section button movie clip on
the stage, to enter inside it.

3.5. Call the movie clip's first layer bkg (because this will be the button's background).

3.6. Right-click on frame 2 in this layer and select Insert Keyframe from the contextual menu.

3.7. In the newly made keyframe, the rectangle will automatically be selected. Just change its
color to some other of your choice — I used #7C3F52. Do this by clicking on the fill color
square in the Colors section of the Tools panel, all the while the rectangle is selected.
Why was this done? Because you need to have a rollover effect for your menu to make it more
user-friendly and easier to navigate. So that's why you have to have two keyframes, with the
same rectangle inside, but differently colored. You will enable this rollover visual change via
ActionScript later.

3.8. Lock the bkg layer and make a new layer above it and call it label.

This new layer will automatically have the same timeline duration as the one below it (2 frames
long), which is fine, because the label (the text that will appear on the button) must be visible in
both states — the initial one as well as the rollover.

3.9. Select the Text tool (T). In the Property inspector, do the following choices and tweaks:

1. Select Dynamic Text.


2. Select a font that you like.
3. Select 14 as font size, or bigger if necessary. The important thing is that the text field's
height should approximately match the height of the rectangular background. You'll see
that once you make the actual text field, so you may need to re-adjust this value as
necessary.
4. Select white for the text color — this choice will make the button labels visible in both
states — initial and rollover.
5. Select the left alignment for the text field. It looks well, unlike the central alignment
which would look awkward on this kind of menu and would also make things more
difficult to read.
6. Select Anti-alias for readability in the rendering menu.
7. Make sure that the Selectable option stays turned off. If you turn it on, your menu
buttons will suck royally and possibly won't be clickable at all.
8. Make sure that Single line is selected. Multiline doesn't make any sense for a text field
inside a menu button, right?
3.10. Click and drag on the stage with the Text tool to create a dynamic text field. Create it over
the button's backround rectangle, so that the dimensions of the two approximately match. Hit Esc
when finished and you'll exit the text field and see a blue border appear around it.

3.11. Now go over to the Property inspector and type in the Instance name for your dynamic
text field: call it sectionTitle_txt.

3.12. On the right side of the same panel, click the Embed button.

The Character Embedding window will open up. Select multiple character groups by Shift-
clicking them: choose the Uppercase, Lowercase, Numerals and Punctuation options. Click
OK.

Embedding the characters in the dynamic text field will ensure the continuity of design accross
different platforms and operating systems. No matter if a user has your menu font of choice
installed or not, he/she will see the exact same font, thanks to the embed option.

The four groups of characters that you have embedded in your dynamic text field will cover 99%
percent of possible gallery names. Of course, you may choose to add any additional special and
exotic characters if you wish so. Bear in mind that the embedding of these characters will add
about 20-30 KB to your final SWF file.
3.13. Lock the label layer. Make a new layer and call it actions. You can lock this layer also,
since ActionScript code can be placed inside it while it is locked too.

Click on the actions layer's first frame to select it.

3.14. Open up the Actions panel by selecting Window > Actions. Enter the following code
inside it:

stop();

This simple action prevents the playhead from going forward, as any animation in Flash
naturally does. You will create programming code later that will move the playhead to the next
frame while the user is over a particular button with his/her mouse, to create the rollover effect I
told you about just a few steps before.

3.15. Fine! The button is finished now! Click on the Scene 1 link to go back to the main scene.

3.16. Delete the temporary layer inside which the button was created (Layer 2). This will delete
the button from the stage too. You should have only the gallery menu layer on the main scene
now. However, the gallery section button is stored inside the Library.

3.17. Go to the Library (Window > Library). Right-click on the gallery section button movie
clip inside the Library and select the Linkage option from the contextual menu.
3.18. In the Linkage Properties window that appears, check the Export for ActionScript
option. The Export in first frame option will automatically become checked too. You can leave
it like that, it's fine.

As for the Identifier option, you can also leave it at the default value, which is the name of the
movie clip symbol itself — gallery section button in this case. Click OK.

The Identifier name will serve to pull the button dynamically from the Library and place it inside
the menu that you have created on the previous page. This is very, very practical, because you
will change just the images and the XML file once the SWF is finished.

This makes possible for dynamic menu creation, also thanks to the dynamic text field inside the
button — each button will have its label match the section of the gallery it represents. Why
create every single button manually, re-open the FLA, re-export it as a SWF when you can solve
this with ActionScript and have the menu created in a split second!

You will now make the remaining elements, so that your photo galleries menu is complete.
Namely, you will make two buttons for scrolling through the menu and a title that tells the users
what's the menu about. Before that, you'll just position the galleryMenu_mc movie clip.

4. Making the menu navigation buttons


4.1. You have to select the galleryMenu_mc movie clip to be able to position it. Since this movie
clip is almost invisible, it isn't as easily selectable as any othe movie clip might be. Here's how
you do it (follow the pictures below the list):

1. Unlock the gallery menu layer.


2. Click on the layer's first frame to select it.
3. The Property inspector tells you that a frame has been selected.
4. Once you select a frame, all the content inside it is selected too. Because of this, the
movie clip you are looking for will appear. Click on the movie clip once with the
Selection tool (V) to select it (you must click on its registration point since no other
content of this symbol is visible).
5. The movie clip is selected, which is indicated in the Property inspector.

4.2. Enter the following values for the movie clip's coordinates (inside the Property inspector):
10 for X and 99 for Y.

Fine. Let me show you now how to create a couple of sleek navigational buttons.

4.3. First, make a line that will separate the menu buttons from the menu navigation. Select the
Line tool (N). In the Property inspector, select black for the line color and hairline for the line
thickness.

4.4. Hold down Shift on your keyboard, click with your mouse somewhere above the
galleryMenu_mc movie clip and draw a horizontal line. Holding Shift will enable you to make a
perfect horizontal line. You can select the line later and position it via the Property inspector.
Also, make it as wide as the menu, to have a more coherent and professional design.
4.5. Select the Rectangle tool (R). Go to the Options part of the Tools panel and make sure that
both the Object Drawing and Snap to Objects options are turned off (see 1 and 2 on the
screenshot below).

Next, click on the Set Corner Radius button (see 3 above). In the Rectangle settings window
that will show up, enter 7 as the corner radius value, then click OK. This will enable you to draw
rectangles with smooth, rounded corners.

4.6. Go over to the Color Mixer panel (to access it, select Window > Color Mixer, although it is
probably open already, by default). Block the stroke color and make a nice bluish-turquoise
linear gradient for the fill color, like this:

1. Click the small pencil icon.


2. Click the little square next to it and select the No Color option (the white square with the
red diagonal line).
3. Click the paint bucket icon to select the fill color.
4. Select the Linear option in the Type menu.
5. Click on the left color (the small square) in the gradient stripe to select it.
6. Enter the hexadecimal code for this color: I chose #00789F.
7. Repeat the two previous steps for the right-side color: select it and enter #81E6FE as its
code.
4.7. Hold Shift (to draw a square and not a rectangle), click on the stage and draw a 29 by 29
pixel square.

This square looks nice, but since it is a navigational element, I think that it would look much
better if the gradient spreads from top to bottom instead from left to right. Follow the next step to
see how to do this simple modification.

4.8. Select the Gradient Transform Tool (F). Turn on the Snap to Objects option in the Tools
panel. Now, rotate the graident like this:

1. Click on the square that you drew in the previous step to select it. The controls for
gradient modification will appear.
2. Click the circle with the small black arrow in it and start dragging your mouse counter-
clockwise.
3. Once you reach a 90-degree turn, release your mouse button. There!

4.9. Select the Selection tool (V) and turn off the Snap to Objects option. Click on the gradient-
filled square to select it.

4.10. Select Modify > Convert to Symbol to make a symbol out of this square. This time, select
Button as type (not Movie clip), call it scroll menu down and click OK.

4.11. Double-click on the newly made scroll menu down button on the stage to enter inside it.
Once inside the button's timeline, lock the first layer and call it bkg. Make a new layer above it
and call it arrow.
4.12. Draw a white arrow that is pointing downwards, inside the arrow layer.

You can do it easily like this (see the sequence of images below):

1. Using the Rectangle tool (R), draw a square (I made a 19 by 19 pixel square).
2. Choose the Selection tool (V) and bring your cursor near the square's upper right
corner. A small right angle will appear near your cursor.
3. Click and drag your mouse toward the square's center. Once your cursor is near the
center, a circle will appear, indicating that it is ready to snap into place.
4. Release your mouse button and you've got yourself a nice triangle.
5. Select the Free Transform Tool (Q) and rotate the triangle by 45 degrees counter-
clockwise. There! You have the arrow for your button now.

Note that I have used the blue color just to show you how it's done. You can use any color you
want while making the triangle — once you move it over the button's background, change its
color to white.

4.13. Add a third layer inside the button and call it label.

4.14. Select the Text tool (T) and change the type of text field to Static Text in the Property
inspector. Click somewhere over the button's background area and type DOWN.
As you can see above, I chose a pixel font for the label (it looks cool). If you do the same, be
sure to set the rendering option to Bitmap text, which is the best for pixel and bitmap fonts.
Also, most pixel fonts have to be typed with a font size of 8, to render properly and sharply.

4.15. Click the Scene 1 link to go back to the main scene, because the button is complete now.

4.16. Assign an Instance name to this button because you'll need to manipulate it via
Actioncript later. Name it menuDown_btn.

Place this button above the thin line, on the right.

Now you need to make the second button, for scrolling the menu upwards. This one is going to
be easy to do, because you'll just clone the existing button and make a few modifications.

4.17. Go to the Library. Find the scroll menu down button symbol, right-click on it and select
Duplicate from the contextual menu.

In the Duplicate Symbol dialog that appears, enter scroll menu up as the new symbol's name,
leave the other options as they are and click OK.

4.18. Double-click on the newly made scroll menu up button symbol inside the Library to acces
its timeline. Once inside, unlock the arrow layer.
4.19. Select the triangular arrow shape in this layer. Now select Modify > Transform > Flip
Vertical. The arrow will now point upwards, thanks to the flipping you did. Also, Change the
static text from DOWN to UP. Remember, these changes will not affect the first button you
made, because the duplicated scroll menu up button is an independent symbol, not linked to any
other one in any way.

4.20. Click on the Scene 1 link above the timeline to exit the button's timeline and to return to
the main one.

4.21. Click on the scroll menu up button inside the Library once, hold your mouse button and
drag out an instance of it out onto the scene. Place it next to the scroll menu down button, like
shown below.

4.22. Select the "UP" button and assign it an Instance name: call it menuUp_btn.

4.23. Add some text near the buttons, so that the users actually know what's the menu about —
don't leave anyone guessing. Do this with the Text tool (T) set to Static text.

TIP Always think about the user who is the least web-savvy. Creating a user-friendly site with
the lowest common denominator in mind will enable you to have a much bigger public and also,
the users will want to return to your site because they found it easy to use.

4.24. Lock the gallery menu layer.

5. Creating the image placeholders


5.1. Create a new layer and call it images holder.

5.2. Drag out an instance of the empty movie clip symbol from the Library into this new layer. As
this movie clip is completely devoid of any graphical content, it is shown as a registration point
only.

Assign an Instance name for this important movie clip into which all images will be loaded:
name it imagesHolder_mc. Position it like this: set its X to 260 and Y to 100.

This will place the imagesHolder_mc movie clip close to the menu, on its right, like shown
below.

When the overal dimensions of the movie are taken, this is a good position. I had a general idea
about the gallery's layout, but I arrived at this final dimensions and positions through the creation
process itself. As I said, you can change these dimensions to suit you as you please later, just
stick with them now, until you complete this lesson. The same goes for the placement of the
elements: the menu doesn't necessarily have to be on the left, vertically positioned, etc. I just
made these choices for this tutorial.

5.3. Make a third layer. You will create two movie clips here that will be present inside the
Library only (for dynamic use, like the menu section button that you have made earlier). After
they are complete, you will erase them from the stage and assign them identifiers in the Library
to be able to use them via ActionScript later.
5.4. Select the Rectangle tool (R), use white for the fill color and black for the stroke color.
Select hairline for the line type. Make sure that Stroke hinting is turned on.

5.5. Draw a 88x61 pixel rectangle on the stage. This will be the background for gallery
thumbnails that will be loaded later.

Again, I chose these dimensions because they suit me for this tutorial. You may chose other
dimensions. What is important is that you should create thumbnails with appropriate
dimensions in Photoshop (or Fireworks) later. To obtain a nice appearance for your thumbnails,
I suggest that you make them a little bit smaller than the rectangular backgound that you have
just created. The white background being 88x61 pixels, I decided to make my thumbnails 81x54
pixels.

5.6. Select the rectangle that you just drew (both the outline and the fill). Then select Modify >
Convert to Symbol (shortcut key: F8). Select Movie clip as type (be careful not to choose the
Button type, as it may have stayed from before), call it thumbnail holder and click OK.

5.7. Double-click on the newly made movie clip to enter it. Lock the first layer and call it bkg.
Make a new layer and call it image holder.

5.8. Click and drag out and instance of the empty movie clip from the Library and into the
image holder layer. In the Property inspector, give it the Instance name thumbImage_mc and
position it so that both its X and Y coordinates are 4. You can see the movie clip below (its
registration point), over the rectangle's upper left corner.
5.9. Lock the image holder layer and make a new layer above it and name it text.

This is the layer where you'll be placing a dynamic text field, so that a numerical (percentage)
preloader can be displayed while the thumbnail is loading. Making a preloader for thumbnails is
a nice thing: you give your users all the information about loading, even for such small images.
This also covers the slow-speed modem users, by telling them how much they must wait before
everything is loaded.

5.10. Select the Text tool (T). Set its properties like this:

1. Use Dynamic Text, which is understandable, since this text field will show the
preloading process via some ActionScript code.
2. Select the same font type that you did before, to have a coherent design for your gallery.
3. Select an appropriate font size — I chose 14 for the button labels before so I did the same
here.
4. Select black as the color, to be highly visible against the thumbnail holder's white
background.
5. Select left text alignment.
6. Choose Anti-alias for readability.
7. Like in most cases in this tutorial, make sure that the Selectable option stays turned off.
8. The Single line option should be used for this text field.
5.11. Click and drag your mouse to make a text field. Press Esc on your keyboard to exit the
text field edit mode. Go to the Property inspector and give your text field an Instance name: call
it percent_txt. Position it in the middle of your thumbnail holder movie clip.

Now, click the Embed button (it's on the right side of the Property inspector when the text field
is selected). Do the following:

1. Select the Numeral option (you need all the numbers, since this is a percentage
preloader). See 1 in the scrrenshot below.
2. Click inside the input field below the Include these characters text and type the
percentage sign (%) inside it (see 2 in the screenshot below).
3. Click OK.

Having the characters of the specific font you selected embedded inside your text field assures
the coherence of your design and makes sure that all users will see the same thing.

5.12. Lock the text layer and click on the Scene 1 link to return to the main scene.
5.13. Erase the thumbnail holder movie clip from the scene.

5.14. Go over to the Library and find the thumbnail holder movie clip inside it. Right-click on
it and select the Linkage option. Check the Export for ActionScript option (this is what
enables you to pull out the movie clip from the Library dynamically). The Export in first frame
option will automatically become checked. Leave the Identifier as it is: thumbnail holder. Click
OK.

There! Your thumbnail holder movie clip symbol is now ready to be used by ActionScript.
Specifically, you will use the attachMovie() method in your code later to pull this symbol from
the Library and place it on the stage.

Now that the thumbnail holder is complete, you will create a similar but slightly different holder
for the images — the big ones that will be loaded as a user clicks on a thumbnail. You will
follow the same procedure as you did for the thumbnail holder movie clip.

5.15. Select the Rectangle tool (R). Draw a 475x317 pixel rectangle using the same options that
you did in step 5.4.
5.16. Select the rectangle (both its fill and outline) and press F8 (or select Modify > Convert to
Symbol) to convert it into a symbol. Select Movie clip as type, call it big image holder and click
OK.

5.17. Double-click on the big image holder movie clip on the stage to enter inside it. Call the
first layer bkg and lock it. Make a new layer above it and call it image holder.

5.18. Click and drag out an instance of the empty movie clip symbol out of the Library and into
the new layer (image holder) that you made in the previous step. Make the following
adjustements:

1. Give the movie clip an Instance name: call it imageHolder_mc.


2. Make both the X and Y coordinates of the movie clip equal 4.

The empty movie clip is represented by its registration point, since it contains no graphics at all
(which is normal, because it will be used to load external JPEG images). I have marked it with a
red arrow in the screenshot below so that you can more easily see it.
This movie clip is placed near the background rectangle's upper left corner. This is a fine
position for the JPEG image that will be loaded — its upper left corner will cooincide with the
registration point of empty movie clip. You could reposition it later with ActionScript if you
want, but I think there is no need to do that. This position is just fine.

5.19. Lock the image holder layer and make a new one and call it text. You will place a
dynamic text field for the preloader here, just like you did for the thumbnail holder.

5.20. Select the Text tool (T) and choose the same options as you did with it in step 5.10.,
change only the font size — increase it more than twice. I chose 30.

5.21. Click and drag to create a text field. Place it over the middle of the big rectangle. It should
be large enough for three numbers and the percentage sign to show inside it. Press Esc to exit the
text field. The Instance name for this text field can be the same as it was for the thumbnail
holder (percent_txt), since these are two different movie clips and there will be no conflicts.
You need to embed the appropriate characters in this text field too:

1. Click the Embed button in Property inspector.


2. Select the Numerals option and insert the % character where appropriate, just like you
did in step 5.11.
3. Click OK.

5.22. Lock the text layer and click on the Scene 1 link inside this movie clip to exit it. Once on
the main stage, erase this movie clip from it.

5.23. Find the big image holder movie clip inside the Library and right-click on it, then select
Linkage from the context menu. Click the Export for ActionScript option to check it, leave the
Identifier as big image holder and click OK.

6. Creating a text field for gallery and image descriptions

6.1. You should be on the main scene (timeline) now. Call the current layer (the one which you
used to create the image placeholders) description text.
6.2. Select the Text tool (T). This time, you will select different options than you did for the
percentage preloaders inside the image placeholders. Select:

1. Dynamic text, of course.


2. Choose a font that is readable. Avoid exotic fonts.
3. Choose a size that is suitable for reading. Font sizes 11 or 12 work just fine.
4. I suggest that you select black for the color of your text, to have a good contrast with the
white background and make the text easy to read.
5. Select left alignment. You may also select the Justify option. Avoid right or central
alignment - this is never used in a "normal" text — that is, text that isn't a title or a link,
but a standard paragraph.
6. Select Anti-alias for readability (you will have to embed the characters because of this
later).
7. You can either turn on or off the Selectable option — this is entirely up to you, whether
you'll enable your users to select the description text or not.
8. Make sure to choose the Multiline option, as your descriptions may be several lines long,
you never know, right? Better to make sure :-).

6.3. Click on the stage and drag your mouse to create a text field. Hit Esc to exit the text field
editing mode. Your text field's dimensions should be about 475x100 pixels. Also, pay attention
to its position: try to align it with the image placeholder and think about how much space will
take an image once it's loaded. In the screenshot below you can see the position and dimensions
of the text field.

6.4. Assign an Instance name to the text field to be able to manipulate it later via ActionScript:
call it desc_txt.
6.5. Click the Embed button while the text field is selected to include the necessary characters in
it and have nice, readable descriptions which are going to be nicely rendered: select the Basic
Latin category and click OK.

The last (yes, the last one, indeed :) thing that you need to create in this document is your logo.
After that, the things that remain to be done are the external XML file, the folders with their
respective photos and thumbnails and lastly, the magnificent ActionScript code that will make
possible for the whole thing to work.

Top of page

7. Making the logo

7.1. Lock the description text layer and make a new layer and call it logo.

7.2. Now, this is just a suggestion fo the logo. You can make any kind of logo/header that you
like, but I recommend that you follow my proposals here, just to be able to follow this tutorial
more easily.

Select the Rectangle tool (R) and draw a 700 by 40 pixels rectangle. Place it above the gallery
menu. I have also drawn a thin white line through the lower part of the rectangle and changed the
fill color of the lower part.
7.3. Select the Text tool (T) and switch the type of the text field to Static text. Click and type
anything you want over the rectangle.

7.4. Select the whole logo — both the rectangle and the text — and then choose Modify >
Convert to Symbol (shortcut key: F8). Select Movie clip as type, call it logo and click OK.

NOTE I didn't make separate layers for the background rectangle and the text inside the logo
movie clip, but just selected the whole thing and made a movie clip symbol out of it. It is usually
recommended to make separate layers for different elements inside a symbol, but logos aren't
supposed to change much, so I guess a single layer should pose no problems at all. Of course, if
you are going to animate an element inside your logo or are planning to make changes later, you
should place each element on its own layer.

7.5. While the newly made logo movie clip symbol is selected on the stage, go over to the
Property inspector and assign it an Instance name: call it logo_mc. Also, you can set both of its
coordinates to 10.
You could have left the logo as it is without having to convert it into a movie clip symbol. But
having a movie clip enables you to position it via ActionScript later if needed — you won't need
to do that manually, which is much more practical.

7.6. Lock the logo layer and make a new layer and call it actions.

You won't be entering any ActionScript code here right now. First you have to have an XML file
where all the gallery data will be stored, some images and an exact folder hierarchy. So let me
show you how to do all that before the coding part comes up. Before that, save your document!

Top of page

8. Creating the XML file with image galleries data

8.1. First, download the XML file that I created for this tutorial.

Before I tell you how this XML file will relate to your image galleries, the folders they are in,
etc, I just want to say that I won't explain the principles of XML and its interaction with Flash
here, because I already made a detailed explanation of XML in my Hangman game tutorial, and
there is no sense repeating it if it's already written, right? :-)

If you're not familiar with XML, I heartily recommend that you go and read the rules of XML
and how Flash loads and parses XML data, before proceeding.

So, the XML file that you have just downloaded looks something like this (I haven't displayed
the whole file here for the sake of brevity and screen real estate):

<?xml version="1.0"?>
<galleries>
<gallery title="architecture" intro="These are the photos of various buildings in the cities, towns
and villages I visited during my voyages.">
<image>Dallas.</image>
<image>Tresnjevka. I love the atmosphere on this one.</image>
<image>Motovun.</image>
<image>New York.</image>
<image>Paris.</image>
</gallery>
<gallery title="essays" intro="A collection of various photos which either do not fit any other
category - experiments and such.">
<image>Color mayhem!</image>
<image>The sleeping monster.</image>
<image>Let me out!</image>
<image>A barrel on the side of the trail.</image>
<image>Subterranean passage.</image>
<image>A train in snow.</image>
</gallery>
</galleries>

After the XML declaration comes the root node, of course. I chose to call it galleries. Within
this, root node, every other bit of data is contained.

<galleries>
...
</galleries>

Every child node of the root node is called gallery. I chose to give each of these child nodes
the same name (gallery) on purpose. You will see later why (when I'll explain the
ActionScript code) — this is related to parsing the XML data.

<gallery title="architecture" intro="These are the photos of various buildings in the cities, towns
and villages I visited during my voyages.">
...
</gallery>

Each gallery node has two attributes inside it: title and intro. I chose these names because
I think they are logical: the first one refers to the title of each gallery and the second one tells the
user what's the gallery about. Remember, you may call your attributes any way you like, as long
as you stick to the rules of XML.

The title attribute is very important: its value (between the quotation marks:
title="architecture") has a special functionality:

 It will appear on this particular gallery's button in the gallery menu — it will become a
button label.
 This value is also the name of the folder inside which the images belonging to this
particular gallery will be stored.
So, as you'll see a little bit later, the values of these attributes will have to be followed strictly,
because the application will be made as a case-sensitive one. This means that the name of a
folder must be exactly the same as the value of the title attribute for a particular gallery. If, as in
the above example, the value of the title attribute for a gallery is essays, the name of the folder
must be essays too. It cannot be Essays or ESSAYS.

The value of the attribute intro will be displayed inside the big dynamic text field below the
thumbnails when the user clicks on any of the gallery buttons inside the menu. Once he chooses
a gallery, the thumbnails will be loaded and displayed and the description text will be shown
beneath them.

<gallery title="architecture" intro="These are the photos of various buildings in the cities,
towns and villages I visited during my voyages.">

So, the intro text can be anything you want. And it has no relation with the naming of the folders
and galleries. It just describes a particular gallery.

Now, each gallery node has many child nodes, each of which is called image. Again, I chose to
give them all the same name on purpose, because this will enable Flash to parse the XML data
much more efficiently, and will save you a lot of trouble.

<image>A barrel on the side of the trail.</image>

Between the opening and closing tags of each image node, there is a child node, which is in fact
the description of the image. This description will appear in the big text field when the user
clicks on a thumbnail and the big image starts to load.

IMPORTANT You may have as many galleries as you like, as long as each one is referenced in
the XML file, and the corresponding folder exists. This is possible because in this tutorial you
will see how to create a menu that can contain a basically limitless number of buttons (each
button corresponds to a gallery).

9. Creating the folder structure for the image gallery

9.1. As the first thing, you should have a separate folder (directory) inside which all the files that
make up your gallery will be stored (SWF, HTML, XML, images). For the sake of simplicity, I
chose to call this folder root.

As you can see in the screenshot below, both the SWF file (the one you are learning to create in
this lesson) and the HTML page inside which it will be embedded should be placed inside this
main (root) folder.
9.2. Also, create a new folder inside the root folder and call it gallery.

I chose to call the page mypage.html and the SWF file imagegallery.swf. You can call them as
you like. It is the gallery folder that must have that exact name, because you will be using it in
ActionScript later.

Of course, you can choose other file/folder placements, but I strongly recommend that you
follow the one explained here, not only because you need it to complete this lesson, but also
because I think that this folder hierarchy and structure is really one of the simplest and most
easiest to use. Thanks to it, you will be able to modify or update your image gallery in a snap!

9.3. The XML file that you have downloaded earlier must be placed inside the gallery folder.
This file should be named gallery.xml.

Also, the gallery folder will contain all the sub-galleries: different sections of your image
gallery, which will correspond to the menu buttons.

What's very important, I repeat it again, is that these subfolders must have the same names as
they are defined inside the XML file. Otherwise, Flash won't be able to find the folders if there
are differences between them. They must match perfectly, including uppercase and lowercase
letters.

TIP Using only lowercase letters for folder names will prevent a lot of possible mistakes. I
recommend that you use them only, because you can change them into uppercase letters once
these names are loaded in Flash, which you will do later in this lesson.

9.4. Each gallery subfolder (like architecture, essays, etc in the above example) will contain the
big images, the ones that are loaded and show up once a user clicks on a thumbnail.
These images should be named 1.jpg, 2.jpg, 3.jpg... In short, each image name is a number.

The numbers must follow the natural order, i.e. if you happen to dislike an image and want to
remove it from the gallery, you should rename the other ones so that the order remains unbroken.
For example, look at the screenshot above. If you want to remove the image 3.jpg, you should
rename 4.jpg to 3.jpg and 5.jpg to 4.jpg. This is important because of two things:

1. Flash will load the exact number of images as there are inside the XML file.
2. The images will be looked for and once found, loaded in a sequential order — the
thumbnails, and after that, the corresponding big image, for each thumbnail.

9.5. Here is what you should do to have the thumbnails load and display properly for each
gallery:

1. The thumbnails for each image gallery section must be placed in a folder called thumbs.
Each gallery section must have such a folder inside itself.
2. The number of thumbnail images must match the number of big images.
3. The thumbnails must have the same file names as their bigger counterparts. So, for
example, the thumbnail, for say, image 14.jpg should also be called 14.jpg.
IMPORTANT In this project, the number of thumbnails for each section is limited to 20. It was
my choice to make it this way, based on the gallery's overall layout and concept. You can
increase this number if you want, but then you'll need to rearrange your gallery elements'
position and dimensions to accomodate a higher number of thumbnails. I recommend that you
stick with my concept until the end of this tutorial and then experiment later. Of you do need
more thumbnails for a particular gallery section, I suggest that you split it into two or more
sections. For example, if you have tons of photos from a summer vacation, split them into
different sections, like summer vacation 1, summer vacation 2, etc.

The screenshot below shows the maximum number of thumbnails for a single gallery section.

A small reminder: for this project, the big images should be resized/cropped to 469x311 pixels.
The thumbnails should be made to be 81x54 pixels. Again, I repeat, this suits this particular
project you are learning to create right now. Once you get hold of how things function, make any
other Flash image gallery system.

Before you start working with your photos, here is a hint: If you need a smart, intuitive and easy
to use application for managing your photos, I highly recommend Picasa from Google. It is
completely free.

With Picasa, you can search for and organize your photos on your computer, add many
effects to them and edit them, then share and publish them on the Web. And for free! There are a
lot of applications out there who do the same thing, but none of them is free and so easy to use as
Picasa.

And this wraps it up for the file/folder hierarchy. The last, and probably one of the most
important things, is the ActionScript programming code that powers up the gallery.

10. Inserting the ActionScript code

10.1. Go back to your document. Lock the actions layer and click on its first keyframe to select
it. As you may already know, a layer does not have to be unlocked for you to be able to insert
ActionScript code inside it. In fact, I always lock the layer where my code is contained, to
minimize errors — not to insert any graphics in it by mistake.
TIP If possible, always place all of your ActionScript code into one layer, and also, into as few
keyframes as you can. The layer which contains your ActionScript code should be made
exclusively for that purpose. There is just no sense in placing any graphics or symbols inside it.
Also, place the layer with ActionScript either on top of all layers or below all the other layers so
that you can find it very quick when you need it. This is a time-tested and a very convenient
practice!

10.2. Select Window > Actions to open the Actions panel.

10.3. Insert the following ActionScript code inside the panel:

var menuSpeed:Number = 6;
var menuDown:Button = menuDown_btn;
var menuUp:Button = menuUp_btn;
menuUp._alpha = 0;
menuUp.enabled = false;
var firstLook:Boolean = true;
var menuButtons:MovieClip = galleryMenu_mc.buttonsHolder_mc;
var galleryMask:MovieClip = galleryMenu_mc.galleryMask_mc;
galleryMask._height = 391;
var imagesHolder:MovieClip = imagesHolder_mc;
var descText:TextField = desc_txt;
var imagesInGallery:Array = new Array();
var galleryNames:Array = new Array();
var galleryIntros:Array = new Array();
var descriptions:Array = new Array();
var tracker:Number = new Number();
var whatIsLoading:String = new String();
var galleryBtnLeftMargin:Number = 10;
var galleryBtnUpperMargin:Number = 60;
var galleryBtnVSpace:Number = 23;
var thumbMarginX:Number = 96;
var thumbMarginY:Number = 68;
imagesHolder._x = 243;
imagesHolder._y = galleryBtnUpperMargin;
logo_mc._x = logo_mc._y=galleryBtnLeftMargin;
desc_txt._x = 243;
desc_txt._y = 400;
descText.text = "Click on a gallery name on the left to load its thumbnails. Remember, you can click on a
thumbnail only when all the thumbnails in a gallery have been loaded. When you click on a thumbnail to
see the big image, clicking on the big image will close it and you will return to the gallery. Use the
button(s) above the galleries to scroll through them.";
import flash.filters.DropShadowFilter;
var shadowEffect:DropShadowFilter = new DropShadowFilter(3, 45, 0x000000, 100, 3, 3, 1, 3);
var thumbsFilter:Array = [shadowEffect];
var loader:MovieClipLoader = new MovieClipLoader();
var myListener:Object = new Object();
loader.addListener(myListener);
myListener.onLoadInit = function(target:MovieClip) {
if (whatIsLoading == "thumb") {
currentThumbnail.percent_txt._visible = false;
currentThumbnail.filters = thumbsFilter;
thumbClickable();
tracker++;
if (tracker<howManyImages) {
loadThumbnail();
} else {
enableThumbs();
}
} else if (whatIsLoading == "big") {
target._alpha = 0;
displayBigImage.percent_txt._visible = false;
displayBigImage.filters = thumbsFilter;
bigClickable();
fadeIn();
}
};
myListener.onLoadProgress = function(target:MovieClip, loaded:Number, total:Number) {
percent = Math.floor(loaded/total*100);
if (whatIsLoading == "thumb") {
currentThumbnail.percent_txt._visible = true;
currentThumbnail.percent_txt.text = percent+"%";
} else if (whatIsLoading == "big") {
displayBigImage.percent_txt._visible = true;
displayBigImage.percent_txt.text = percent+"%";
}
};
var imageGallery:XML = new XML();
imageGallery.ignoreWhite = true;
imageGallery.onLoad = function(success) {
if (success) {
parseGalleries();
} else {
descText.text = "Sorry the image data just didn't load.";
}
};
imageGallery.load("gallery/gallery.xml");
function parseGalleries():Void {
if (imageGallery.firstChild.nodeName == "galleries") {
var rootNode:XMLNode = imageGallery.firstChild;
for (i=0; i<rootNode.childNodes.length; i++) {
if (rootNode.childNodes[i].nodeName == "gallery") {
currentGallery = rootNode.childNodes[i];
imagesInGallery.push(currentGallery.childNodes.length);
galleryNames.push(currentGallery.attributes.title);
galleryIntros.push(currentGallery.attributes.intro);
currentGalleryTitle = rootNode.childNodes[i].attributes.title;
currentGalleryButton = galleryMenu_mc.buttonsHolder_mc.attachMovie("gallery section
button", "galleryButton"+i, galleryMenu_mc.buttonsHolder_mc.getNextHighestDepth());
currentGalleryButton._x = 0;
currentGalleryButton._y = galleryBtnVSpace*i;
currentGalleryButton.sectionTitle_txt.text = "0"+(i+1)+" "+currentGalleryTitle.toUpperCase();
for (j=0; j<currentGallery.childNodes.length; j++) {
if (currentGallery.childNodes[j].nodeName == "image") {
currentDescription = currentGallery.childNodes[j].firstChild.toString();
descriptions.push(currentDescription);
}
}
}
}
}
numberOfGalleries = i;
enableButtons(numberOfGalleries);
}
function enableButtons(numberOfGalleries:Number):Void { for (i=0; i<numberOfGalleries; i++) {
pressedButton = galleryMenu_mc.buttonsHolder_mc["galleryButton"+i];
pressedButton.onRollOver = function():Void {
this.gotoAndStop(2);
};
pressedButton.onRollOut = function():Void {
this.gotoAndStop(1);
};
pressedButton.onPress = function():Void {
removeMovieClip(thumbsDisplayer);
removeMovieClip(displayBigImage);
tracker = 0;
thumbsDisplayer = imagesHolder.createEmptyMovieClip("thumbsDisplayer_mc",
imagesHolder.getNextHighestDepth());
clickedGallery = Number(this._name.substr(13));
howManyImages = imagesInGallery[clickedGallery];
whichGallery = galleryNames[clickedGallery];
descText.text = galleryIntros[clickedGallery];
currentRow = 0;
currentColumn = 0;
loadThumbnail();
};
}
enableGalleryNavigation();
}
function loadThumbnail() {
currentThumbnail = thumbsDisplayer.attachMovie("thumbnail holder", "thumbnail"+(tracker+1),
thumbsDisplayer.getNextHighestDepth());
target = currentThumbnail.thumbImage_mc;
if ((tracker%5) == 0 && tracker != 0) {
currentRow += 1;
}
if (currentColumn>3) {
currentColumn = 0;
} else if (tracker == 0) {
currentColumn = 0;
} else {
currentColumn += 1;
}
currentThumbnail._x = currentColumn*thumbMarginX;
currentThumbnail._y = currentRow*thumbMarginY;
currentThumbnail.percent_txt._visible = true;
thumbNumber = currentThumbnail._name.substr(9);
thumbPath = "gallery/"+whichGallery+"/thumbs/"+thumbNumber+".jpg";
whatIsLoading = "thumb";
loader.loadClip(thumbPath, target);
}
function thumbClickable():Void {
currentThumbnail.onPress = function() {
bigNumber = this._name.substr(9);
displayBigImage = imagesHolder.attachMovie("big image holder", "bigImage_mc",
imagesHolder.getNextHighestDepth());
target = displayBigImage.imageHolder_mc;
bigImagePath = "gallery/"+whichGallery+"/"+bigNumber+".jpg";
whatIsLoading = "big";
disableThumbs();
loader.loadClip(bigImagePath, target);
if (clickedGallery>0) {
var descPosition:Number = 0;
for (i=0; i<clickedGallery; i++) {
descPosition += imagesInGallery[i];
}
descPosition = descPosition+Number(bigNumber)-1;
imageDesc = descriptions[descPosition];
} else {
imageDesc = descriptions[Number(bigNumber)-1];
}
descText.text = imageDesc;
};
currentThumbnail.enabled = false;
}
function disableThumbs():Void {
for (i=0; i<howManyImages; i++) {
thumbsDisplayer["thumbnail"+(i+1)].enabled = false;
}
}
function enableThumbs():Void {
for (i=0; i<howManyImages; i++) {
thumbsDisplayer["thumbnail"+(i+1)].enabled = true;
}
}
function bigClickable():Void {
displayBigImage.onPress = function() {
removeMovieClip(this);
enableThumbs();
descText.text = galleryIntros[clickedGallery];
};
}
function fadeIn():Void {
target.onEnterFrame = function():Void {
this._alpha += 10;
if (this._alpha>=100) {
delete this.onEnterFrame;
this._alpha = 100;
}
};
}
function enableGalleryNavigation():Void {
menuDown.onPress = function() {
if (firstLook) {
menuUp._alpha = 100;
menuUp.enabled = true;
firstLook = false;
}
var menuTop:Number = menuButtons._height-Math.abs(menuButtons._y);
if (menuButtons._y<=0 && menuTop>=galleryMask._height) {
var targetPos:Number = menuButtons._y-galleryMask._height;
menuDown.enabled = false;
menuUp.enabled = false;
menuButtons.onEnterFrame = function():Void {
menuButtons._y += (targetPos-menuButtons._y)/menuSpeed;
if (menuButtons._y<=(targetPos+0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};
}
};
menuUp.onPress = function() {
var menuTop:Number = menuButtons._height-Math.abs(menuButtons._y);
if (menuButtons._y<0 && menuTop>0) {
var targetPos:Number = menuButtons._y+galleryMask._height;
menuDown.enabled = false;
menuUp.enabled = false;
menuButtons.onEnterFrame = function():Void {
menuButtons._y += (-menuButtons._y+targetPos)/menuSpeed;
if (menuButtons._y>=(targetPos-0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};
}
};
}

This a really big piece of ActionScript code! More than 230 lines of it! Now save your work and
try to understand all this programming code.

11. Testing the image gallery

11.1. Before testing your gallery, check if all the elements are in place:

 The images, along with their thumbnails, placed in appropriate folders.


 The XML file, with all the elements, some of which must match gallery folders' names.
 The Flash document (.fla file) your currently working on, must be saved in the
appropriate place.

11.2. Select Control > Test Movie. The gallery menu should appear, with each of the sections
buttons having its label. Click on them and see if everything loads properly: the thumbnails, and
then the big images as you click on each thumbnail.

11.3. You should check now if the preloader works: still in the SWF preview window, select
View > Download Settings > 56K and after that View > Simulate Download.
You will see a blank screen for a short period of time, because you have just made Flash
simulate downloading from the Web, to see the preloader in action. When I say preloader, I
mean the one for the images, because this gallery hasn't got its own, main preloader — it's easy
to create one, if you want to know how, just check out my preloader tutorials. I won't delve into
that here, because I want to concentrate on the image gallery.

So, once the gallery has appeared, try clicking on a section button — you should see the
preloader for each thumbnail appear, and if you click on a thumbnail, the big image should begin
preloading. Each image may take a bit to load, because you have chosen the simulated download
setting for one of the slowest connections — a plain 56K modem.

Fine. Let me explain you now the almighty ActionScript routines that are responsible for this
image gallery working so nicely.

12. The ActionScript code behind the image gallery explained

I will explain you the ActionScript programming code by section, for easier understanding. The
code consists of the following parts:

1. Defining variables and positioning the main gallery elements


2. Importing the DropShadow filter
3. Creation of the MovieClipLoader and Listener objects and the functions that enable
preloading
4. Loading XML
5. Parsing XML
o Retrieving gallery data (titles and descriptions)
o Creating menu section buttons dynamically
6. Defining the functionality of the menu section buttons
o Enabling the display of the roll over and roll out states
o Defining which thumbnails shall be loaded
7. Thumbnail positioning and thumbnail preloading
8. Defining the functionality of the thumbnails
o Big image preloading
o
Disabling the thumbnails while the big image is preloading
o
Selecting the right description for the chosen image
9. Making the big image clickable
10. Fading in the loaded big image
11. Creating the scrolling functionality for the gallery sections menu

Let's start!

12.1. Defining variables and positioning the main gallery elements

As you can see, some of the variables here are created to serve as shortcuts to various movie
clips, buttons and text fields:

var menuDown:Button = menuDown_btn;


var menuUp:Button = menuUp_btn;
var menuButtons:MovieClip = galleryMenu_mc.buttonsHolder_mc;
var galleryMask:MovieClip = galleryMenu_mc.galleryMask_mc;
var imagesHolder:MovieClip = imagesHolder_mc;
var descText:TextField = desc_txt;

This is done in order to reference them more easily and to do it a lot more faster. For example,
imagine if you wanted to point to the menuDown_btn button from a galleryMask_mc movie
clip's event handler. Without the shortcut, you would have to do it like this:

this._parent._parent.menuDown_btn

But when you have defined the variables as you did above, so that they serve as references to
various objects in your SWF movie, all you have to do is write them and Flash instantly knows
what movie clip or button you're talking about, no matter where you reference it. So, instead of
writing the above path, all you do is write menuDown and that's it!

And of course, when you are referencing a Movie clip symbol, you have to define the variable
which serves as its shortcut as a Movie clip type of variable:

var imagesHolder:MovieClip = imagesHolder_mc;

In a similar way, variables that reference buttons must of the Button type, and of the TextField
type for text fields.

Next, the speed at which the menu will scroll is defined, in the variable menuSpeed. This value
will be used later, when the scrolling of the menu is going to be defined.

var menuSpeed:Number = 6;
menuUp._alpha = 0;
menuUp.enabled = false;
As you can see above, the menuUp button, which is used to scroll the menu upwards is first made
invisible by turning its _alpha (transparency) property to 0 (zero) and then disabled by setting
its enabled property to false.

Why is this done? To simply turn off and make invisible the button, not to confuse your users. I
have done a little bit of testing and people told me that they don't know which button to press in
the beginning. Since the menu can only be scrolled downwards at first, it makes sense to remove
the menuUp button. This also removes any confusion. So, later you'll see the explanation for the
code that makes the button in question appear, but only once a user has clicked on the menuDown
button.

NOTE You must always think about your users and make your websites as user-friendly as
possible. This can be tricky with Flash, as it offers far more possibilities than plain old HTML,
where navigation is reduced to textual or image links. Flash offers basically infinite possibilities
to create rich, interactive experiences, and that's why you must be careful: Don't let yourself be
seduced by the vast array of eye-candy gizmos that can be made — always keep the user in
mind! Have someone try out your Flash project before you launch it: even just a little bit of
testing with real users (NOT web designers and such, who are web and computer-savvy) can go
a long way towards improving the user experience. I always test my projects before going live. I
suggest you do the same and make this a habit.

The variable firstLook is of the Boolean type, which means that its value can equal only true or
false. This variable will help Flash determine if the user is using the gallery section menu for
the first time. You'll see it later: If the user is indeed using the menu for the first time — by
pressing the menuDown button, the menuUp button will appear and become enabled
(clickable). After that, the firstLook variable's value will be set to false, because once the
button for scrolling the menu up appears, there is no need and sense to do it again.

var firstLook:Boolean = true;

After that, the height of the galleryMask movie clip is set via the _height property of the Movie
clip class. This value is expressed in pixels. I have set it to 391 pixels, because I have found that
this value is fine for showing up a certain number of gallery section buttons. It just looked good
to me, after some experimentation.

galleryMask._height = 391;

See now why it's fine to make a movie clip out of a mask? You can easily readjust its dimensions
via ActionScript — there is no need for you to go back inside the gallery menu movie clip each
time that you want to change it, select the mask, resize it manually, etc. With ActionScript, the
change is done in a snap!

Now come four variables of the Array type. An array is like a big variable: it can store many
values, be those values of the Number type, String (text) type or something else. Think of them
as of filing cabinets, where each drawer contains a value. They are perfect for storing many
values, which will be used later at different points in your code.
var imagesInGallery:Array = new Array();
var galleryNames:Array = new Array();
var galleryIntros:Array = new Array();
var descriptions:Array = new Array();

They serve to contain the following values:

 The imagesInGallery array will store the information on the number of images in each
gallery section.
 The galleryNames array will keep the names (titles) of the sections of your image
gallery. If you recall, these are the names of the folders of different gallery sections,
which are exactly the same as the values of the title attributes of gallery nodes inside your
XML file.
 The galleryIntros array will store the descriptions for each gallery section. These are
the values of the intro attributes belonging to each gallery node in your XML file.
 The descriptions array will store inside itself the textual description for each image in
your gallery, which is going to be pulled out from the XML file too.

All of these arrays will be populated (filled with data) during the XML parsing process, which is
explained later.

The tracker variable is of the Number type (which means it stores numerical values) and it will
serve to keep track of the number of thumbnails when user has clicked on a gallery section and
will also serve to place the thumbnails correctly and evenly into rows.

var tracker:Number = new Number();

The whatIsLoading variable is of the String type (meaning it will contain text values). This
variable's value will serve to tell Flash if the image that is being loaded is a thumbnail or a big
image and to react appropriately in each case.

var whatIsLoading:String = new String();

The variables that follow serve to position different elements of your gallery on the stage:

var galleryBtnLeftMargin:Number = 10;


var galleryBtnUpperMargin:Number = 60;
var galleryBtnVSpace:Number = 23;
var thumbMarginX:Number = 96;
var thumbMarginY:Number = 68;
imagesHolder._x = 243;
imagesHolder._y = galleryBtnUpperMargin;
logo_mc._x = logo_mc._y = galleryBtnLeftMargin;

The galleryBtnLeftMargin and galleryBtnUpperMargin variables hold the values that serve to
position the imagesHolder movie clip (which will contain all the thumbnails and big images,
once they load) and also to position the logo. The variable called galleryBtnVSpace determines
the vertical space between each of the section buttons inside the gallery menu. If you
remember, the height of this button was made to be 20 pixels, so adding three more pixels should
be just fine. The thumbMarginX and thumbMarginY variables' values determine the spacing
between thumbnails of each gallery section.

Next comes the positioning of the big dynamic text field, referred to as desc_txt...

desc_txt._x = 243;
desc_txt._y = 400;

...or using the shortcut (see above), descText. Below is the text that will appear when the gallery
loads and there hasn't been any interaction with it yet from the user. You must give your users
some guidelines for them to be able to use your image gallery more easily.

descText.text = "Click on a gallery name on the left to load its thumbnails. Remember, you can
click on a thumbnail only when all the thumbnails in a gallery have been loaded. When you click
on a thumbnail to see the big image, clicking on the big image will close it and you will return to
the gallery. Use the button(s) above the galleries to scroll through them.";

Of course, you could have devised a graphical element to do this: for example, to give a hint that
the big image will close once clicked upon, a "close" button with a small x inside it could be
made to show up. There are always many ways to improve your user's experience. Choose what
works best and what you think goes well with your gallery's overall design.

12.2. Importing the DropShadow filter

I decided to apply the DropShadow filter to the thumbnails to make them even nicer. The first
thing that you must do before applying a filter to an object inside Flash is to import it. When you
do this, Flash reads from your disk (specifically, from a folder within the Flash installation) and
inserts all the needed code for a particular filter into your SWF movie. Then it can be used and
applied, once the importation has been made.

import flash.filters.DropShadowFilter;

After that, a variable of the DropShadowFilter type is created.

var shadowEffect:DropShadowFilter = new DropShadowFilter(3, 45, 0x000000, 100, 3, 3, 1, 3);

The values between the parenthesis are as follows: distance, angle, color, alpha, blurX, blurY,
strength and quality. They are pretty much self-explanatory. After that, you add the
shadowEffect variable which contains the filter to the thumbsFilter array, which will then be
applied to the thumbnails.

var thumbsFilter:Array = [shadowEffect];


12.3. Creation of the MovieClipLoader and Listener objects and the functions that enable
preloading

If you wish to preload external JPEG images into Flash across all browsers, the best method
available is the one that uses the MovieClipLoader object. This particular object is specifically
made for external content loading. It is great and you will use it to load and preload both the
thumbnails and the big images! Here's how it works:

1. The first thing that you must do is create an instance of the MovieClipLoader object. I
chose to call the variable which will contain it loader.

var loader:MovieClipLoader = new MovieClipLoader();

2. Then, you need to make a listener object, which can be a movie clip or an Object object
(a generic object, let's say so). It will listen to what the MovieClipLoader object is doing
and will react when things start happening: for example, when the loading is started by
the MovieClipLoader or is in progress, the listener is aware of that and reacts by running
specific functions (which will, for example, tell Flash how much has been loaded, etc). I
called the listener object myListener.

var myListener:Object = new Object();

3. And to have the MovieClipLoader and the listener work together nicely, you must
associate the listener object to the MovieClipLoader, like this, using the addListener
method:

loader.addListener(myListener);

Fine. But, before any loading/preloading is going to be done, you must first and foremost write
two important functions:

 One that will tell Flash what to do while an image is being loaded (called
onLoadProgress),
 And the other that will tell it what to do once the loading is complete (called
onLoadInit).

I repeat, these functions must be created before any loading begins. Flash must know what to do
in advance! Let me show you now how I set up the listener object's onLoadInit() function for
the gallery.

myListener.onLoadInit = function(target:MovieClip) {
if (whatIsLoading == "thumb") {
currentThumbnail.percent_txt._visible = false;
currentThumbnail.filters = thumbsFilter;
thumbClickable();
tracker++;
if (tracker<howManyImages) {
loadThumbnail();
} else {
enableThumbs();
}
} else if (whatIsLoading == "big") {
target._alpha = 0;
displayBigImage.percent_txt._visible = false;
displayBigImage.filters = thumbsFilter;
bigClickable();
fadeIn();
}
};

Flash will automatically execute the onLoadInit() function once the external JPG image (or a
SWF, or a GIF...) has been entirely downloaded to the user's hard disk.

First, the function is defined with a parameter (the thing between the function's parenthesis): the
target variable which is a Movie clip. This is the empty movie clip into which the external
image will be loaded.

myListener.onLoadInit = function(target:MovieClip) {

Inside the function (meaning between its curly braces: { and }), the first thing that shows up is an
if/else if conditional statement:

if (whatIsLoading == "thumb") {
currentThumbnail.percent_txt._visible = false;
currentThumbnail.filters = thumbsFilter;
thumbClickable();
tracker++;
if (tracker<howManyImages) {
loadThumbnail();
} else {
enableThumbs();
}
} else if (whatIsLoading == "big") {
target._alpha = 0;
displayBigImage.percent_txt._visible = false;
displayBigImage.filters = thumbsFilter;
bigClickable();
fadeIn();
}

As you can see, this conditional statement looks at the value of the whatIsLoading variable to
decide what to do next. This value is of the string type (meaning it's text) and can equal either
"thumb" or "big". These two values stand for thumbnail and big image. I defined them as such
because it's logical and I can instantly see what do they refer to.

As I said, this function is defined before the actual loading starts. So, as you will see later, once
the loading of an external JPEG image has been triggered, the value of the whatIsLoading
variable will be set to either "thumb" or "big". It is set to "thumb" when the user clicks on a
gallery section button — when the thumbnails of that section should be loaded and displayed. It
is set to "big" when the user has clicked on a thumbnail to see the big image.

So, what happens when the value is set to "thumb"? The following:

currentThumbnail.percent_txt._visible = false;
currentThumbnail.filters = thumbsFilter;
thumbClickable();
tracker++;
if (tracker < howManyImages) {
loadThumbnail();
} else {
enableThumbs();
}

Here is the above code, broken down line by line:

 The dynamic text field inside the thumbnail holder movie clip of the currently loaded
thumbnail is hidden by setting its _visible property to false (remember, this is the text
field that you created earlier in this tutorial, where the percentage preloader will show up
during preloading).
 The drop shadow effect is applied to the thumbnail holder via the movie clip's filters
property.
 The thumbClickable() function is invoked (meaning it is called), which will define
what will happen when the user clicks on a thumbnail: she or he will begin the
loading of its bigger counterpart (the big image). This function comes later in the code,
you'll see it explained too.
 The tracker variable is incremented by one (1 is added to its current value) — that's
what the two plus signs (++) stand for. Remember, this variable is used to let Flash know
which thumbnail is currently being loaded/has been loaded, where it should be placed,
etc.
 Then, an if/else conditional statement shows up, which does the following:
 if the value of tracker variable is lesser than the value of howManyImages variable, the
loadThumbnail() function will be invoked and the next thumbnail will be loaded.
 If that condition isn't true (when tracker's value is equal to or bigger than
howManyImages' value), then the thumbnails will be enabled. This means that they will
be clickable.
The tracker keeps track of the number of thumbnails in the current gallery section (the one that
the user chose to see). The variable howManyImages holds the number of images that exist in the
chosen gallery section. If the current thumbnail isn't the last one loaded — more will be loaded.

When all the thumbnails have been loaded, they are all enabled. This means that the user isn't
able to click on any of the thumbnails until all of them have been completely loaded. This is
because I don't have to deal with additional interactions.

What happens when the value of the whatIsLoading variable has been set to "big"?

target._alpha = 0;
displayBigImage.percent_txt._visible = false;
displayBigImage.filters = thumbsFilter;
bigClickable();
fadeIn();

Here's the breakdown of the above code:

 The _alpha property (transparency) of the target movie clip (the one into which the
big image will be loaded) is set to zero, meaning that it will become invisible. I have
chosen to do this to be able to apply the nice fade-in effect to the big image later :). Why
make a simple instant appearance when you can create a cool fade-in effect?
 Then, as was the case with the thumbnails, the dynamic text field of the big image
holder is made invisible (_visible = false), because the percentage preloader needs
to disappear once the big image has been fully loaded.
 The drop shadow filter is applied to the big image, as it was for the thumbnails.
 The big image is made clickable by calling the bigClickable() function, which you'll
see later. This makes possible for the user to click the big image, and once that has been
done, the image will be removed and the thumbnails will be visible again.
 And finally, the fadeIn() function is invoked to smoothly fade in the big image, from
invisibility to complete opaqueness.

Cool! What comes next is the onLoadProgress() function which monitors the downloading of
the image(s) to the user's computer. This function is used to create the preloaders.

myListener.onLoadProgress = function(target:MovieClip, loaded:Number, total:Number) {


percent = Math.floor(loaded/total*100);
if (whatIsLoading == "thumb") {
currentThumbnail.percent_txt._visible = true;
currentThumbnail.percent_txt.text = percent+"%";
} else if (whatIsLoading == "big") {
displayBigImage.percent_txt._visible = true;
displayBigImage.percent_txt.text = percent+"%";
}
};
This function comes with three parameters:

 target — the empty movie clip which into which the external JPEG is loaded,
 loaded — how much of the image has been loaded so far, in bytes and
 total — the total file size of the image that is being loaded.

Inside the function, the first line servers to calculate the percentage of the image that has been
loaded so far (loaded/total*100) which is then rounded to the nearest lower value with the
floor() method of the Math object.

percent = Math.floor(loaded/total*100);

Next comes a conditional if/else if statement, which, much like in the previous function,
determines if the value of the whatIsLoading variable equals either "thumb" or "big". Then,
whether it is a thumbnail that is being loaded or a big image, what goes on is basically the same:
the percent_txt dynamic text field inside the image holder becomes visible and inside it the
information on how much of the image has been loaded so far is displayed, using the percent
variable followed by the % character.

For the thumbnail:

currentThumbnail.percent_txt._visible = true;
currentThumbnail.percent_txt.text = percent+"%";

...as well as for the big image:

displayBigImage.percent_txt._visible = true;
displayBigImage.percent_txt.text = percent+"%";

The currentThumbnail and displayBigImage variables are defined later, you'll see. There is a
lot going on here in those two functions that hasn't appeared or been defined in your code yet,
but that is, I repeat, because these functions, which are connected to the MovieClipLoader
object and its associated listener object have to be defined before you actually proceed to
load the external JPEG images.

Great! Let's move on to the XML loading part now.

12.4. Loading XML

To load XML data from an external XML file into Flash, you must do the following:

1. Create a new XML object.


2. Create an onLoad() function which will tell Flash what to do after loading has been
finished, whether it was performed successfully or not.
3. Tell Flash to load the XML data from the external XML file.
Here is the code that does exactly that:

var imageGallery:XML = new XML();


imageGallery.ignoreWhite = true;
imageGallery.onLoad = function(success) {
if (success) {
parseGalleries();
} else {
descText.text = "Sorry the image data just didn't load.";
}
};
imageGallery.load("gallery/gallery.xml");

The first line creates a new XML object. I chose to call it imageGallery.

var imageGallery:XML = new XML();

The second one tells Flash to ignore the white space between the chunks of data inside the
XML file:

imageGallery.ignoreWhite = true;

This must be done, yes, because blank spaces in an XML file are considered by Flash as data,
too. That's why you must tell Flash to skip it because otherwise you'll have a mess to deal with.

Now comes the onLoad() function of your XML object. This function (similarly as the ones
used for preloading with the MovieClipLoader and its listener) must be defined before the
actual XML loading takes place. Flash must know in advance what to do once the XML data has
been loaded.

imageGallery.onLoad = function(success) {
if (success) {
parseGalleries();
} else {
descText.text = "Sorry the image data just didn't load.";
}
};

As you can see above, the onLoad() function has one parameter: success. This is a parameter
that gets automatically passed to this function upon XML data loading. It holds a Boolean type
of value, which means that it equals either true or false. It yields as true if the XML data
loading was performed successfully and false if it was not.
Inside the function, there is a simple if/else conditional logic used to help Flash decide what
to do if the loading was successful or not. The line

if (success)

is the shorthand way of writing

if (success == true)

And the else part, of course, is activated only when success turns out to be false. So, when
XML data loading has been successful, the parseGalleries() function is invoked (invoked
means called in programmers' jargon). I chose that name for the function, because it will literally
parse the XML data to extract every bit of information that is needed for the creation of the
image gallery.

parseGalleries();

If the loading of XML data fails, you have to inform your users about that.

descText.text = "Sorry the image data just didn't load.";

The above text is what will appear in the big dynamic text field. Basically, I don't know what
else can be done if the loading process fails. The user can try to reload the page, but most likely
he or she will just close the page with the image gallery and move. If you have created a good
XML file and tested your SWF and seen that it works online with no problems, there is not much
that you can do if now and then some user can't see the gallery because the XML data failed to
load. That is beyond your power: maybe the server where you host your image gallery went
down for a moment or the user has a too strong firewall, router, etc. But it happens rarely. Most
people should see your Flash image gallery with no problems at all.

And now, once you have defined what Flash should do upon loading the XML data, tell it to load
it! LIke this:

imageGallery.load("gallery/gallery.xml");

Notice the path to the XML file: it is stored inside the gallery folder that you have created earlier
in this tutorial, when you created the whole folder structure. This can be a source of problems
too! If you change the folder inside which your XML file resides or the name of the XML file
itself, you must change it in the above line of code too!

REMEMBER When loading external data, you must reference it in relation to the HTML file
inside which your SWF file is embedded, NOT in relation to the SWF file itself, regardless
where it is situated. The HTML page is what's important!

12.5. Parsing XML: Retrieving gallery data (titles and descriptions) and creating the menu
section buttons dynamically
Below is the parseGalleries() function which serves to parse the XML data and store it in
various variables. It looks big... scary... doesn't it? :-) No, it is not! It is just a little bit long, but
everything inside it is perfectly logical and understandable and I will explain it to you in no time
at all! So let's get on with it.

function parseGalleries():Void {
if (imageGallery.firstChild.nodeName == "galleries") {
var rootNode:XMLNode = imageGallery.firstChild;
for (i=0; i<rootNode.childNodes.length; i++) {
if (rootNode.childNodes[i].nodeName == "gallery") {
currentGallery = rootNode.childNodes[i];
imagesInGallery.push(currentGallery.childNodes.length);
galleryNames.push(currentGallery.attributes.title);
galleryIntros.push(currentGallery.attributes.intro);
currentGalleryTitle = rootNode.childNodes[i].attributes.title;
currentGalleryButton = galleryMenu_mc.buttonsHolder_mc.attachMovie("gallery section
button", "galleryButton"+i, galleryMenu_mc.buttonsHolder_mc.getNextHighestDepth());
currentGalleryButton._x = 0;
currentGalleryButton._y = galleryBtnVSpace*i;
currentGalleryButton.sectionTitle_txt.text = "0"+(i+1)+" "+currentGalleryTitle.toUpperCase();
for (j=0; j<currentGallery.childNodes.length; j++) {
if (currentGallery.childNodes[j].nodeName == "image") {
currentDescription = currentGallery.childNodes[j].firstChild.toString();
descriptions.push(currentDescription);
}
}
}
}
}
numberOfGalleries = i;
enableButtons(numberOfGalleries);
}

As you probably noticed, there is a semicolon (:) followed by the ActionScript keyword Void in
the first line of function's code.

function parseGalleries():Void {

This keyword tells Flash that the parseGalleries() function does not return a value. It is
good to specify this, although it isn't obligatory. When you have a function that does return a
value to the caller, you have to specify this. For example, you may have a function which serves
to perform a simple mathematical calculation and so instead of Void, you would write Number
after the function's name and the semicolon, because the function would return a numerical
value.

Inside the function, almost all of the code (except two lines) is contained within an if
conditional statement:
if (imageGallery.firstChild.nodeName == "galleries") {

Notice that I said an if conditional statement, not an if/else one. Why? Because there is no
"else" situation here. The if conditional is used here as to say to Flash "When you find the root
node with the name galleries, do the following". Also, there is no else, because Flash will
find the node named galleries because you created it in the XML file. This is a fail-safe
procedure!

Remember, an XML file has only one root node. So when you say
imageGallery.firstChild.nodeName, you tell Flash to look up the name of the root node — it
is the first child of the XML file (which was converted to XML object when loaded into Flash)
itself.

<?xml version="1.0"?>
<galleries>
...
</galleries>

After that, a shortcut variable called rootNode is created that points to this root node:

var rootNode:XMLNode = imageGallery.firstChild;

This is much like the variables that you have created at the very start of your ActionScript code
to be able to reference movie clips and buttons in a shorthand and practical manner.

Next, you have a for loop that is used to loop through all the child nodes of the root node.

for (i=0; i<rootNode.childNodes.length; i++) {

To be sure that Flash loops through all the child nodes of the root node, set the condition of the
loop as follows: i must be less than the total number of child nodes
(rootNode.childNodes.length). Why less than and not equal to the number of child nodes?
Because the loop starts with i set to zero. Like the position of elements in an array and the
position of characters in a string, for example, the XML nodes are also counted starting from
zero. What follows is an if conditional statement, again. Exactly like for the root node, you tell
Flash here to look for child nodes of the root node that are called gallery.

if (rootNode.childNodes[i].nodeName == "gallery") {

<?xml version="1.0"?>
<galleries>
<gallery title="architecture" intro="These are the photos of various buildings in the cities, towns
and villages I visited during my voyages.">
...
</gallery>
<gallery title="essays" intro="A collection of various photos which either do not fit any other
category - experiments and such.">
...
</gallery>
</galleries>

The variable i will be replaced by the number of the current loop, of course: 0, 1, 2, 3, etc... so
all child nodes will be parsed.

The gallery that is currently being parsed is stored in the currentGallery variable:

currentGallery = rootNode.childNodes[i];

This si done to be able to reference it more easily in the next few lines of code.

Next, the construct currentGallery.childNodes.length is used to pull out the number of


images in the current gallery section. This value is in turn stored inside the imagesInGallery
array (which you created when you defined all the variables) via the push() method of the
Array object.

imagesInGallery.push(currentGallery.childNodes.length);

The imagesInGallery array is very important because the values stored inside it (the number of
images in each gallery section) will be used later to tell Flash how many thumbnails should be
loaded for a given gallery section.

Next, the value of the title attribute for the current gallery node is extracted and stored
inside the galleryNames array via its push() method. This value will be later used to tell Flash
what gallery section the user has chosen and also to give Flash the proper path to the
section's folder.

galleryNames.push(currentGallery.attributes.title);

Using the same procedure as above, the value of the intro attribute is extracted and stored
inside the galleryIntros array. These values will be used to show what's the current gallery
section about — this is the description text which will appear in the big dynamic text field once
the user clicks on a gallery section button.

galleryIntros.push(currentGallery.attributes.intro);

Next, by using the procedure that you understand well by now, the value of the title attribute
of the current gallery section is extracted and stored inside the currentGalleryTitle variable.
There is an important distinction here: before, the same attribute's value was extracted and placed
inside an array along with its counterparts from other gallery nodes and now it is placed inside
a simple, plain variable. This is done because this variable's value will be used very soon.

currentGalleryTitle = rootNode.childNodes[i].attributes.title;
And now, the gallery section button movie clip is being extracted from the Library dynamically
and placed inside the gallery menu:

currentGalleryButton = galleryMenu_mc.buttonsHolder_mc.attachMovie("gallery section


button", "galleryButton"+i, galleryMenu_mc.buttonsHolder_mc.getNextHighestDepth());

The gallery section button that you have created earlier is being attached inside the gallery menu,
more specifically to the buttonsHolder_mc empty movie clip inside it:
galleryMenu_mc.buttonsHolder_mc.attachMovie. As you remember, thsi is the empty clip
beneath the mask in the gallery menu movie clip. The attachMovie() method has 3 parameters:

1. The Linkage identifier which is used to pull a movie clip dynamically out of the
Library: "gallery section button" in this case.
2. The new instance name of the newly attached movie clip. This will be different for each
gallery section of course, so it has to be created dynamically: "galleryButton"+i. So,
as the loop goes on, this instance name will be galleryButton0, galleryButton1,
galleryButton2, etc.
3. The depth level of the attached movie clip. This parameter must also be different for
each attached movie clip, because if it stays the same, each subsequent movie clip will
replace the previous one, because there cannot be two movie clips present on a same
depth level. So, the convenient getNextHighestDepth() method is used to place each
movie clip on a separate depth level. Think of the depth levels as invisible layers inside
the empty movie clip where you are attaching your buttons.

And the currentGalleryButton variable is used as a shortcut for this newly attached movie
clip — the current gallery section button. And now, you see why it is very practical to use such
"variable shortcuts" — there are many things that you will now do with the attached movie clip.
The first one is positioning:

currentGalleryButton._x = 0;
currentGalleryButton._y = galleryBtnVSpace*i;

The first line above serves to position each gallery section button horizontally, via the movie
clip _x property, which defines its horizontal position in relation to the left edge of the stage,
expressed in pixels. This value is 0 (zero) for each gallery section button, because they must be
aligned flawlessly inside the menu.
On the other side, the vertical position of each section button inside the gallery menu is
determined dynamically, because you have to put some space between them:
galleryBtnVSpace*i. If you remember, when you defined all the variables, the
galleryBtnVSpace was set to the value of 23. Like I said, I chose this value in relation to the
height of the buttons, to be able to space them nicely. Since in every loop iteration this value is
multiplied by i, the position of buttons will be: 0, 23, 46, 69, etc.

And now you must define the label for the current gallery section button:

currentGalleryButton.sectionTitle_txt.text = "0"+(i+1)+" "+currentGalleryTitle.toUpperCase();

As you can see above, this label is composed of a few things, all were my choice. I could have
just slapped the plain gallery section title over each button, but I wanted to add numbers and also
put all the letters into capitals:

 I added a zero ("0") in front of each number because it looks cool :-).
 After the zero comes the number, which is defined as i+1 because I didn't want the first
label to be preceded with "00", but "01". Remember, in the main loop, the variable i
starts as zero.
 Then comes a blank space, to separate the number from the title: " ".
 Then I transformed the titles into uppercase: currentGalleryTitle.toUpperCase().
That's why I advise to always write such elements inside your XML file in lowercase
letters: it is easy to transform them any way you like with ActionScript later.

And now comes the for loop which passes through each image element inside each gallery
node:

for (j=0; j<currentGallery.childNodes.length; j++) {


if (currentGallery.childNodes[j].nodeName == "image") {
currentDescription = currentGallery.childNodes[j].firstChild.toString();
descriptions.push(currentDescription);
}
}

Since this loop is contained within the main loop, you must naturally change the variable: it is j
here. The condition for the loop to continue the iterations is that j, which starts at 0, must be
lesser than the number of the child nodes of the current gallery node, i.e. the number of
image nodes.
Again, you have an if which checks that the name of each node looked at is indeed "image" and
not something else. Like before, this is a way of telling Flash to look at precisely these nodes.

<?xml version="1.0"?>
<galleries>
<gallery title="architecture" intro="These are the photos of various buildings in the cities, towns
and villages I visited during my voyages.">
<image>Dallas.</image>
<image>Tresnjevka. I love the atmosphere on this one.</image>
<image>Motovun.</image>
<image>New York.</image>
<image>Paris.</image>
</gallery>
<gallery title="essays" intro="A collection of various photos which either do not fit any other
category - experiments and such.">
<image>Color mayhem!</image>
<image>The sleeping monster.</image>
<image>Let me out!</image>
<image>A barrel on the side of the trail.</image>
<image>Subterranean passage.</image>
<image>A train in snow.</image>
</gallery>
</galleries>

Then, as each image node is found, its first child's value is converted to a String (text) value.

currentDescription = currentGallery.childNodes[j].firstChild.toString();

For example, the value of the first child node of the fourth image node in the first gallery node
above is New York. And since this is an XML node, it has to be converted to a String value, for
Flash to be able to display in the dynamic text field later and not to spit out a type mismatch
error. Yes, the text between the <image> opening and closing tag is considered the image node's
first child.

And the text (which is the description of each particular image) is then stored inside the
descriptions array.

descriptions.push(currentDescription);

Finally, after the big for loop has ended after going through all the gallery nodes, the value of
i, which matches the number of galleries (sections) is stored inside the numberOfGalleries
variable.

numberOfGalleries = i;

This number will be used later to determine the number of gallery section buttons and loop
through all of them.
And finally, the enableButtons() function is called and the variable numberOfGalleries is
passed to it.

enableButtons(numberOfGalleries);

Whew! That was all about XML parsing and data extraction!

12.6. Defining the functionality of the menu section buttons: Enabling the display of the roll
over and roll out states and defining which thumbnails shall be loaded

Here's the enableButtons() function which has numberOfGalleries passed as a parameter to


it (which is of the Number type) and it does not return a value, hence the Void keyword:

function enableButtons(numberOfGalleries:Number):Void {
for (i=0; i<numberOfGalleries; i++) {
pressedButton = galleryMenu_mc.buttonsHolder_mc["galleryButton"+i];
pressedButton.onRollOver = function():Void {
this.gotoAndStop(2);
};
pressedButton.onRollOut = function():Void {
this.gotoAndStop(1);
};
pressedButton.onPress = function():Void {
removeMovieClip(thumbsDisplayer);
removeMovieClip(displayBigImage);
tracker = 0;
thumbsDisplayer = imagesHolder.createEmptyMovieClip("thumbsDisplayer_mc",
imagesHolder.getNextHighestDepth());
clickedGallery = Number(this._name.substr(13));
howManyImages = imagesInGallery[clickedGallery];
whichGallery = galleryNames[clickedGallery];
descText.text = galleryIntros[clickedGallery];
currentRow = 0;
currentColumn = 0;
loadThumbnail();
};
}
enableGalleryNavigation();
}

Almost all the code of the enableButtons() function is wrapped in a for loop which serves to
pass through all the gallery section buttons and define their onRollOver, OnRollOut and
onPress event handler functions.

for (i=0; i<numberOfGalleries; i++) {


Now you see how important the numberOfGalleries variable is — without it, you wouldn't be
able to know the number of gallery section buttons.

The first thing that needs to be done is to set up another shorcut: a variable which will point to
each button in your gallery menu as the loop progresses: pressedButton.

pressedButton = galleryMenu_mc.buttonsHolder_mc["galleryButton"+i];

Of course, Flash will process the expression between the angled brackets: [ and ], which will
result in galleryButton0, galleryButton1, galleryButton2, etc.

Now comes the definition of the onRollOver event handler function, which gets executed when
the user rolls her mouse over a button in the gallery section menu:

pressedButton.onRollOver = function():Void {
this.gotoAndStop(2);
};

Basically, what happens is that the movie clip's (which acts as a gallery section button) playhead
gets sent to the second frame, where there is a different background color, to accentuate the
rollover effect.

After that, the rollOut event handler function is defined, which gets run once the mouse has
been pulled out of the button area. This returns the movie clip's playhead to the first frame,
putting it back to its primary state.

pressedButton.onRollOut = function():Void {
this.gotoAndStop(1);
};

NOTE In both event handler functions, the keyword this points to the gallery section button
movie clip itself, because it is contained inside the functions (inside the curly braces). Thanks to
this, there is no need to specify the full path to the movie clip.

The diagram below explains this functionality well. The gallery section button has a blue
background in the first frame and a crimson one in the second frame, when the onRollOver event
has been fired and its event handler function executed.
And now, a very important event handler function comes up: onPress, which governs what
actions will be taken when the user has clicked a button. What will happen is the following:

1. Any previously existing thumbnails and big image will be removed.


2. The tracking of the number of thumbnails will be reset to zero.
3. A new empty movie clip which will hold all the section's thumbnails will be created.
4. The following information will be retrieved and stored: what gallery section was selected,
how many images are in it, the name (title) of the section and its description.
5. The variables which keep track of the rows and columns into which the thumbnails are
placed will be reset to zero.
6. The function for loading the section's thumbnails will be invoked.

pressedButton.onPress = function():Void {
removeMovieClip(thumbsDisplayer);
removeMovieClip(displayBigImage);
tracker = 0;
thumbsDisplayer = imagesHolder.createEmptyMovieClip("thumbsDisplayer_mc",
imagesHolder.getNextHighestDepth());
clickedGallery = Number(this._name.substr(13));
howManyImages = imagesInGallery[clickedGallery];
whichGallery = galleryNames[clickedGallery];
descText.text = galleryIntros[clickedGallery];
currentRow = 0;
currentColumn = 0;
loadThumbnail();
};

Any thumbnails or big images that may have been loaded before are removed with the
removeMovieClip() method. If there weren't any present, it doesn't matter — nothing will
happen. This is done by removing the placeholder movie clips that are created when the user
clicks on a gallery section button or a thumbnail.

removeMovieClip(thumbsDisplayer);
removeMovieClip(displayBigImage);

Then, the tracker is reset to zero.


tracker = 0;

And the thumbsDisplayer empty movie clip is created from scratch, using the
createEmptyMovieClip() method. It will hold all the thumbnails of the gallery section that
was selected by the user. This movie clip is created inside the imagesHolder movie clip, the
empty movie clip which you have created on the stage during the first stages of this tutorial. You
could have created this latter one dynamically via ActionScript too, but I wanted things to be a
little more diverse and simplified. Not everything needs to be done through coding.

thumbsDisplayer = imagesHolder.createEmptyMovieClip("thumbsDisplayer_mc",
imagesHolder.getNextHighestDepth());

There are two parameters used in the createEmptyMovieClip() method:

 The first is the instance name of the newly made empty movie clip.
 The second one is the depth level into which the new movie clip is placed. Again, the
best thing to do is to use the getNextHighestDepth() method because with it, Flash
automatically assigns the first free depth to the new movie clip. And of course, this depth
level is the first free inside the imagesHolder movie clip, the one inside which the new
empty movie clip is being created.

Now the clickedGallery variable gets its value assigned. This value will be the identification
number of the gallery section movie clip which was clicked. Since it is being extracted from
the movie clip's instance name, you need to pass it through the Number() method to convert the
character into a number.

clickedGallery = Number(this._name.substr(13));

The substr() method of the String object is used to do the extraction, since the instance name
of the movie clip is a string (text) value. It goes on like this: suppose that the user clicked on the
fourth gallery section button (which is the monochrome section in my gallery example). The
instance name of the clicked movie clip will be galleryButton3. Yes, there is the number 3 at the
end of the instance name, because, as you remember, in the for loop which is used to create
these buttons, the starting value is always zero. The extraction would proceed like this (this is
pseudo-code, not real one, just to show you how this process goes):

clickedGallery = Number(this._name.substr(13));
clickedGallery = Number("galleryButton3".substr(13));
clickedGallery = Number(3);
clickedGallery = 3;

The first parameter of the substr() method is the starting point of extraction. The first
character in a string (a piece of text) has the position 0 (zero).

The second parameter is the number of characters to be extracted (the length of the new,
extracted string). And if it is omitted (like above), then all the characters from that point until the
end of the string will be extracted. So it doesn't matter if your button has the name
galleryButton3, galleryButton42 or galleryButton128, the number will always get extracted
properly, because the extraction starts at position 13 and gets any remaining characters in the
string from that point on.

After the extraction has been done, the result is converted to a mathematical value from a
plain text character.

And this final value is used three times after that:

howManyImages = imagesInGallery[clickedGallery];
whichGallery = galleryNames[clickedGallery];
descText.text = galleryIntros[clickedGallery];

Specifically, It is used to:

1. See how many images are in the selected gallery section (howManyImages).
2. What is the name/title of the selected gallery section (whichGallery).
3. Get and display the description for the selected gallery section ( descText.text).

All three values are extracted from different arrays. In all three cases, this happens in the same
manner, so I will explain it for the gallery title, for example. Let's suppose again that the user
clicked on the fourth (monochrome ) button, so the value of the clickedGallery variable is 3.
Flash will proceed like this:

whichGallery = galleryNames[clickedGallery];
whichGallery = galleryNames[3];
whichGallery = "monochrome";

Why so? Because the number between the angled brackets: [ and ] points to the value at the
position no. 3 inside the galleryNames array. You may already know it, but here it is: the first
value inside an array in ActionScript has the position 0. The image below explains this nicely.

Now you see how the values for the other two variables were extracted from their respective
arrays, too.

Next, the values of the variables which serve to place the thumbnails into rows of five are reset
to zero:

currentRow = 0;
currentColumn = 0;
Then the loadThumbnail() function is invoked, which will load the thumbnails for the chosen
gallery section. This functions comes in the code just after the current one. Remember that all of
this happens when the user has clicked on a gallery section button.

loadThumbnail();

Once all of three event handler functions (onRollOver, onRollOut and onPress) for all the gallery
section menu buttons have been properly defined, there is still one line of code (outside the for
loop, so it is executed once the loop has reached its end) that is going to be run:

enableGalleryNavigation();

This calls the enableGalleryNaviagtion() function which sets up the scrollability of the menu
via the two buttons (up and down). This function will be defined at the end of all the gallery's
code.

Let me explain you now what happens when a gallery section button has been clicked and the
thumbnails begin to load via the loadThumbnail() function.

Top of page

12.7. Thumbnail positioning and thumbnail preloading

So, the user has clicked on a gallery section to see its images. Here is the function that will attach
the thumbnail holders, place them in an orderly fashion and trigger the preloading, so that the
user can see that something is actually happening!

function loadThumbnail() {
currentThumbnail = thumbsDisplayer.attachMovie("thumbnail holder",
"thumbnail"+(tracker+1), thumbsDisplayer.getNextHighestDepth());
target = currentThumbnail.thumbImage_mc;
if ((tracker%5) == 0 && tracker != 0) {
currentRow += 1;
}
if (currentColumn>3) {
currentColumn = 0;
} else if (tracker == 0) {
currentColumn = 0;
} else {
currentColumn += 1;
}
currentThumbnail._x = currentColumn*thumbMarginX;
currentThumbnail._y = currentRow*thumbMarginY;
currentThumbnail.percent_txt._visible = true;
thumbNumber = currentThumbnail._name.substr(9);
thumbPath = "gallery/"+whichGallery+"/thumbs/"+thumbNumber+".jpg";
whatIsLoading = "thumb";
loader.loadClip(thumbPath, target);
}

The first action inside the function is the process of attaching a thumbnail holder movie clip
from the Library, to the thumbsDisplayer empty movie clip. This is done with the
attachMovie() method which you have already encountered in this tutorial.

currentThumbnail = thumbsDisplayer.attachMovie("thumbnail holder",


"thumbnail"+(tracker+1), thumbsDisplayer.getNextHighestDepth());

The parameters of the method are as follows:

1. The Linkage identifier, which serves to pull the movie clip out of the Library:
"thumbnail holder".
2. The new instance name of the attached movie clip: "thumbnail"+(tracker+1). So the
Instance names will be thumbnail1, thumbnail2, thumbnail3... and so on, until
thumbnail20. Remember, I created the gallery so that each section can have a maximum
of 20 thumbnails. I have written (tracker + 1) here because I don't want the name of
the first thumbnails to be thumbnail0, but thumbnail1. Why? Because I will need to
extract that number later to point to the thumbnail JPEG image, and the first thumbnail in
each gallery section is name 1.jpg and not 0.jpg.
3. And of course, the depth level assignment via the getNextHighestDepth() method.

And the newly attached movie clip is referenced by the currentThumbnail variable.

Next, the target variable is defined, which will tell Flash where the external thumbnail will be
loaded into. As you can see in the line of ActionScript code below, it is being loaded inside the
thumbImage_mc empty movie clip of the current thumbnail holder.

target = currentThumbnail.thumbImage_mc;

And now come the chunks of code which serve to position the thumbnails into rows, 5
thumbnails per row. First, the counting of rows is done.

if ((tracker%5) == 0 && tracker != 0) {


currentRow += 1;
}

The important thing to be aware of here is that this line serves to place thumbnails in rows of 5,
so the condition(s) will be fulfilled for thumbnail number 6, 11and 16 (when tracker equals 5,
10 or 15). This means that when those thumbnails' turn comes, the value of the currentRow
variable will be increased by 1 (currentRow += 1).

There are two conditions in the if conditional statement here and both must be fulfilled in order
for the code inside the curly brackets to be executed:
 The remainder of tracker divided by 5 must be equal to zero. It is divided by 5
because I want 5 thumbnails to be inside a row. Check out my tutorial on the use of the
modulo operator in ActionScript to see how it is done.
 The value of tracker variable must not equal zero. This one serves only not to
increase the value of currentRow when tracker is still equal to zero. This is a safeguard
that ensures the first 5 thumbnails are placed in the first row and not moved below it.

For example, what happens at the beginning, when tracker equals 0, or when it equals, say, 3 or
5? Let me show you how Flash makes the calculation in all three cases:

(tracker%5) == 0 && tracker != 0


(0%5) == 0 && 0 != 0

You don't even have to look at the first condition in the example above, because the second
condition is false. It says that zero does not equal (!=) zero, which is false. And when just one
condition turns out as false, the whole thing is scrapped and the code inside the curly braces
(currentRow += 1) is skipped altogether.

OK, let's see now what happens when tracker equals 3.

(tracker%5) == 0 && tracker != 0


(3%5) == 0 && 3 != 0
3 == 0 && 3 != 0

This time, it is the first condition that yields as false (it says that 3 equals 0, which is false) and
so the whole thing is again false.

And now, the case when the value of tracker reaches either 5, 10 or 15:

(tracker%5) == 0 && tracker != 0


(5%5) == 0 && 5 != 0
0 == 0 && 5 != 0

Both conditions are now true, because zero does equal zero and five does not equal zero. Here,
the value of currentRow will be increased by 1 and this will be used later to place the
subsequent five thumbnails into the next row.

Ok, you need now to see the code that will ensure that the thumbnails are set apart from each
other:

if (currentColumn>3) {
currentColumn = 0;
} else if (tracker == 0) {
currentColumn = 0;
} else {
currentColumn += 1;
}

Translated into english, this if/else if/else conditional statement means this:

if (the value of currentColumn is greater then 3 — meaning it is not 0, 1, 2 or 3) {


reset the value of currentColumn to 0
} on the other hand, if (tracker equals zero) {
reset the value of currentColumn to 0
} and in all other cases, meaning when currentColumn is either 0, 1, 2 or 3 {
increase the value of currentColumn by 1
}

And finally, the code that actually positions the thumbnails on stage based on what I just
explained to you.

currentThumbnail._x = currentColumn*thumbMarginX;
currentThumbnail._y = currentRow*thumbMarginY;

The _x and _y properties, as you know by now, position a movie clip horizontally and vertically
on the stage. The value of currentColumn is multiplied by thumbMarginX and that of
currentRow is multiplied by thumbMarginY. These two values serve to put some space
between the thumbnails. You defined them at the beginning of your code, remember? They are
set to 96 and 68, respectively. This is the value of space between the thumbnails expressed in
pixels.

And now the dynamic text field inside the thumbnail holder is made visible:

currentThumbnail.percent_txt._visible = true;

Using the substr() method of the String object (a text object, and the name of a movie clip is
a piece of text), the number of the thumbnail is extracted:

thumbNumber = currentThumbnail._name.substr(9);
As I have told previously in this tutorial, the first parameter of the substr() method is the place
where the extraction starts. And when the second parameter (length) is omitted, as above, all
the characters from the exatraction point up to the end of the string will be extracted. Why do
this? Because like that, you will be able to extract the number of the thumbnail, whether it is a
one or two-digit number. No need to write any conditional statements at all here. The image
below explains this clearly (the blue numbers are character positions inside the string):

And the value of the thumbNumber variable is used next to point to the right thumbnail which
needs to be loaded:

thumbPath = "gallery/" + whichGallery + "/thumbs/" + thumbNumber + ".jpg";

The line above is using simple concatenation (the joining of two or more strings together) to
create the path to the thumbnail. Again, remember well that this path is relative to the HTML
page inside which your image gallery SWF is embedded.

For example, if the third thumbnail of the essays gallery section were to be loaded, Flash would
create the path like this:

thumbPath = "gallery/" + whichGallery + "/thumbs/" + thumbNumber + ".jpg";


thumbPath = "gallery/" + "essays" + "/thumbs/" + "3" + ".jpg";
thumbPath = "gallery/essays/thumbs/3.jpg";

Subsequently, you have to tell Flash what is loading, the thumb or the big image:

whatIsLoading = "thumb";

And finally, the loadClip() method of the MovieClipLoader object (which is called loader,
you created it earlier, remember) is used to tell Flash to start loading (and preloading) the current
thumbnail:

loader.loadClip(thumbPath, target);

The first parameter inside the parenthesis is the external file that is going to be loaded (a JPEG
thumbnail in this case). The second parameter is the target empty movie clip into which the
external file will be loaded.
And now that the loadClip() method has been invoked, the MovieClipLoader and its associated
listener will start working together and preload the image and display it, with the DropShadow
filter applied to it. You can read again (I recommend it, it will be much more clear to you now)
how this is done on the page which explains the use of the onLoadInit() and onLoadProgress()
methods.

12.8. Defining the functionality of the thumbnails

I will show you now the following things that are part of the thumbnails' functionality:

 Big image preloading


 Disabling the thumbnails while the big image is preloading
 Selecting the right description for the chosen image

function thumbClickable():Void {
currentThumbnail.onPress = function() {
bigNumber = this._name.substr(9);
displayBigImage = imagesHolder.attachMovie("big image holder", "bigImage_mc",
imagesHolder.getNextHighestDepth());
target = displayBigImage.imageHolder_mc;
bigImagePath = "gallery/"+whichGallery+"/"+bigNumber+".jpg";
whatIsLoading = "big";
disableThumbs();
loader.loadClip(bigImagePath, target);
if (clickedGallery>0) {
var descPosition:Number = 0;
for (i=0; i<clickedGallery; i++) {
descPosition += imagesInGallery[i];
}
descPosition = descPosition+Number(bigNumber)-1;
imageDesc = descriptions[descPosition];
} else {
imageDesc = descriptions[Number(bigNumber)-1];
}
descText.text = imageDesc;
};
currentThumbnail.enabled = false;
}

The first thing that can be noticed is that nearly all the code inside the thumbClickable()
function is stored inside the current thumbnail's onPress event handler function definition. This
is to be expected, because the onPress event handler tells Flash what to do when the user click
on a thumbnail.

currentThumbnail.onPress = function() {
The first that you have to do is make Flash extract the number of the big image that is going to
be preloaded once the user clicks on a thumbnail:

bigNumber = this._name.substr(9);

This is done in exactly the same manner as it was for the thumbnails (explained on the previous
page), so I won't repeat myself here.

Next, the big image holder movie clip is pulled out of from the Library and attached to the
imagesHolder empty movie clip using the attachMovie() method which you now well by now:

displayBigImage = imagesHolder.attachMovie("big image holder", "bigImage_mc",


imagesHolder.getNextHighestDepth());

Of course, once again, a variable is used as a shortcut to point to the newly attached movie clip:
displayBigImage. As a reminder, this movie clip contains:

1. The white background with thin black outline,


2. The empty movie clip inside which the big JPEG image will be loaded and
3. The dynamic text field which will display the percentage-based preloader.

And so the empty movie clip (mentioned under no.2 above) is defined as the target for loading
the external JPEG and will be passed as such to the MovieClipLoader later:

target = displayBigImage.imageHolder_mc;

The path to the big JPEG image is defined in a way similar to those of the thumbnails:

bigImagePath = "gallery/"+whichGallery+"/"+bigNumber+".jpg";

The variables whichGallery and bigNumber are used to guide Flash to the right folder and right
image. And the path is stored inside the bigImagePath variable.

Just like for the thumbnails before, you have to tell Flash what you're loading here too:

whatIsLoading = "big";

And the thumbnails have to be disabled — this will stay so throughout the preloading process
and also while the big image is being displayed. They will be re-enabled only once the user has
clicked on the big image and it has disappeared, showing the thumbnails again. This is done
through the disableThumbs() function which I will explain to you later.

disableThumbs();

And now the actual command to load the big image is issued to Flash:
loader.loadClip(bigImagePath, target);

The above is done using the loadclip() method of the MovieClipLoader object, exactly in the
same manner as was done for the thumbnails. Only the path and the target empty movie clip are
different.

The next chunk of code is the one where the description for the selected big image is being
searched for, found and displayed in the big text field below the image:

if (clickedGallery > 0) {
var descPosition:Number = 0;
for (i=0; i<clickedGallery; i++) {
descPosition += imagesInGallery[i];
}
descPosition = descPosition+Number(bigNumber)-1;
imageDesc = descriptions[descPosition];
} else {
imageDesc = descriptions[Number(bigNumber)-1];
}
descText.text = imageDesc;

The search for description is placed inside an if/else conditional statement. Basically, this
conditional logic boils down to this: if the user has clicked any gallery section than the first one
(clickedGallery > 0), a for loop will be initiated for calculating the precise position of the
selected image's description. If the first gallery section is selected by the user, a much simpler
search is performed. I will explain the first case in more detail noe.

First there is the descPosition variable, whose initial value is 0. This variable will hold the
number which will be the image's description position inside the descriptions array.

var descPosition:Number = 0;

Then, the for loop is initiated. The condition for the loop to exist is that i, set to zero, must be
lesser than the value of clickedGallery. Remember, clickedGallery is a variable that holds
the number of the clicked gallery.

for (i=0; i <clickedGallery; i++) {


descPosition += imagesInGallery[i];
}

Every time a loop iteration is made, the value of descPosition is updated. The value on the
equation's right side is added to the descPosition's current value, through the use of the
addition assignment (+=) operator. What's on the right side is a construct that is pulling values
out of the imagesInGallery array. All this is done in order for Flash to be able to find and
display the proper image description.
It will be best explained by an example. In my gallery example, suppose the user has clicked on
the sixth thumbnail in the third gallery section (it is circled in red below, while the gallery
section is in rollover state, just for the purpose of showing it here). The text for this image should
be "Empty silos."

Since the user has clicked the third gallery, the value of clickedGallery is 2, because they start
from zero. The first iteration (when i equals 0) goes like this:

descPosition += imagesInGallery[i];
0 += imagesInGallery[0];
0 += 5;
5

So the value of descPosition is now 5. Why? Because the array imagesInGallery stores
values which correspond to the number of images in each gallery section. In my example, they
are as follows, from the first to last gallery section: 5,6,19,9,7 (corresponding to architecture,
essays, factory, monochrome and nature sections, respectively). The point is that you have to
arrive to the gallery section which the user has selected.

Ok, here comes the next loop iteration, when i equals 1.

descPosition += imagesInGallery[i];
5 += imagesInGallery[1];
5 += 6;
11

The value of descPosition is now 11. Why? Simple. Because the loop has come to en and.
Once i has reached the value of 1, the next iteration won't be performed because the
condition won't validate any more: when i equals 2, the condition i < clickedGallery is
false, because clickedGallery equals 2, in this particular example.

And after that, the next line is executed, which updates the value of descPosition. Flash has
arrived at the third gallery section, but now it must find the description inside this particular
section. This boils down to adding a number until you reach the matching description.

descPosition = descPosition+Number(bigNumber)-1;
Still using the example above, the equation would be calculated like this:

descPosition = descPosition+Number(bigNumber)-1;
descPosition = 11+Number(6)-1;
descPosition = 11+6-1;
descPosition = 16;

First, bigNumber had to be converted into a numerical value (from a String type to a Number
type), because it was a simple text character, not a numerical value, since it was pulled out of
current big image's name.

Then, one is substracted from it, since I chose to give the thumbnails (and subsequently, the big
images too) the numbers starting from 1 and not 0.

And there you go! The right description is really chosen: it is the 17th description in the
descriptions array, placed at number 16, because the counting inside an array starts from 0. In
this case, it is "Empty silos." And that's what precisely the next line of code is about: pulling out
this description from the descriptions array and putting it inside the imageDesc variable.

imageDesc = descriptions[descPosition];

And now for the else part of the conditional statement:

} else {
imageDesc = descriptions[Number(bigNumber)-1];
}

It is used when the user has clicked on the first gallery section. No looping is necessary here,
because this section's descriptions are right at the beginning of the descriptions array. And
that's why the image description is pulled out from the array in a single line of code.

The description of the big image is subsequently displayed in the big dynamic text field below it:

descText.text = imageDesc;

That's it for the thumbnail's onPress event handler. The one line of code that is executed outside
this event handler function, but inside the thumbClickable() function is the following:

currentThumbnail.enabled = false;

...which disables the thumbnail until all of them are loaded for the current gallery section. And
here come now the two functions that disable and enable the clickability of the thumbnails.

The first one, disableThumbs() serves to turn off the clickability of the thumbnails. This
function is invoked whenever the user clicks on a thumbnail and the big image starts to load.
function disableThumbs():Void {
for (i=0; i<howManyImages; i++) {
thumbsDisplayer["thumbnail"+(i+1)].enabled = false;
}
}

How does it work? It uses a for loop to loop through all the thumbnails. It will loop as many
times as there are thumbnails in the selected gallery section (i < howManyImages). Then, they
are disabled one by one via turning their enabled property to false. Each thumbnail is accessed
through the expression thumbsDisplayer["thumbnail"+(i+1)]. Why i+1? Well, again, I
repeat, I have named the thumbnails thumbnail1, thumbnail2, etc, while the starting value of i in
the loop is 0.

The function that restores the clickability of the thumbnails, enableThumbs(), works in the
exact same way, the only difference being the enabled property turned to true this time. This
function is invoked either when the user clicks on a gallery section button in the menu and all the
thumbnails have been successfully loaded or when the big image was clicked, closed and the
thumbnails for the selected section have appeared again.

function enableThumbs():Void {
for (i=0; i<howManyImages; i++) {
thumbsDisplayer["thumbnail"+(i+1)].enabled = true;
}
}

Allright, that's it for the thumbnails. But what about the big image? It has to be made clickable,
for the user to be able to close it once she or he wishes to return to the thumbnails. That's what
the bigClickable() function is here for.

Top of page

12.9. Making the big image clickable

Inside the bigClickable() function, the big image's onPress event handler function is defined.

function bigClickable():Void {
displayBigImage.onPress = function() {
removeMovieClip(this);
enableThumbs();
descText.text = galleryIntros[clickedGallery];
};
}

The line

removeMovieClip(this);
removes the big image with the removeMovieClip() method, inside the parenthesis of which is
the movie clip destined for removal. The keyword this points to the big image itself, since it is
placed inside its onPress event handler function.

After that , the enableThumbs() function call is made. So, the thumbnails will be made clickable
again, since the big image has been removed and they can be seen again. You probably noticed
that I never made any code that would hide the thumbnails, because the big image effectively
covers them all, even when there are twenty of them present. That's just how I solved the
problem, of course, if you wish, you may choose to hide them.

Lastly, the description text is reverted to the one that describes the selected gallery section.

descText.text = galleryIntros[clickedGallery];

OK! Let me show you now how that nice alpha fade-in effect was achieved.

12.10. Fading in the loaded big image

Why go for a simple image appearance when there is eye-candy like the alpha fading in effect at
your disposal? :-)

function fadeIn():Void {
target.onEnterFrame = function():Void {
this._alpha += 10;
if (this._alpha>=100) {
delete this.onEnterFrame;
this._alpha = 100;
}
};
}

This function consists of an onEnterFrame movie clip event handler. This particular movie clip
event is used very often because it makes possible for actions to be performed repeatedly. To be
more exact, every line of code contained inside an onEnterFrame event handler will be executed
as many times per second as your movie speed is set to. So, if your movie speed is set to 30 fps,
the code inside the onEnterFrame event handler will be run 30 times in a second. Ideal for a
fade-in effect!

What happens inside is that the _alpha property (transparency) of the target movie clip, into
which the big image has been loaded, is increased by 10 each time the event fires.

this._alpha += 10;

Remember that the target movie clip's _alpha property was set to 0 (total transparency, i.e.
invisibility) once the onLoadInit() function (one of the two preloading functions) saw that the
loaded file was the big image.
And once _alpha becomes equal to or greater than 100 (this._alpha >= 100), the
onEnterFrame event handler is deleted and the alpha set to 100.

if (this._alpha >= 100) {


delete this.onEnterFrame;
this._alpha = 100;
}

The keyword this inside the onEnterFrame event handler function points to the target movie
clip, because it is placed inside an event handler function associated with it
(target.onEnterFrame). This function is invoked once the image has been fully loaded.

12.11. Creating the scrolling functionality for the gallery sections menu

I have made an example just for the purpose of showing you how the menu will look like when
there are plenty of sections inside it. The section buttons in the example below are not clickable,
but the menu is perfectly scrollable. Click on the down button to try it and then the up button
when it appears!

The big function that follows, enableGalleryNavigation(), is made of two main parts: the
definitions of onPress event handler functions for the two buttons that serve for scrolling the
menu: menuDown and menuUp. Just as a reminder, here is a screenshot of these two buttons:

function enableGalleryNavigation():Void {
menuDown.onPress = function() {
if (firstLook) {
menuUp._alpha = 100;
menuUp.enabled = true;
var firstLook:Boolean = false;
}
var menuTop:Number = menuButtons._height-Math.abs(menuButtons._y);
if (menuButtons._y<=0 && menuTop>=galleryMask._height) {
var targetPos:Number = menuButtons._y-galleryMask._height;
menuDown.enabled = false;
menuUp.enabled = false;
menuButtons.onEnterFrame = function():Void {
menuButtons._y += (targetPos-menuButtons._y)/menuSpeed;
if (menuButtons._y<=(targetPos+0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};
}
};
menuUp.onPress = function() {
var menuTop:Number = menuButtons._height-Math.abs(menuButtons._y);
if (menuButtons._y<0 && menuTop>0) {
var targetPos:Number = menuButtons._y+galleryMask._height;
menuDown.enabled = false;
menuUp.enabled = false;
menuButtons.onEnterFrame = function():Void {
menuButtons._y += (-menuButtons._y+targetPos)/menuSpeed;
if (menuButtons._y>=(targetPos-0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};
}
};
}

Let's see how the functionality of the menuDown button is set up. To understand what is going
on inside the function, keep in mind the following facts:

1. In Flash coordinate system, the vertical direction (Y) is positive downwards. This means
the further you go down from the origin point, the bigger the positive value of an object's
Y coordinate.
2. Each movie clip has its own independent coordinate system. The origin of this coordinate
system is the movie clip's registration point.

menuDown.onPress = function() {
if (firstLook) {
menuUp._alpha = 100;
menuUp.enabled = true;
firstLook = false;
}
var menuTop:Number = menuButtons._height-Math.abs(menuButtons._y);
if (menuButtons._y<=0 && menuTop>=galleryMask._height) {
var targetPos:Number = menuButtons._y-galleryMask._height;
menuDown.enabled = false;
menuUp.enabled = false;
menuButtons.onEnterFrame = function():Void {
menuButtons._y += (targetPos-menuButtons._y)/menuSpeed;
if (menuButtons._y<=(targetPos+0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};
}
};

The first thing inside the event handler function is an if conditional statement which serves
only to activate the menuUp button. If you remember, the menuUp button is invisible in the
beginning, to avoid confusing the user. Once the menuDown button has been clicked, its
counterpart will appear and the if statement will never be used again, because the condition will
yield as false.

if (firstLook) {
menuUp._alpha = 100;
menuUp.enabled = true;
firstLook = false;
}

The condition if (firstLook) translates as if (firstLook == true). And when the


menuDown button has been clicked for the first time, this condition will yield as true,
because the value of the variable firstLook has been set as true at the very beginning of your
code (when all the variables were defined).

So, the code between the curly braces, { and }, will be run. It restores the button's alpha
(transparency) property to 100, meaning full opaqueness. After that, the button is enabled (it can
be clicked).
menuUp._alpha = 100;
menuUp.enabled = true;

After that, the variable firstLook is set to false and that's why the if statement will be ignored
every subsequent time that the menuDown button is clicked: the other button has appeared and
that's it.

firstLook = false;

Next, the menuTop variable is defined. Keep in mind that the menuButtons variable is the
shortcut for the buttonsHolder_mc movie clip, which is itself situated inside the
galleryMenu_mc movie clip. So, the menuButtons movie clip is the one into which all the
gallery section buttons were attached from the Library.

var menuTop:Number = menuButtons._height - Math.abs(menuButtons._y);

The value of the menuTop variable is the lowest point of your menu, all section buttons
included. I called it menuTop because the Y coordinate values increase when going down, that's
why. This value is obtained by substracting the absolute value (meaning the number itself,
whether positive or negative, it will be converted to a positive value) of the vertical position
(_y) of the menuButtons movie clip from its height. This value will be used to scroll the menu
(to move it) properly, without fear that it will disappear by going off the stage etc.

Next comes an if conditional statement that checks for two things:

 If the menuButtons vertical position is less than or equal to zero (menuButtons._y <= 0)
and
 If the value of menuTop is greater than or equal to the height of the galleryMask movie
clip, the one that serves as the mask for the menu buttons (menuTop >=
galleryMask._height).

if (menuButtons._y <= 0 && menuTop >= galleryMask._height) {

These two conditions ensure that:

 The menu can only be scrolled down if its position is lesser than or equal to zero.
 The menu won't be scrolled down if its lower (menuTop) edge's coordinate is lesser than
the lower edge of the mask.

So, if these conditions have been met, the menu will be scrolled down, thanks again to an
onEnterFrame event handler function and a few variables defined before it is executed. The
variable that gets defined is the following:

var targetPos:Number = menuButtons._y - galleryMask._height;


The targetPos variable is a reference point up to which the menu will be scrolled. Think of it as
an anchor towards which the menu is pulled. Its value is obtained by substracting the height of
the mask from the position of the menu buttons. It makes sense: you have to scroll your menu
by the height of its mask, so that each time the buttons below the current ones appear.

Next, both buttons that serve for scrolling the menu (menuDown and menuUp) are disabled just
before the scrolling begins. You don't want your menu to be moved up and down without control
— it is best to lock it until it has reached the targetPos coordinate.

menuDown.enabled = false;
menuUp.enabled = false;

And now comes the onEnterFrame event handler:

menuButtons.onEnterFrame = function():Void {
menuButtons._y += (targetPos-menuButtons._y)/menuSpeed;
if (menuButtons._y<=(targetPos+0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};

The code line that makes the menu move is the one that adds a value to the menuButtons' Y
coordinate each time the onEnterFrame event is fired:

menuButtons._y += (targetPos-menuButtons._y)/menuSpeed;

Remember that the addition assignment operator (+=) adds the value on its right side to the
cuurent value of the variable on its left side. And what's added is the result of substracting the
position of the menu section buttons from the target position point, divided by menu speed. As
the menu approaches the target position, the distance is smaller each time and there you have the
easing effect. Remember that the lower the value of menuSpeed, the quicker the menu will
move. I found 6 to be an optimal value in combination with the speed of the SWF, which was set
to 30 fps at the beginning.

And each time the menu approaches the target point, a check must be made to see if the point in
question has actually been reached. This is done through an if conditional statement, of course.

if (menuButtons._y <= (targetPos+0.8)) {

The if conditional checks if the menuButtons movie clip's vertical position is lesser than or
equal to (<=) the target position plus 0.8 pixels (targetPos+0.8). You have to make this so as a
safeguard against waiting too long for the menu to reach the target position. This easing method
is described in more detail in my sliding image mask tutorial, located on the following URL
http://flashexplained.com/actionscript/making-a-sliding-image-mask/

And, once that condition is fulfilled (meaning that the menu has reached the target position), its
position is fixed in place by setting it definitely to the rounded targetPos value. I recommend
that you always do that in cases like this, because objects placed on round pixels are rendered
much better than in other cases. Well, Flash 8 renders graphics greatly, but ensuring this with
round coordinates doesn't hurt.

menuButtons._y = Math.round(targetPos);

Then, of course, you should delete the onEnterFrame event handler, because it has fulfilled its
purpose and it is good to take load of the user's computer processor.

delete menuButtons.onEnterFrame;

After that, the buttons for scrolling the menu up and down are enabled again.

menuDown.enabled = true;
menuUp.enabled = true;

As for the onPress event handler function that serves to enable scrolling the menu up, the
differences are only in the conditions and some other details.

menuUp.onPress = function() {
var menuTop:Number = menuButtons._height-Math.abs(menuButtons._y);
if (menuButtons._y<0 && menuTop>0) {
var targetPos:Number = menuButtons._y+galleryMask._height;
menuDown.enabled = false;
menuUp.enabled = false;
menuButtons.onEnterFrame = function():Void {
menuButtons._y += (-menuButtons._y+targetPos)/menuSpeed;
if (menuButtons._y>=(targetPos-0.8)) {
menuButtons._y = Math.round(targetPos);
delete menuButtons.onEnterFrame;
menuDown.enabled = true;
menuUp.enabled = true;
}
};
}
};

The main if conditional statement checks if the position of menu buttons movie clip is lesser
than zero and if the lower edge point of the menu buttons movie clip is greater than zero. This
time, the target position is determined by adding the height of the mask to the menuButtons'
current position.

Conclusion
Congratulations on going through to the end of this tutorial and learning very much about
ActionScript! I am glad that you have followed me until the end. There are some things I want to
tell you.

First, this gallery is modular, expandable and pretty powerful. Of course, it could have been done
in many other ways: having many thumbnails in each section instead of a maximum of 20,
scrolling thorough thumbnails etc. But that would be another gallery.

The main purpose of my tutorial is to teach you to build a powerful dynamic image gallery by
combining ActionScript and XML so that you can also build other galleries, which will have
different interfaces and menus. I wanted you to show how to handle the main elements of such
image galleries: XML, preloading, navigation, visual effects, etc. I hope that you have learned
much and that you will use the knowledge in other galleries and create cool Flash websites.

Note also that if you are going to have many, many images (let's say, about 100 sections), the
XML file is going to be heavy. In that case, you will need to preload the XML too, using the
XML object's getBytesLoaded and getBytesTotal methods. Also, note that in this tutorial's code I
have limited the number of pictures to 1000. This is more than enough for any practical
purposes. If you need even more than that, just change the if/else if/else statement inside the
enableButtons function.

S-ar putea să vă placă și