making the ultimate dynamic image gallery in flash 8

78
Making the ultimate dynamic image gallery in Flash 8 November 20th, 2008 | Author: Luka | Category: ActionScript In this Flash 8 lesson explained in extreme detail, I will teach you how to make a powerful image gallery. Before proceeding, please note that this lesson is made for intermediate and advanced Flash users — the ActionScript code behind this image gallery is nearly 250 lines long. This image gallery will have the following characteristics: It will be dynamic, meaning that the image-related data (the location of images — the file paths, and the descriptions ) will be loaded from an external XML file.  The dynamic nature of the gallery will allow you to update it just by changing the external XML file and re-upload it to the server along with the new images, without having to modify the SWF movie at all. Once the SWF is finished and ready, you don’t have to touch it any more.  The gallery can feature an unlimited number of images.  The image gallery will feature a menu which will enable the users to select a particular section and have the related thumbnails displayed. The menu will be created dynamically (on the fly) via ActionScr ipt, making it expandable. It can store as many sections as you like.  The menu will be scrollable, with a nice easing effect added to it. Every thumbnail section and every individual image will have its own textual description . Every thumbnail will have its own preloader, as well as every image. Once a user clicks on a thumbnail, the external JPEG image will be loaded (a percentage preloader will be used to show the downloading progress ), and once it is fully loaded, it will show up with an alpha fade-in effect. By clicking on the loaded image, the user will go back to the thumbnail section.  The image gallery is extremely small in filesize (the SWF itself weighs less than 30 KB), because all the JPEG images will be stored externally. Last but not least, the gallery works in all major browsers. View the image gallery in action. You can also click o n the screenshot below to see it.

Upload: rmyroslina

Post on 07-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 1/78

Making the ultimate dynamic image gallery in Flash 8

November 20th, 2008 | Author: Luka | Category: ActionScript 

In this Flash 8 lesson explained in extreme detail, I will teach you how to make a powerful

image gallery. Before proceeding, please note that this lesson is made for intermediate andadvanced Flash users — the ActionScript code behind this image gallery is nearly 250 lineslong. This image gallery will have the following characteristics:

• It will be dynamic, meaning that the image-related data (the location of images — the file paths, and the descriptions) will be loaded from anexternal XML file.

•  The dynamic nature of the gallery will allow you to update it just bychanging the external XML file and re-upload it to the server along withthe new images, without having to modify the SWF movie at all. Once theSWF is finished and ready, you don’t have to touch it any more.

•  The gallery can feature an unlimited number of images.

•  The image gallery will feature a menu which will enable the users to select aparticular section and have the related thumbnails displayed.

• The menu will be created dynamically (on the fly) via ActionScript,making it expandable. It can store as many sections as you like.

•  The menu will be scrollable, with a nice easing effect added to it.

• Every thumbnail section and every individual image will have its own textualdescription.

• Every thumbnail will have its own preloader, as well as every image.

• Once a user clicks on a thumbnail, the external JPEG image will be loaded(a percentage preloader will be used to show the downloading progress), andonce it is fully loaded, it will show up with an alpha fade-in effect.

• By clicking on the loaded image, the user will go back to the thumbnailsection.

•  The image gallery is extremely small in filesize (the SWF itself weighs lessthan 30 KB), because all the JPEG images will be stored externally.

• Last but not least, the gallery works in all major browsers.

View the image gallery in action. You can also click on the screenshot below to see it.

Page 2: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 2/78

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 browsethrough the galleries. It will be made of buttons dynamically pulled out fromthe Library and then nested inside an empty movie clip. The menu will havetwo buttons, which will make possible for the user to scroll through themenu, up and down. A mask will be made inside this menu, to limit itsvisible area. You must do this because if you are going to have manygalleries (let’s say 40, 50 or even more), their respective buttons cannot beall over your movie — that would look bad.

2. The thumbnail MovieClip. This is a movieclip symbol stored inside theLibrary, into which a single thumbnail (small image) will be loaded. Itcontains:

○ a white background, just to make it nicer, and to be able to add a drop

shadow effect to it later,

○ an empty MovieClip inside which the external JPEG thumbnail will be

loaded and

○ 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 storedin the Library and will be pulled out of it dynamically, via ActionScript. It isnearly the same as the thumbnail MovieClip, except bigger in size. It containsthe same three elements as the one above:

○ a white background,

○ an empty MovieClip inside which the big external JPEG image will be

loaded and

○ a dynamic text field for the preloader.

Page 3: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 3/78

4. A placeholder for thumbnails and big images. This is an emptyMovieClip, placed directly on the stage, which will have two empty MovieClipscreated inside it at runtime (meaning while your SWF is running), like this:

○ 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, dependingon the number of images in the gallery that the user has selected.

○ When the user clicks on a thumbnail, a new empty MovieClip will be

created inside the placeholder, which will have the big image holderMovieClip attached to it. The preloading of the big JPEG image willstart, and when it reaches 100%, the image will fade in nicely and hidethe thumbnails. When the user click on the image, it will disappear andthe thumbnails will appear again.

