1. Code
  2. ActionScript

Make a Dynamic Copyright Notice in Flash: Part 1


This huge tutorial will help you learn a number of useful programming techniques, all tied together with a deceptively simple (and very flexible) end result. Grab a cup of coffee and let's jump into part one..

From the first look at the demo, I'm sure you will think, what's the big deal? This can be done with a single timeline tween and a stop() action in the last frame. But in this case, appearances are deceiving. The actual purpose of this tutorial is not to teach you how to make a primitive copyright notice, but to show you a great cluster of useful programming techniques, the copyright notice serving as a simple example.

Of course one may argue that using complex object-oriented programming for such a basic task is like firing a ballistic missile to swat a fly. But then again, if someone would actually manage to hit a fly deliberately with a ballistic missile, that would say a lot about that person's marksmanship, wouldn't it? Anyway, in a moment you'll see that our little module packs a lot more value than is at first obvious.

From this tutorial you will learn a number of useful techniques:

  • Creating timer-based animations
  • Transforming a String received from XML into a MovieClip instance name
  • Correctly interpreting XML String values as Booleans
  • Basic error handling when passing values from XML
  • Drawing shapes with code
  • Creating masks with code
  • Adding and removing event handlers
  • Creating the resizing events
  • Adding text fields in code
  • Text formatting
  • Working with Date class

In the meantime, you can download all the files used in this tutorial from the link above.

Step 1: Create a .fla File

Let's start by creating a new .fla file.

In that file, let's change the stage width to 600 and stage height to 300, and let's change the color of the stage from white to black. We'll create a rectangular MovieClip with width of 550 and height of 150, and let's place it on the stage at X coordinate of 25 and Y coordinate of 0. In the demo file I use in this tutorial, I've set the alpha of that MovieClip to 0, and the clip approximately covers the word PROJECT that appears in the background, but in your .fla the MovieClip can be of any color and opacity, and there needn't be any text on the background.

One thing is essential though: you should give the MovieClip on the stage the instance name of mcContentModule for our testing purposes.

Now let's link our .fla file to the custom Document class we have yet to create, by typing the path to the class in the Document Class textfield in the Properties panel of our .fla. For his tutorial, type CopyrightDocumentClass (the name of the custom class we'll be creating). For more information on working with the Document class, please consult this Document Class Quick Tip.

Let's save our project as CopyrightTest.fla.

Step 2: Outline the Desired Functionality

Before we begin coding, let's figure out what we want our copyright notice module to be like, and what we want it to do. This will help us organize the code well from the very start.

Our copyright notice should be easy to re-use. That's why we are going to write it as a custom ActionScript 3.0 class.

The copyright notice should include the current year and update automatically each following year. For this, we will need to use the Date class.

The copyright notice should be animated and we want that animation to play smoothly even when viewed on a really slow computer. This we can achieve using Timer class-based animation.

The copyright notice should have the option of being linked to another web page.

The copyright notice must self-align left or right, either near the bottom edge of the stage or near the bottom edge of a chosen MovieClip in our project. It should also realign itself whenever the browser window is resized. We will need the resize event handler/listener combo for that.

We also want our module to be dynamically customizable from an XML file: this way we'll have an easier time formatting it and won't need to republish the .swf file every time we make a minor change to the way our copyright notice looks and behaves. Sending data from an XML file is also very convenient for the end users, especially for those who know very little or nothing about ActionScript 3.0.

After a little brainstorming, we create the list of XML-customizable features we'd like to have in our module:

  1. The font
  2. The font size
  3. The font color
  4. The font weight (bold or regular)
  5. The font style (italic or regular)
  6. The font decoration (underline or none)
  7. The link url (in case at some point we want the copyright notice to be linked to another web page)
  8. The link target (opening the linked page in the same window or in the new window)
  9. The initial year of the copyright
  10. The name of the company or person who owns the copyright
  11. The optional additional statement, such as "All rights reserved"
  12. The positioning of the copyright notice (relative to stage or to a MovieClip of our choice)
  13. The instance name of the MovieClip (if the copyright notice is positioned relative to a MovieClip)
  14. The alignment of the copyright notice (left or right)
  15. The horizontal offset in pixels (relative to the left or right edge of the stage or MovieClip)
  16. The vertical offset in pixels (relative to the bottom edge of the stage or MovieClip)
  17. The optional slide-in effect (we want to be able to toggle it on or off)
  18. The speed of the slide-in effect
  19. The optional fade-in effect (we want to be able to toggle it on or off)
  20. The initial opacity (if the fade-in effect is used)
  21. The speed of the fade-in effect
  22. The final opacity