5. A dynamic text field. This is where the descriptions for all the galleriesand 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 eachgallery button in the menu. Also, this same name is the name of thefolder (directory, file folder, as it is also called) inside which that particulargallery will be stored on your web server.

• The description of each gallery. This is the text that will appear in thedynamic text field when the user clicks on a gallery button and thethumbnails for it are shown.

• The description of each image. This is the text that will show up in thesame 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 namingrules. Each gallery will be placed in a folder which will have the same name as the title of thegallery as it appears in the XML file. Inside each folder, the images will have to be named as1.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 thesame file names as their bigger counterparts (1.jpg , 2.jpg , etc). All the galleries will be placed ina single folder, named gallery.

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

Page 4: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 4/78

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

1. Setting up your document1.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 pixelsand 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 lotof files are going to be needed for the creation of the image gallery, so it is a wise thing to keepthem all in one place, instead of putting them together with any other Flash files that you may beworking on.

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, mainimages, thumbnails, etc) involved in this lesson. I recommend that you use my dimensions untilthe end of the tutorial, so that you can more easily follow my instructions. Later, once that yougrasp the way the gallery works, you can change the dimensions and the general layout of thegallery to suit your needs.

Top of page

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 .

Page 5: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 5/78

2.3 You will now find yourself working inside the new MovieClip symbol. Since you need anempty 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 theLibrary by selecting Window > Library. Keep the Library window open, because you are goingto need it frequently, especially to place instances of the empty movie clip symbol on the stage atvarious points during this lesson.

 Now you are going to create the main MovieClip for the image gallery menu. The first thing thatyou’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 strokecolor, because you won’t need it. Do this by selecting the stroke color first — click on the littlepencil icon to do it (see 1 in the image below). Next, click on the No color button (see 2 in theimage 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).

Page 6: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 6/78

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 theProperty 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 thefollowing 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 aregoing 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 anduse the width and height for each symbol to be able to position them properly. By selecting theupper 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 Selectiontool) to enter inside it. If you take a look above the stage, you’ll see that Flash nicely informs youthat you are working inside the menu holder MovieClip now.

Page 7: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 7/78

2.9 The rectangle vector shape inside the movie clip should be selected by default. If this isn’tthe 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 theupper 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 thisMovieClip: 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 clipsymbol 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 clipfrom the Library onto the stage. If ever in doubt which movie clip you are tinkering with, justlook 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).

Page 8: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 8/78

The empty movie clip will now be perfectly aligned with the menu holder movie clip’sregistration point, as you can see.

This is just what you need, since this empty movie clip which you have just positioned will bethe placeholder for all the menu buttons. That being said, you must prepare it properly to be ableto 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 theInstance 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 (alsocalled 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 Propertyinspector. Go right there and give at an Instance name: call it galleryMenu_mc.

Page 9: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 9/78

You have probably noticed that this movie clip is almost invisible — it is represented by itsregistration point (see1 in the screenshot below) and central point (see 2) only. This is becausethe 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 actuallymake a button that is going to be pulled out of the Library at runtime (while the Flash SWFmovie is running, that is) and placed inside the menu, as many times as there will be sectionsinside your gallery.

Top of page

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 newlayer. You don’t have to gave any specific name to this new layer at all, because it will serve asa 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 unchangedfrom the previous use of it: the stroke color (outline) should be blocked, the Object Drawing andSnap 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 a200 by 20 pixel rectangle anywhere on the stage. You can draw any rectangle at first and thenset these exact dimensions in the Property inspector after.

These exact dimensions are important, especially the width, because the mask that you made inthe previous section is also 200 pixels wide. They have to match (or the mask can eventually be a

Page 10: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 10/78

little wider than the button) if you want your menu to look professionally designed — clean andsharp.

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 factserve as a button. Why a movie clip then? Because a movie clip symbol is far more versatile andusable 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 aswell as a movie clip for all purposes, I have just acquired a habit of making movie clips insteadof buttons :-).

3.4 Choose the Selection tool (V) and double-click on the gallery section button movie clip onthe 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 itscolor to some other of your choice — I used #7C3F52. Do this by clicking on the fill colorsquare 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 moreuser-friendly and easier to navigate. So that’s why you have to have two keyframes, with thesame rectangle inside, but differently colored. You will enable this rollover visual change viaActionScript later.

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

Page 11: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 11/78

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’sheight should approximately match the height of the rectangular background. You’ll seethat once you make the actual text field, so you may need to re-adjust this value asnecessary.

4. Select white for the text color — this choice will make the button labels visible in bothstates — initial and rollover.

5. Select the left alignment for the text field. It looks well, unlike the central alignmentwhich would look awkward on this kind of menu and would also make things moredifficult 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 fieldinside 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. HitEsc 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 dynamictext field: call it sectionTitle_txt .

Page 12: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 12/78

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 accrossdifferent platforms and operating systems. No matter if a user has your menu font of choiceinstalled 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 andexotic characters if you wish so. Bear in mind that the embedding of these characters will addabout 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 insideit:

stop();

Page 13: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 13/78

This simple action prevents the playhead from going forward, as any animation in Flashnaturally does. You will create programming code later that will move the playhead to the nextframe while the user is over a particular button with his/her mouse, to create the rollover effect Itold 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 deletethe button from the stage too. You should have only the gallery menu layer on the main scenenow. 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 ActionScriptoption. The Export in first frame option will automatically become checked too. You can leaveit like that, it’s fine.

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

Page 14: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 14/78

The Identifier name will serve to pull the button dynamically from the Library and place it insidethe menu that you have created on the previous page. This is very, very practical, because youwill 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. Whycreate every single button manually, re-open the FLA, re-export it as a SWF when you can solvethis 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 userswhat’s the menu about. Before that, you’ll just position the galleryMenu_mc movie clip.

Save your document before proceeding to the next section of this lesson, where the creation of menu navigation buttons is explained.

Top of page

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 movieclip is almost invisible, it isn’t as easily selectable as any othe movie clip might be. Here’s howyou 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, themovie clip you are looking for will appear. Click on the movie clip once with theSelection 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.

Page 15: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 15/78

4.2 Enter the following values for the movie clip’s coordinates (inside the Property inspector): 10for 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 theLine tool (N). In the Property inspector, select black for the line color and hairline for the linethickness.

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 thescreenshot below).

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

Page 16: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 16/78

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-turquoiselinear 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 itscode.

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 tosee 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!

Page 17: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 17/78

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, selectButton 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 itand 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 rightcorner. 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 thecenter, 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.

Page 18: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 18/78

 Note that I have used the blue color just to show you how it’s done. You can use any color youwant while making the triangle — once you move it over the button’s background, change itscolor 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 Propertyinspector. 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, besure 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 Actioncriptlater. Name it menuDown_btn.

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

Page 19: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 19/78

 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 selectDuplicate 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 accesits timeline. Once inside, unlock the arrow layer.

4.19 Select the triangular arrow shape in this layer. Now select Modify > Transform > FlipVertical. The arrow will now point upwards, thanks to the flipping you did. Also, Change thestatic 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 anyother 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 themain one.

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

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

Page 20: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 20/78

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.

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

4.24 Lock the gallery menu layer.

That’s it for the menu! You have completed it.

Top of page

5. Creating the image placeholders5.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. Asthis movie clip is completely devoid of any graphical content, it is shown as a registration pointonly.

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 ideaabout the gallery’s layout, but I arrived at this final dimensions and positions through the

Page 21: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 21/78

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 theelements: the menu doesn’t necessarily have to be on the left, vertically positioned, etc. I justmade 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 Libraryto 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 88×61 pixel rectangle on the stage. This will be the background for gallerythumbnails 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 appropriatedimensions 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 88×61 pixels, I decided to make my thumbnails 81×54pixels.

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 .

Page 22: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 22/78