Twenty two options for easy customization, plus a lot of initial features, so as you can see, the copyright notice module we're about to create is indeed not as simple as it might have appeared at first.

Step 3: Create the XML File

As you may have guessed, we will now turn the list of customizable features from the previous step into an XML file that will control our copyright module. Nothing is easier, but if you want more information, take a look at this tutorial on XML for Flash.

Let's create a new XML file. We can do this in any non-specialized text editor, such as TextEdit for the Mac or WordPad for PC. (Alternatively, you can use a specialized editor, such as Adobe Dreamweaver.)

All we need to do now is transform the plain English descriptions of our custom functions from the previous step into the legitimate XML code, and insert some arbitrary values into it. Here's the result:

Let's save this file as Copyright.xml in a folder called CopyrightXML. IMPORTANT: the folder CopyrightXML should be located in the same directory as our CopyrightTest.fla file.

Step 4: Variables Declaration

In this step, we'll use our just-created XML file as the model for the initial list of variables we're going to use in our .as file. These variables will hold the values passed from the XML file.

But first, we should create a new .as file and save it in the same directory where we have the CopyrightXML folder. Let's call our new file

What we have now is just the empty .as file, so let's put some code into it.

There are twenty four items in our XML file, but we'll need twenty nine variables to pass these values to our ActionScript file, and here's why..

We can think of all the values held in the XML file as strings. Some of them appear numeric and others look unmistakably Boolean, but for our purposes, they are all strings nevertheless. In our ActionScript file, we'll keep some of those strings as strings. For example, the name of the font, the url, the name of the copyright holder and the statement will remain strings in our ActionScript file. Other values will have to be converted from strings to numbers and Booleans. We won't have to do anything special to convert strings to numbers in our code: we'll just use implicit conversion. Things are a little more challenging with Booleans.

It's convenient to use true and false values in XML. They are self-explanatory and useful when something needs to be toggled on and off dynamically. However, these are actually not Booleans but string values, and when passed to ActionScript and converted directly to Booleans, both "true" and "false" values will return true. Any non-empty string returns true when converted directly to a Boolean.

Later in this tutorial we'll use if... else if conditional statements to convert strings to Booleans, and for those statements, we'll need a String and a Boolean version of each true or false value passed from our XML file. This is why we need more variables to pass values from XML than there are items in our XML file.

For example, instead of having just one variable called theFontBold we'll have to have two variables: theFontBoldString to hold the String value and theFontBold to hold the Boolean value. So instead of this:

we'll have this:

Other than that, we'll pretty much go through our XML file top to bottom and translate the XML items directly to variables that we'll now type in our ActionScript file. This is what we'll have in our ActionScript file as a result:

Note that when declaring the data type for numeric variables, we're using uint data type whenever the variable will hold an unsigned integer, int data type if our integer variable may have a negative value (for example, our X and Y offsets may be negative), and Number data type only when we use decimals. This is the most resource-saving way to assign numeric data types to variables.

I won't remind you again, but let's agree to save our ActionScript file every now and then as we make changes to it.

Step 5: Variables TextFormat

The first six items in our XML file and the first nine of the variables we created in the previous step deal with text formatting. To enable text formatting, we'll need to add a new variable that belongs to the TextFormat data type. Let's call our variable tfCopyright, where tf stands for TextFormat.

The variable we've just declared will be taking care of all our text formatting needs.

Step 6: Variables TextField