5.8 Click and drag out and instance of the empty movie clip from the Library and into theimage 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 (itsregistration 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 isa 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 beforeeverything 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 samehere.

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.

Page 23: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 23/78

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 textfield 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 fieldis 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 .

Page 24: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 24/78

Having the characters of the specific font you selected embedded inside your text field assuresthe 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 itand select the Linkage option. Check the Export for ActionScript option (this is what enablesyou to pull out the movie clip from the Library dynamically). The Export in first frame optionwill 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 holderfor the images — the big ones that will be loaded as a user clicks on a thumbnail. You willfollow the same procedure as you did for the thumbnail holder movie clip.

5.15 Select the Rectangle tool (R). Draw a 475×317 pixel rectangle using the same options thatyou did in step 5.4.

Page 25: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 25/78

5.16 Select the rectangle (both its fill and outline) and press F8 (or select Modify > Convert toSymbol) 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 firstlayer 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 intothe new layer (image holder ) that you made in the previous step. Make the followingadjustements:

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 ared arrow in the screenshot below so that you can more easily see it.

Page 26: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 26/78

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 theregistration point of empty movie clip. You could reposition it later with ActionScript if youwant, 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 dynamictext 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., changeonly 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 thetext 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.

Page 27: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 27/78

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 youdid 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 onthe 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 selectLinkage from the context menu. Click the Export for ActionScript option to check it, leave theIdentifier as big image holder and click OK .

Save your work now if you haven’t already done so! Make this a habit, but especially in long projects like this one. Proceed to the next section to see how to create a text field where galleryand image descriptions will appear.

Top of page

6. Creating a text field for gallery and image descriptions6.1 You should be on the main scene (timeline) now. Call the current layer (the one which youused to create the image placeholders) description text .

Page 28: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 28/78

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 thewhite background and make the text easy to read.

5. Select left alignment. You may also select the Justify option. Avoid right or centralalignment - 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 fieldediting mode. Your text field’s dimensions should be about 475×100 pixels. Also, pay attentionto its position: try to align it with the image placeholder and think about how much space willtake an image once it’s loaded. In the screenshot below you can see the position and dimensionsof the text field.

Page 29: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 29/78

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 init and have nice, readable descriptions which are going to be nicely rendered: select the BasicLatin 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 youlike, but I recommend that you follow my proposals here, just to be able to follow this tutorialmore 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 thefill color of the lower part.

Page 30: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 30/78

7.3 Select the Text tool (T) and switch the type of the text field to Static text. Click and typeanything 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 .

I didn’t make separate layers for the background rectangle and the text inside the logo movieclip, but just selected the whole thing and made a movie clip symbol out of it. It is usuallyrecommended to make separate layers for different elements inside a symbol, but logos aren’tsupposed 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, youshould 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 theProperty inspector and assign it an Instance name: call it logo_mc. Also, you can set both of itscoordinates to 10.

Page 31: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 31/78

You could have left the logo as it is without having to convert it into a movie clip symbol. Buthaving a movie clip enables you to position it via ActionScript later if needed — you won’t needto 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 filewhere all the gallery data will be stored, some images and an exact folder hierarchy. So let meshow 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 Flashhere, 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 XMLand 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 displayedthe 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, townsand 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>

Page 32: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 32/78

</gallery></galleries>

After the XML declaration comes the root node, of course. I chose to call it galleries. Withinthis, 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 nodesthe same name (gallery) on purpose. You will see later why (when I’ll explain theActionScript code) — this is related to parsing the XML data.

<gallery title="architecture" intro="These are the photos of various buildings in the cities, townsand 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 theuser what’s the gallery about. Remember, you may call your attributes any way you like, as longas 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 abutton 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 afolder must be exactly the same as the value of the title attribute for a particular gallery. If, as inthe 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 thethumbnails when the user clicks on any of the gallery buttons inside the menu. Once he choosesa 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 foldersand galleries. It just describes a particular gallery.

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

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

Page 33: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 33/78

Between the opening and closing tags of each image node, there is a child node, which is in factthe 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.

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 correspondsto a gallery).

And that would be it concerning the XML file.

Top of page

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 thatmake up your gallery will be stored (SWF, HTML, XML, images). For the sake of simplicity, Ichose to call this folder root.

As you can see in the screenshot below, both the SWF file (the one you are learning to create inthis lesson) and the HTML page inside which it will be embedded should be placed inside thismain (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 asyou like. It is the gallery folder that must have that exact name, because you will be using it inActionScript later.

Of course, you can choose other file/folder placements, but I strongly recommend that youfollow 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 mosteasiest 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 imagegallery, which will correspond to the menu buttons.

Page 34: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 34/78

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

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 oncethese 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 thebig 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 shouldrename 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 — thethumbnails, 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 eachgallery:

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 .

Page 35: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 35/78

In this project, the number of thumbnails for each section is limited to 20. It was my choice tomake it this way, based on the gallery’s overall layout and concept. You can increase thisnumber if you want, but then you’ll need to rearrange your gallery elements’ position anddimensions to accomodate a higher number of thumbnails. I recommend that you stick with myconcept until the end of this tutorial and then experiment later. Of you do need more thumbnailsfor 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 469×311 pixels.The thumbnails should be made to be 81×54 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. And post a comment with a link to it, I’d love to see it!

Page 36: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 36/78

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

Top of page

10. Inserting the ActionScript code

10.1 Go back to your document. Lock the actions layer and click on its first keyframe to selectit. As you may already know, a layer does not have to be unlocked for you to be able to insertActionScript code inside it. In fact, I always lock the layer where my code is contained, tominimize errors — not to insert any graphics in it by mistake.

If possible, always place all of your ActionScript code into one layer, and also, into as fewkeyframes as you can. The layer which contains your ActionScript code should be madeexclusively 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 sothat 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;

Page 37: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 37/78

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 canclick 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 tothe 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) {

Page 38: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 38/78

 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());

Page 39: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 39/78

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];}

Page 40: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 40/78

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 {

Page 41: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 41/78

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;}};}};}

Yep, this a really big piece of ActionScript code! More than 230 lines of it! Now save yourwork and go onto the next section to see how to test your SWF movie and to understand all this programming code.

Top of page

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, andthen 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, selectView > Download Settings > 56K and after that View > Simulate Download.

Page 42: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 42/78

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, Imean the one for the images, because this gallery hasn’t got its own, main preloader — it’s easyto create one, if you want to know how, just check out my  preloader tutorials. I won’t delve intothat 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 downloadsetting for one of the slowest connections — a plain 56K modem.

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

Top of page12. The ActionScript code behind the image gallery explained

I will explain you the ActionScript programming code by section, for easier understanding. Thecode 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○ Retrieving gallery data (titles and descriptions)

○ Creating menu section buttons dynamically

6. Defining the functionality of the menu section buttons

○ Enabling the display of the roll over and roll out states

○ Defining which thumbnails shall be loaded

Page 43: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 43/78

7. Thumbnail positioning and thumbnail preloading

8. Defining the functionality of the thumbnails

○ Big image preloading

○ Disabling the thumbnails while the big image is preloading

○ 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 movieclips, 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 movieclip’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 knowswhat 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 variablewhich 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 valuewill 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 madeinvisible by turning its _alpha (transparency) property to 0 (zero) and then disabled by settingits enabled property to false.

Page 44: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 44/78

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

 button.

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, wherenavigation is reduced to textual or image links. Flash offers basically infinite possibilities tocreate rich, interactive experiences, and that’s why you must be careful: Don’t let yourself beseduced by the vast array of eye-candy gizmos that can be made — always keep the user inmind! 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 goa long way towards improving the user experience. I always test my projects before going live. Isuggest 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 Movieclip class. This value is expressed in pixels. I have set it to 391 pixels, because I have found thatthis value is fine for showing up a certain number of gallery section buttons. It just looked goodto 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 itsdimensions via ActionScript — there is no need for you to go back inside the gallery menumovie clip each time that you want to change it, select the mask, resize it manually, etc. WithActionScript, 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 manyvalues, be those values of the Number type, String (text) type or something else. Think of themas of filing cabinets, where each drawer contains a value. They are perfect for storing manyvalues, 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 eachgallery section.

• The galleryNames array will keep the names (titles) of the sections of your imagegallery. If you recall, these are the names of the folders of different gallery sections,

Page 45: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 45/78

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 arethe 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 isexplained later.

The tracker variable is of the Number type (which means it stores numerical values) and it willserve to keep track of the number of thumbnails when user has clicked on a gallery section andwill 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). Thisvariable’s value will serve to tell Flash if the image that is being loaded is a thumbnail or a bigimage 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 determinesthe vertical space between each of the section buttons inside the gallery menu. If youremember, 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 spacingbetween 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 galleryloads and there hasn’t been any interaction with it yet from the user. You must give your userssome 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 canclick 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 tothe gallery. Use the button(s) above the galleries to scroll through them.";

Page 46: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 46/78

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

Top of page

12.2 Importing the DropShadow filter

I decided to apply the DropShadow filter to the thumbnails to make them even nicer. The firstthing that you must do before applying a filter to an object inside Flash is to import it. When youdo this, Flash reads from your disk (specifically, from a folder within the Flash installation) andinserts all the needed code for a particular filter into your SWF movie. Then it can be used andapplied, 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 theshadowEffect variable which contains the filter to the thumbsFilter array, which will then beapplied to the thumbnails.

var thumbsFilter:Array = [shadowEffect];

For a more detailed explanation of how a filter in Flash works and why you need to create anarray that will contain it, check out my tutorial on the use of the blur filter in Flash.

12.3 Creation of the MovieClipLoader and Listener objects and the functions that enablepreloading

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 specificallymade for external content loading. It is great and you will use it to load and preload both thethumbnails 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. Ichose to call the variable which will contain it loader.

var loader:MovieClipLoader = new MovieClipLoader();

1. 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 doingand will react when things start happening: for example, when the loading is started bythe MovieClipLoader or is in progress, the listener is aware of that and reacts by runningspecific functions (which will, for example, tell Flash how much has been loaded, etc). I

called the listener object myListener.

var myListener:Object = new Object();

1. And to have the MovieClipLoader and the listener work together nicely, you mustassociate the listener object to the MovieClipLoader, like this, using the addListener

method:

loader.addListener(myListener);

Page 47: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 47/78

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

• One that will tell Flash what to do while an image is being loaded (calledonLoadProgress),

• And the other that will tell it what to do once the loading is complete (calledonLoadInit).

I repeat, these functions must be created before any loading begins. Flash must know what to doin advance! On a sideline note, this method of preloading is also explained extensively in mymenu preloader system tutorial. Let me show you now how have I set up the listener object’sonLoadInit() 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 aSWF, 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 externalimage will be loaded.

myListener.onLoadInit = function(target:MovieClip) {

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

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

Page 48: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 48/78

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 todecide 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, oncethe loading of an external JPEG image has been triggered, the value of the whatIsLoadingvariable 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. Itis 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 loadedthumbnail is hidden by setting its _visible property to false (remember, this is the textfield that you created earlier in this tutorial, where the percentage preloader will show upduring 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 definewhat 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’swhat the two plus signs (++) stand for. Remember, this variable is used to let Flash knowwhich 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:

Page 49: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 49/78

• if the value of tracker variable is lesser than the value of howManyImages variable, theloadThumbnail() 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 thanhowManyImages‘ value), then the thumbnails will be enabled. This means that they will be clickable.

The above means the following: tracker keeps track of the number of thumbnails in the currentgallery section (the one that the user chose to see). The variable howManyImages holds thenumber of images that exist in the chosen gallery section. So, if the current thumbnail isn’t thelast one — meaning if there are more to be loaded — more will be loaded.

And when all the thumbnails have been loaded, they are all enabled. This means that the userisn’t able to click on any of the thumbnails until all of them have been completely loaded. Imade this to be so because I like it like that and also because I don’t have to deal with additionalinteraction stuff which I’d have to, if I hadn’t done this.

And now, what happens when the value of the whatIsLoading variable has been set to “big”? Aslightly different thing:

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 havechosen to do this to be able to apply the nice fade-in effect to the big image later :). Whymake 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 imageholder is made invisible (_visible = false), because the percentage preloader needsto 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’llsee later. This makes possible for the user to click the big image, and once that has beendone, 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, frominvisibility 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;