To output the formatted text for the whole world to see, we need an instance of the TextField class. We'll create the actual TextField object a bit later, but now, as we're populating our list of variables, it would make perfect sense to declare the variable that will eventually hold our TextField instance. Let's call that variable txtCopyright:

As you can see, we're declaring all the variables in our code before assigning any values to them and before creating the functions that would manipulate those values. Even though that's not the only way to write ActionScript, and probably not even the easiest one, the described coding practice has many advantages. It can help a programmer to form a very clear idea of the code before the actual coding begins. It produces very readable, well-structured code. And last but not least (I hope you forgive me this little detour into psychology of programming), it can make a programmer feel confident and secure about being able to make the code do exactly what it must do.

So even if you do not understand why we declare some of the variables, please bear with me, and I promise that you will understand their purpose by the time we finish our tutorial.

Step 7: Variables Loading XML Data

To load data from our XML file into our ActionScript file, we'll need two kinds of objects: a URLLoader object and an XML object. Let's now declare the variables that will eventually hold these objects in our code:

Step 8: Variables Current Year Values

Our copyright notice will include two dates: the year the copyright began and the current year. We already agreed to set the initial year in the XML file. The value of the current year should update automatically each new year, and for this we will need an instance of the Date class, an unsigned integer to hold the numeric value of the current year and also the String object that will output the current year in the text field. Let's declare these three variables now:

Step 9: Variables Timer

Our copyright notice will have two optional animated effects: fade-in and slide-in. Our animated effects will be based on the Timer class, and to keep the animations independent from one another (so that, for example, if we stop the timer that controls one animation we don't accidentally stop the other animation's timer as well) we'll need two separate variables to hold the two instances of the Timer class. Let's declare them now:

Step 10: Variables Easing

I suppose we could use a Tween class or a popular tweening engine such as Caurina or TweenLite to add easing to our slide-in animated effect, but these are too heavy for a simple effect such as we need. Instead, we'll write a few lines of code for a very basic easing effect. For that code, we'll need two variables that will hold the decimal numeric values of the final X coordinate and the distance from our copyright module's current position to that X coordinate:

Step 11: Variables Relative X and Y Coordinates

We want to be able to place our copyright either at the bottom of the stage or at the bottom of a MovieClip in our Flash project, at the left or right edge of the stage or a MovieClip. To achieve that kind of flexibility, we'll need to make the actual X and Y coordinates of the copyright module depending on whether we place it relative to the stage or relative to a MovieClip, and on whether we place it to the left or to the right. We need variables for that:

Step 12: Variables Reference MovieClip

We need a variable to hold the MovieClip relative to which we may want to position our copyright notice:

Step 13: VariablesThe Mask

We'll use a coded mask to improve the look of our slide-in animated effect. Let's declare a variable to hold our mask. That variable can belong to either a Sprite or a MovieClip data type. In many cases we would use the Sprite data type for our mask, because the mask doesn't really need a Timeline, and having no Timeline, the Sprite class is lighter than the MovieClip class. However, we'll be importing the MovieClip class anyway, because the custom class we're creating will be written as a subclass of the MovieClip class. If we assigned our mask variable to the Sprite data type we would also have to import the Sprite class, which would make our code not lighter, but heavier.

So, our mask variable will hold an instance of the MovieClip class, and that's that (and I sure hope you're not feeling dizzy after reading the previous paragraph).

Step 14: Package the Class

Before we package the class, let's take a look at our code so far:

The groups of variables didn't have to be positioned in exactly that order. There are programmers who like their variable declarations to be grouped by the data type, others prefer alphabetical order. In this tutorial we group them by their functionality because that seems most natural and logical for this particular application.

Let's now add a few lines of code to package all these variables inside our custom class. We will be implementing it as a Document Class, which is a nice and easy way to use custom classes in Flash. To brush up on the topic, check out this Document Class Quick Tip.

You may find the following a little unusual, but it saves time. Let's start by adding four curly braces below our variables, one opening brace and three closing ones, like this:

Let's comment the braces:

Now let's add two opening curly braces above our variables, like this:

Let's comment these two braces, too:

Our class will be called CopyrightDocumentClass and it will be the subclass of the MovieClip class. We saved the file in the same directory where we keep our CopyrightTest.fla file and our CopyrightXML folder. Knowing these things, we can declare the package and the class before the first and second opening brace, respectively:

Finally, we should define the constructor before the opening brace that we placed below our long list of variables:

Our ActionScript file is now a legitimate custom class (even though, technically, it doesn't do anything just yet), and our code so far should look like this:

Step 15: Import the Superclasses

In our custom class we'll be using the following data types that must be imported:

  • Event
  • TimerEvent
  • URLLoader
  • URLRequest
  • Timer
  • TextField
  • TextFieldAutoSize
  • TextFormat
  • MovieClip
  • StageAlign
  • StageScaleMode

Let's import them, right under the package declaration, as it's appropriate:

Step 16: Align Stage and Set Scale Mode

We want our copyright notice to reposition itself whenever a user resizes the browser window, and we want any MovieClips on the stage to remain the same size irrespective of the current size and proportions of the stage. To make these two things possible, we need to align the stage and make the visual objects on the stage non-scalable.

Let's add a couple of lines of code just below the constructor definition:

These two new statements tell Flash to align the stage to the top left corner of the player and to set the scaleMode of the stage to NO_SCALE constant (which means that any visual object on stage, including the TextField that will hold the copyright information passed form XML and our reference MovieClip, will not be scaling when the browser window is resized. If we wanted to make them scalable, we would have to set the stage scale mode to EXACT_FIT or to SHOW_ALL.)

Step 17: Load XML

Let's now load XML data into our ActionScript file. Add the following code below the code we wrote in the previous step:

That event listener/event handler pair loads the XML data from the file located at a given URL. For the details on how it's done I'd like to address you again to this tutorial on XML for Flash.

We won't be adding any more code within the constructor function. The code we've written so far should look like this:

Step 18: Define the Main Function

This may come as a shock, but we're not done with the variables yet. We've declared them, but they currently don't hold any values. We need to assign values to all our variables. Most of those values should come from our XML file, a few others will be calculated with simple mathematical operations, and one value (the current year) will be taken from the system of whichever computer runs our little application.

Because of the challenge of converting Strings passed from XML into Booleans, the values will have to be assigned to our variables in a certain order, and the reason for that order will become very clear in the next few steps of the tutorial.

Also, because most of our values come for the XML file, we'll need to contain them within a function that parses the XML. But to organize the code even better we can actually contain all our variable values within that function, and make the function not only parse XML but also perform all the manipulations with the data held in the variables. By the look of it, that function qualifies as the main function of our code. So let's define it now. It doesn't need to return any value, so we can indicate the void data type after the parentheses. Let's name our main function makeCopyright and add it below the constructor in our code:

This looks good, but there's one more thing to do before we proceed to the next step. A lot of values for out variables will be passed from the XML file, so we'll need to reference that file somehow in our function. In order to do so, we should pass to our function an argument of the XML data type. We can call that argument anything we want, so let's not strain our imagination too much and just call it copyright, and let's put it within the parentheses where it belongs:

To better understand what we just did, you can think of it this way: the name of the argument we placed in the parentheses (copyright) is simply a nickname for our XML file.

We have the basis for the main function of our code now and in the next few steps we'll be writing the code within our main function.

Step 19: The TextField Object

Let's assign the value to the txtCopyright variable by calling the constructor of the TextField class:

We've created the TextField object, so now let's add it to the Display List:

Step 20: Display Text in the TextField

Our copyright notice should have this format: COPYRIGHT @ Initial Year-Current Year Name of the copyright holder. Optional statement. Let's now express this via ActionScript:

Step 21: Add Variable Values

Let's save our .as file and test our code now by publishing the .swf file. If your code matches mine, your .swf file should look more or less like this:

If you're expecting the TextField we created to be visible by now, your expectations are justified. But where is the TextField?

If you click and drag anywhere in the upper left corner of the image, you will see the text field. It was sort of invisible before because the text in it is black by default, and couldn't be seen against the background of the black stage.

Apart from the text color, we can see two other obvious problems with our TextField: it's too narrow to display the entire copyright notice, and all the values that should come from XML display in it as null, like this: COPYRIGHT © null-null- null null. That's because the variables that we use to display text are still holding their default values (null), since we hadn't yet assigned any non-default values to them. Let's fix that first, and take care of the width of the TextField later. Obviously, we should assign values to the variables above the code that displays them, otherwise even after we fill the variables we'd still be getting null-null null null output.

First, we should get the String values from XML. We can do it using the following model:

In this model, theVariable and xmlItem are pretty self-explanatory, and the argument stands for the name of the single argument we placed in the parentheses of our function. The nickname for our XML file (copyright). Remember?

So, to pass the value to the initialYear variable from the XML item that is also called initialYear, we should write this line of code:

To assign values from XML to theHolder and theStatement variables, we write this:

We have one more value to obtain for display in our TextField: the String value of the current year. To get that value from the system of a computer that will run our code, we'll actually need not one variable, but three.

First variable, currentDate, belongs to the Date class. Let's call the constructor of the Date class to assign the value to that variable:

We will now use the second variable, currentYear, to extract the unsigned integer value of the current year from the Date object we've created a moment ago. We'll use the getFullYear() method of the Date class for that:

The third variable, currentYearString, will hold the String value converted from the numeric value of the currentYear variable using the toString() method of the uint class:

All the variables involved in displaying the text in the TextField object are now holding the required values. The only thing we can do to further improve our code now is add comments. With the comments, the code in our main function should look like this:

Let's resave the .as and republish the .swf. Click and drag near the upper left corner of the image, and you will see the TextField filled with correct values passed from XML and the system of your computer:

In the next few steps we'll resolve the problems with the color of the text and the width of the TextField.

Step 22: TextFormat Variable Value

To format the text displayed in the TextField, we should create an instance of the TextFormat class. We already have the variable tfCopyright that will hold that TextFormat object. The new code should be placed below the one we've completed in the previous step:

Step 23: String and Numeric Values

We need to get String and Numeric Values for the TextFormat Object from the XML. The model is already familiar from one of the previous steps, so there's not much to explain:

The only thing to be noted is that we're actually using the same syntax to get String and numeric values from XML. If we aimed for perfection, we could use slightly different syntax for extracting the numeric values:

But we don't have to, because Strings convert implicitly to Numbers and integers. So, to keep things simple, we'll just use the same syntax structure for getting Strings and numbers from XML.

Things will get a little more involved when we need to take String values from XML and convert them correctly into Booleans, as you'll see in the next step.

Step 24: Convert Strings and Handle Errors

Any non-empty String will convert into a Boolean as true. This means that if we try to pass true or false values from our XML file using the syntax model described above, the Boolean will return true no matter whether the XML item contains true or false. That's very unfortunate because Boolean values are otherwise simple and convenient. Luckily, there's a workaround.

We can use a well-known if... else if conditional statement to convert Strings to Booleans. Here's the generic model:

Error handling is a huge topic and we won't go into much detail here. When the data loads dynamically, errors can happen literally anywhere. In fact, one of the valid definitions for a computer is "the machine to make errors". If we tried to handle every possible error here in this ridiculously simple tutorial, our code would begin to look paranoid (even though often addressing every possible error is necessary and ActionScript 3.0 offers a lot of tools for that).

To illustrate the concept, if a user accidentally types trye instead of true in the XML file, the value will actually return as false, because else if part of the conditional statement includes all the functionality of the else. If we didn't add the final else clause, a user may not ever notice the typo and keep wondering why the value set in XML as true returns false in ActionScript. To help such users, we can add the final else clause and tell Flash to replace the text in our TextField object with an appropriate error message. This is why we need this code to be placed below the code that creates the TextField object and displays text in it. Otherwise our error message would never be displayed.

Enough theory, let's finish up Part 1 by applying our generic model to specific tasks:


Well, we've covered quite some ground during this tut! I hope you enjoyed following it thus far; part 2 coming soon..

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.