Page 50: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 50/78

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 beenloaded so far (loaded/total*100) which is then rounded to the nearest lower value with thefloor() 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 theinformation on how much of the image has been loaded so far is displayed, using the percentvariable 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 MovieClipLoaderobject and its associated listener object have to be defined before you actually proceed toload the external JPEG images.

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

Top of page

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 beenfinished, 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) {

Page 51: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 51/78

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 theXML 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 theactual 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 typeof value, which means that it equals either true or false. It yields as true if the XML dataloading was performed successfully and false if it was not.

Inisde the function, there is a simple if/else conditional logic used to help Flash decide whatto 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 (invokedmeans 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 theimage 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.";

Page 52: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 52/78

The above text is what will appear in the big dynamic text field. Basically, I don’t know whatelse can be done if the loading process fails. The user can try to reload the page, but most likelyhe or she will just close the page with the image gallery and move. If you have created a goodXML file and tested your SWF and seen that it works online with no problems, there is not muchthat you can do if now and then some user can’t see the gallery because the XML data failed toload. That is beyond your power: maybe the server where you host your image gallery wentdown 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 loadit! 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 problemstoo! If you change the folder inside which your XML file resides or the name of the XML fileitself, you must change it in the above line of code too!

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. TheHTML page is what’s important!

In the next step, I will show you how the parsing of XML data is done.

12.5 Parsing XML: Retrieving gallery data (titles and descriptions) and creating the menusection 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, buteverything inside it is perfectly logical and understandable and I will explain it to you in no timeat 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);

Page 53: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 53/78

}}}}}numberOfGalleries = i;enableButtons(numberOfGalleries);}

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

function parseGalleries():Void {

This keyword tells Flash that the parseGalleries() function does not return a value. It isgood to specify this, although it isn’t obligatory. When you have a function that does return avalue to the caller, you have to specify this. For example, you may have a function which servesto 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 sayimageGallery.firstChild.nodeName, you tell Flash to look up the name of the root node — itis 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 codeto 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 really loops through all the child nodes of the root node, you set thecondition 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?

Page 54: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 54/78

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 fromzero. It is just how it’s done in ActionScript and the majority of programming languages.

What follows is an if conditional statement, again. Exactly like for the root node, you tell Flashhere 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, townsand 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… soall 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 beloaded for a given gallery section.

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

galleryNames.push(currentGallery.attributes.title);

Using the same procedure as above, the value of the intro attribute is extracted and storedinside the galleryIntros array. These values will be used to show what’s the current gallerysection about — this is the description text which will appear in the big dynamic text field oncethe 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 attributeof the current gallery section is extracted and stored inside the currentGalleryTitle variable.

Page 55: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 55/78

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 usedvery soon.

currentGalleryTitle = rootNode.childNodes[i].attributes.title;

And now, the gallery section button movie clip is being extracted from the Library dynamicallyand 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 theLibrary: “gallery section button” in this case.

2. The new instance name of the newly attached movie clip. This will be different for eachgallery 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 willreplace the previous one, because there cannot be two movie clips present on a samedepth level. So, the convenient getNextHighestDepth() method is used to place eachmovie clip on a separate depth level. Think of the depth levels as invisible layers insidethe empty movie clip where you are attaching your buttons.

And the currentGalleryButton variable is used as a shortcut for this newly attached movieclip — 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 movieclip _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 bealigned flawlessly inside the menu.

Page 56: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 56/78

On the other side, the vertical position of each section button inside the gallery menu isdetermined dynamically, because you have to put some space between them:galleryBtnVSpace*i. If you remember, when you defined all the variables, thegalleryBtnVSpace was set to the value of 23. Like I said, I chose this value in relation to theheight of the buttons, to be able to space them nicely. Since in every loop iteration this value ismultiplied 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 firstlabel 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 lowercaseletters: 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 gallerynode:

for (j=0; j<currentGallery.childNodes.length; j++) {if (currentGallery.childNodes[j].nodeName == "image") {currentDescription = currentGallery.childNodes[j].firstChild.toString();descriptions.push(currentDescription);

Page 57: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 57/78

}}

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" andnot 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, townsand 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 nodeabove 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 mismatcherror. Yes, the text between the <image> opening and closing tag is considered the image node’sfirst child.

And the text (which is the description of each particular image) is then stored inside thedescriptions 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 numberOfGalleriesvariable.

numberOfGalleries = i;

This number will be used later to determine the number of gallery section buttons and loopthrough all of them.

Page 58: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 58/78

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! Cool! Jump to the next step to seehow the functionality of the gallery menu section buttons is created.

Top of page

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

Here’s the enableButtons() function which has numberOfGalleries passed as a parameter toit (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 andonPress event handler functions.

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

 Now you see how important the numberOfGalleries variable is — without it, you wouldn’t beable 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 toeach button in your gallery menu as the loop progresses: pressedButton.

Page 59: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 59/78

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

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

 Now comes the definition of the onRollOver event handler function, which gets executed whenthe 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, toaccentuate the rollover effect.

After that, the rollOut event handler function is defined, which gets run once the mouse hasbeen 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);};

In both event handler functions, the keyword this points to the gallery section button movie clipitself, because it is contained inside the functions (inside the curly braces). Thanks to this, thereis 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 eventhas been fired and its event handler function executed.

And now, a very important event handler function comes up: onPress, which governs whatactions 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.

Page 60: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 60/78

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 willhappen. 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 thecreateEmptyMovieClip() method. It will hold all the thumbnails of the gallery section thatwas 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. Youcould have created this latter one dynamically via ActionScript too, but I wanted things to be alittle 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, Flashautomatically 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 newempty movie clip is being created.

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

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

Page 61: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 61/78

The substr() method of the String object is used to do the extraction, since the instance nameof the movie clip is a string (text) value. It goes on like this: suppose that the user clicked on thefourth gallery section button (which is the monochrome section in my gallery example). Theinstance name of the clicked movie clip will be galleryButton3. Yes, there is the number 3 at theend of the instance name, because, as you remember, in the for loop which is used to createthese 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 firstcharacter 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 theend 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 thestring from that point on.

After the extraction has been done, the result is converted to a mathematical value from aplain 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 samemanner, 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 firstvalue inside an array in ActionScript has the position 0. The image below explains this nicely.

Page 62: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 62/78

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

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

currentRow = 0;

currentColumn = 0;

Then the loadThumbnail() function is invoked, which will load the thumbnails for the chosengallery 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 gallerysection 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 menuvia the two buttons (up and down). This function will be defined at the end of all the gallery’scode.

Let me explain you now what happens when a gallery section button has been clicked and thethumbnails 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 attachthe thumbnail holders, place them in an orderly fashion and trigger the preloading, so that theuser 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";

Page 63: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 63/78

loader.loadClip(thumbPath, target);}

The first action inside the function is the process of attaching a thumbnail holder movie clipfrom the Library, to the thumbsDisplayer empty movie clip. This is done with theattachMovie() 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 theInstance names will be thumbnail1, thumbnail2, thumbnail3… and so on, untilthumbnail20. Remember, I created the gallery so that each section can have a maximumof 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 ineach 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 beloaded into. As you can see in the line of ActionScript code below, it is being loaded inside thethumbImage_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, 5thumbnails 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 themodulo 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 safeguardthat 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:

Page 64: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 64/78

(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 secondcondition is false. It says that zero does not equal (!=) zero, which is false. And when just onecondition 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 != 03 == 0 && 3 != 0

This time, it is the first condition that yields as false (it says that 3 equals 0, which is false) andso 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 thesubsequent five thumbnails into the next row.

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

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 justexplained 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 verticallyon 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

Page 65: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 65/78

between the thumbnails. You defined them at the beginning of your code, remember? They areset to 96 and 68, respectively. This is the value of space between the thumbnails expressed inpixels.

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 isa 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, allthe characters from the exatraction point up to the end of the string will be extracted. Why dothis? Because like that, you will be able to extract the number of the thumbnail, whether it is aone 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 whichneeds 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 HTMLpage inside which your image gallery SWF is embedded.

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

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

Page 66: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 66/78

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 currentthumbnail:

loader.loadClip(thumbPath, target);

The first parameter inside the parenthesis is the external file that is going to be loaded (a JPEGthumbnail in this case). The second parameter is the target empty movie clip into which theexternal file will be loaded.

And now that the loadClip() method has been invoked, the MovieClipLoader and its associatedlistener will start working together and preload the image and display it, with the DropShadowfilter applied to it. You can read again (I recommend it, it will be much more clear to you now)how this is done in the section which explains the use of the onLoadInit() and onLoadProgress()methods.

 Now you know how the placement and preloading of thumbnails is done! What follows is the

explanation of how the functionality of the thumbnails is defined.

Top of page

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;

Page 67: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 67/78

};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 theimagesHolder 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 loadingthe 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 rightimage. 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 processand also while the big image is being displayed. They will be re-enabled only once the user hasclicked on the big image and it has disappeared, showing the thumbnails again. This is donethrough 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);

Page 68: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 68/78

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

The next chunk of code is the one where the description for the selected big image is beingsearched 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, thisconditional 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 theselected 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 thenumber 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 belesser 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 theequation’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 valuesout of the imagesInGallery array. All this is done in order for Flash to be able to find anddisplay 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 gallerysection is in rollover state, just for the purpose of showing it here). The text for this image should be “Empty silos.”

Page 69: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 69/78

Since the user has clicked the third gallery, the value of clickedGallery is 2, because they startfrom 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 storesvalues which correspond to the number of images in each gallery section. In my example, theyare 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 toarrive 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 hasarrived at the third gallery section, but now it must find the description inside this particularsection. 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.

Page 70: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 70/78

Then, one is substracted from it, since I chose to give the thumbnails (and subsequently, the bigimages 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 thedescriptions array, placed at number 16, because the counting inside an array starts from 0. Inthis 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. Andthat’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 outsidethis 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. Andhere come now the two functions that disable and enable the clickability of the thumbnails.

Top of page

The first one, disableThumbs() serves to turn off the clickability of the thumbnails. Thisfunction 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 manytimes as there are thumbnails in the selected gallery section (i < howManyImages). Then, theyare disabled one by one via turning their enabled property to false. Each thumbnail is accessedthrough the expression thumbsDisplayer["thumbnail"+(i+1)] . Why i+1? Well, again, Irepeat, 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 theexact same way, the only difference being the enabled property turned to true this time. Thisfunction is invoked either when the user clicks on a gallery section button in the menu and all thethumbnails have been successfully loaded or when the big image was clicked, closed and thethumbnails for the selected section have appeared again.

function enableThumbs():Void {for (i=0; i<howManyImages; i++) {

Page 71: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 71/78

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 isthe 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 clickableagain, since the big image has been removed and they can be seen again. You probably noticedthat I never made any code that would hide the thumbnails, because the big image effectivelycovers 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.

Top of page

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;}

Page 72: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 72/78

};}

This function consists of an onEnterFrame movie clip event handler. This particular movie clipevent is used very often because it makes possible for actions to be performed repeatedly. To bemore 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 afade-in effect!

What happens inside is that the _alpha property (transparency) of the target movie clip, intowhich 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 theloaded 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 movieclip, 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.

And now, the gallery menu scrolling functionality with easing effect is explained. Yes, you arenearing the end of this tutorial :-)!

Top of page

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 whenthere 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 buttonwhen it appears!

Page 73: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 73/78

The big function that follows, enableGalleryNavigation(), is made of two main parts: thedefinitions 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)) {

Page 74: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 74/78

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 goingon inside the function, keep in mind the following facts:

1. In Flash coordinate system, the vertical direction (Y) is positive downwards. This meansthe further you go down from the origin point, the bigger the positive value of an object’sY coordinate.

2. Each movie clip has its own independent coordinate system. The origin of this coordinatesystem 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)) {

Page 75: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 75/78

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, itscounterpart will appear and the if statement will never be used again, because the condition willyield 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 beignored every subsequent time that the menuDown button is clicked: the other button hasappeared and that’s it.

firstLook = false;

 Next, the menuTop variable is defined. Keep in mind that the menuButtons variable is theshortcut for the buttonsHolder_mc movie clip, which is itself situated inside thegalleryMenu_mc movie clip. So, the menuButtons movie clip is the one into which all thegallery 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 buttonsincluded. I called it menuTop because the Y coordinate values increase when going down, that’swhy. 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:

Page 76: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 76/78

• 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 movieclip, 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 thanthe lower edge of the mask.

So, if these conditions have been met, the menu will be scrolled down, thanks again to anonEnterFrame event handler function and a few variables defined before it is executed. Thevariable 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 asan 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’ Ycoordinate 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 thecuurent 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. Asthe menu approaches the target position, the distance is smaller each time and there you have theeasing effect. Remember that the lower the value of menuSpeed, the quicker the menu will

Page 77: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 77/78

move. I found 6 to be an optimal value in combination with the speed of the SWF, which was setto 30 fps at the beginning.

And each time the menu approaches the target point, a check must be made to see if the point inquestion 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 asafeguard against waiting too long for the menu to reach the target position. This easing methodis described in more detail in my sliding image mask tutorial.

And, once that condition is fulfilled (meaning that the menu has reached the target position), itsposition is fixed in place by setting it definitely to the rounded targetPos value. I recommendthat you always do that in cases like this, because objects placed on round pixels are renderedmuch better than in other cases. Well, Flash 8 renders graphics greatly, but ensuring this withround 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, thedifferences 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. Thistime, the target position is determined by adding the height of the mask to the menuButtons’current position.

Page 78: Making the Ultimate Dynamic Image Gallery in Flash 8

8/6/2019 Making the Ultimate Dynamic Image Gallery in Flash 8

http://slidepdf.com/reader/full/making-the-ultimate-dynamic-image-gallery-in-flash-8 78/78