Week 11: AS3 – Animation, Hit Testing, Drag Events

November 17th, 2009
  • Animating With ActionScript
  • Drag and Drop!
  • Hit Testing

Week 11 Example Files

week 11 CS3 Files

Some of the examples from today’s class came from another terrific Friends of Ed book, that you can also get from the 24/7 library – Foundation Actionscript 3.0 Animation: Making Things Move!

This book gets into much more detail about animating with ActionScript, so if your interests lie there, check it out!


Animating with ActionScript

Now that we are comfortable with working with and creating display objects, and using event listeners and event handlers, we can also create animation entirely from code, without involving the timeline. To do this, we use a new event type, onEnterFrame, or ENTER_FRAME event.

You might think that you could use a for loop for animation, like this:

for(i = 0; i < 500; i++){
    ball.x = i;
}

Where “ball” is a display object that you have defined elsewhere. You might think that this code would move the ball 1 pixel 500 times, and in a sense you would be right. The problem is that you would only see the result of the last loop, because all 500 loops are executed before the frame is rendered. To get around this, you need to introduce time between loops, which is where ENTER_FRAME comes in. The ENTER_FRAME event is dispatched at the frame rate of the .swf. Here’s a simple example of how you would use ENTER_FRAME to move a sprite across the stage by 1 pixel in the X axis every frame:

ball.addEventListener(Event.ENTER_FRAME, onEnterFrame);

function onEnterFrame(event:Event):void {
     ball.x++;
}

Creating Drag and Drop Elements

The Sprite class has built into it several methods for allowing user input to grab an object on the stage and drag it to another location. These methods are called startDrag and stopDrag, can be used with any Sprite or MovieClip, and are generally triggered by mouse events. These methods are tied to a specific display object and triggered within an event handler.

The startDrag is called when the initial user event is dispatched, and causes the target object to be draggable. This method takes two optional arguments:

  • lockcenter – this is a Boolean that determines whether the Sprite is locked to the center of the mouse position (true) or to where the user first clicked on it (false). The default value is false.
  • bounds – specifies a boundary rectangle for the Sprite. The default value is null.

The stopDrag method is called when the terminal user event is dispatched, and causes the target object to cease being draggable. This method takes no arguments.

There is a property of the Sprite object that is related to these functions, called the dropTarget. This specifies the object which the sprite was dragged and released onto.


Hit Testing

It can be useful when creating dynamic code based animation to be able to detect when one display object collides with another. This is called “Hit Testing” and there are two DisplayObject methods for dealing with this.

  • hitTestObject takes a single argument, which is the name of the display object you want to test against
  • hitTestPoint takes a three arguments:
    • x:Number – an x coordinate to test against the object
    • y:Number – a y coordinate to test against the object
    • shapeFlag:Boolean – true checks against the actual pixels of the object, false against the boundary box

Homework

This week you have a choice, do one of the following (if you are feeling ambitious, do both and get extra credit!):

1. Using drag event, create a matching game where the user has to match the object they are dragging to another object on the stage.

2. Create an animation, using only code, with at least 10 objects. The objects should react when they hit each other. Be creative about what happens when objects collide!

Week 10: More AS Basics, AddChild, Loading Files

November 9th, 2009
  • More ActionScript Basics
    • Block Statements
    • Arrays
    • Comparison Operators
    • Logical Operators
    • Boolean Operators
    • Conditional Statements
    • Looping
    • Conditional Statements
  • Dynamically Adding Library instances to the Stage
  • Loading External Images and SWFs

Week 10 Example Files


Arrays

An array is a data structure similar to a variable, in that it allows you to hold values in memory. The difference is that a variable can only hold one value at a time, where an array can hold multiple values. Another distinction is that an array can hold values of multiple datatypes. Arrays are used in applications where you need to track an ordered list of values.

There are several different ways to create and populate an array. The simplest way is to create an empty array of indeterminate length:
var myArray:Array = new Array( );

You’ll notice the new operator here for the first time. This allows you to create a new instance of almost any ActionScript object. We’ll get into it more later!

If you put a value in the parentheses after Array in this statement, you are passing a parameter to the array. If you pass a single number, this will determine the number of spaces in the array:

var myArray:Array = new Array(5);

This creates an array with 5 spaces.

If you put anything besides a single number into the parentheses, the value(s) will be the initial values stored in the array.

var myArray:Array = new Array("Apple","Banana","Pear","Peach");

However, we usually create and populate an array all in one go using an array literal, a comma separated list of values enclosed by square brackets:

var arrayName:Array = [ value1, value2, value3 ]

Each value in array is an element. The place that the element holds within the array is its index. In order to access a specific element within the array, you must refer to it by the index number. Important to note is that the first element in an array has an index of 0, not 1.

To access an element in an array, use the following syntax:

arrayName[i]; 

Where i is the index number.

Here’s an example that puts it all together:

//define the array
var fruit:Array = ["banana", "orange", "papaya", "pineapple"];

//access the value of an array element
trace (fruit[0]);

You can find out the length of any array like this:
trace (fruit.length());

If you want to redefine a value in an array, you do this:
fruit[1] = "Guava";

You can add a value to an array either of these ways:
fruit[4] = "Guava";
or
fruit.push("Guava");

The advantage to the second method is that you don’t need to know how many values are already in the array.

You can delete a value in the array with the delete keyword:
delete fruit[1];
This will leave a blank space in the array.

If you want to get rid of that spot in the array completely, you must use the splice method of the Array object:

fruit.splice(1,1);

This will remove 1 element starting at index 1 of the array.

If you want to sort the contents of an array,  you can use the sort method:

fruit.sort();

You can pass an options parameter to the sort method, here are just some of the options:

fruit.sort(Array.CASEINSENSITIVE);

fruit.sort(Array.DESCENDING);

fruit.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options

LiveDocs > Working with Arrays

LiveDocs > Array Reference


Comparison Operators

Last class we talked about mathematical operators. This week we are going to also make use of comparison operators, also called relational and equality operators. Here is a list:

  • < Less than
  • > Greater than
  • <= Less than or equal to
  • >= Greater than or equal to
  • == Equality
  • != Inequality
  • === Strict equality
  • !== Strict inequality

The operators are used to compare the values of the expressions to the left and right of them. Take note of the difference between the assignment operator (=) and the equality operator (==). = is used to assign the value of the expression on the right to the left. == is used to compare the equality of two values.

Livedocs > Operators


Boolean Logic and Operators

So far we’ve covered mathematic, comparison, and equality operators. The next set of operators that becomes useful to us are the logical operators. These will help us create more complex test expressions for use in both conditional and loop statements. Logical operators use boolean logic (whether something is true or false) to evaluate two expressions.

Logical OR

The logical or operator is expressed like this: ||. The use of this operator will return a value of true if at least one of two expressions to the left and right of the operator are true. The syntax for the OR operator is this:

expression1 || expression2

At runtime, the program will evaluate the values of expression1 and expression2. If either are true, it returns a value of true.

Logical AND

The logical AND operator is expressed like this: &&. The use of this operator will return a value of true if both expressions to the left and right of the operator are true. The syntax for the AND operator is this:

expression1 && expression2

At runtime, the program will evaluate the values of expression1 and expression2. It will only return a value of true if both expressions are true.

Both the && and || operators are useful when you want to test an expression within a range of values.

Logical NOT

The logical NOT operator is expressed like this: !. The use of this operator will return a value of true if the expression evaluates as false, and a value of false if the expression is true . Basically, it will return the opposite value. The syntax for the NOT operator is this:

!expression

This can be useful in situations where you need to toggle a value back and forth, like an on / off switch.


Conditional Statements

A conditional is a statement that is only executed at run time if a certain condition is met. There are two conditionals within ActionScript: if and switch.

The if statement

A basic if statement contains two block statements and a test expression:

if (testExpression) {
codeBlock1
} else {
codeBlock2
}

Here’s a example of the if statement in action:

//define variables
var age:Number = 21;
var greeting:String

// if statement
if (age < 21) {
greeting = "Sorry, no beer for you!";
} else {
greeting = "Have a cold one on me!";
}

//Output result
trace(greeting);

In the example above, the else clause provides an outcome in the case that the test expression is not true. You can also omit the else clause entirely, in which case the program will do nothing:

// if statement without else clause
if (age < 21) {
greeting = "Sorry, no beer for you!";

If you have a scenario in which you want to have more than two possible outcomes, you can chain your statements, adding an elseif clause:

if (testExpression1) {
codeBlock1
} else if (testExpression2) {
codeBlock2
} else {
codeBlock3
}

Livedocs > Conditionals


Loops

A loop is a block of code that is executed repeatedly based on a test expression. There are five types of loops: while, do-while, for, for-in, and for-each-in.

While Statement

A While statement executes while a test expression is true.

while (testExpression) {

codeBlock

}

You can see this looks very much like the if statement. The difference is that after the code block is executed the program returns to the beginning of the statement and evaluates the test expression again. If the test expression remains true, the code block is run again. This will continue until the test expression is evaluated as false.

If you create a while statement with a test expression that never evaluates as true, the loop will execute indefinitely, and Flash will generate a runtime error. Usually within the code block, you will include a statement that modifies the test expression. This will yield a false value for the test expression after the loop has executed the desired number of times:

var i:Number = 0;
while (i < 5) {
i = i + 1;
trace (i);
}

The variable name “i” is often used in a loop such as this. Like any variable, those used in a loop can have any name, but since this value is used as an incrementor, i is a recognizable shorthand for this use, and a common convention among programmers. There is also a new operator you can use in this case, the increment operator, which looks like this: ++. Placing this operator after a variable name will increase the value of the variable by one: i++. Our while loop example above can be simplified with the increment operator like so:

var i:Number = 0;
while (i < 5) {
i++;
trace (i);
}

There is also a decrement operator: –. When used after a variable name, it will decrease the variable value by one. So if you want your loop to count down to a value, instead of up, it could look like this:

var i:Number = 5;
while (i >= 0) {
i--;
trace (i);
}

do-while Statement

The do-while statement functions exactly the same as the while statement, except that the code block is placed before the test expression. This ensures that the code block will run at least once, even if the test expression evaluates as false the first time through. The syntax for the do-while statement is as follows:

do {
codeBlock
} while (testExpression);

For Statement

The for statement functions essentially the same as the while statement, but with a more compact syntax:

for (initialization; testExpression; update) {
codeBlock
}

The following example yields the same result as our original while statement, but in a much more compact way. Notice that the variable declaration and initialization, test case, and incrementor all take place within the test expression:

for (var i = 0; i <= 10; i++) {
trace(i);
}

Just like if statements, loops can be nested inside each other:

for (var i = 0; i <= 10; i++) {
trace("i="+i);
for (var j = 0; j <= 10; j++){
trace ("j="+j);
trace ("i*j="+j * i);
}
}

Using a loop with an array

Any type of loop statement is very useful for performing the same operation on all elements in an array. If we combine a for loop with the array we defined early, we can out all the values in the array sequentially:
for (var i = 0; i <= fruit.length; i++) {
trace(fruit[i]);}

Livedocs > Looping


Adding Objects to the Display List

There are two steps to adding a new Object to the stage. The Object can either be one of the built in classes (MovieClip, Sprite, TextField, etc) or an item from the library. First you must create the object instance using the new operator:

var myObject = new Object();

This instantiates the object, but it does not yet appear on the stage. You must add it as a child of the stage in order for it to become part of the Display List:

parentObject.addChild(myObject);

You can also put a new child at a specific depth, although you can’t skip depths. If you put a child at a depth where one already exists, that one will be bumped up a level.

parentObject.addChildAt(myObject,depth);

The parent object can be any DisplayObjectContainer that is already in the Display List. Remember, this includes the stage!

Remove Objects from the Display List

This is a one step process:

parentObject.removeChild(myObject);
Or
parentObject.removeChildAt(myObject,depth);

Livedocs > DisplayObjectContainer


Loading External Assets

ActionScript has the built-in ability to load external files via the Loader object, which, like MovieClip and Sprite is a subclass of the DisplayObjectContainer class. The Loader has a few special methods and properties that are tied to the loading and manipulating of an external file. You may load image files (jpg, png, or gif) and also other swf files, including swf files created with older versions of flash, with ActionScript 1.0 and 2.0.

The Loader works in conjunction with another class: URLRequest. This is a part of the flash.net package. When you create a new URLRequest you designate the path/filename of the asset to be loaded. This can either be an absolute path (http://www.mywebsite.com/image/myimage.jpg) or relative to the .swf file that will load the asset (image/myimage.jpg).

Once you have created instances of the Loader and URLRequest you can then use the load method of the Loader class to load the asset into the loader, something like this:

myLoader:Loader = new Loader();
myRequest:URLRequest = new URLRequest("images/myImage.jpg");
myLoader.load(myRequest);

A Loader instance can only hold one URLRequest at a time. If you load a new request into it, it will replace the existing request. However, you can have multiple Loader instances in a single movie.

Livedocs > Loader


Homework

Create a Flash movie containing grid of at least 9 images. To do this you should:

  • Use a loop to load the images from external files and add them to the stage

Week 9: Controlling Movie Clips, Simple Events

November 2nd, 2009
  • Functions
  • Variable Scope
  • Objects and Classes, Properties and Methods
  • Changing MovieClip properties with ActionScript
  • Buttons
  • Text Fields

Examples


    Functions

    A function is a block of code that can be defined and then invoked at a later time. There are two primary advantages to using functions. First, a function can be invoked in your ActionScript at any point and as many times as needed. Second, you can pass parameters into a function call for even more flexibility.

    Functions statements have three parts:

    1. The function name
    2. The parameters, in a comma-delimited list enclosed in parentheses
    3. The function body–that is, the ActionScript code to be executed when the function is invoked, enclosed in curly braces

    Function syntax looks like this:

    function functionName(parameter1:datatype, parameter2:datatype):returntype {
    function body
    }

    To call, or invoke, a function, you use the function name, followed by the parameters (also called arguments) enclosed by parentheses:

    functionName(parameter1_value,
    parameter2_value);

    Functions have the ability to take and return values. These values can be of any datatype. If a function does not take any values, simply leave the parentheses empty. If a function does not return any values, the the return type must be specified as :void. This is a function that does not take or return any values:

    function basic():void{
     trace("This function doesn't do much.");
    }

    To call this function, use this code:

    basic();

    This function takes two numbers and returns a number:

    function addMe(var x:Number, var y:Number):Number {
    z = x + y;
    return z;
    }

    When this function is called, you must pass it two numbers:

    addMe (4,5);

    This function call will add 4+5 and return 9.


    Variable Scope

    A variable’s scope refers to where in the code it is defined. A variable is either global or local. A global variable is available to all code within the program. A local variable is only available to the function or statement where it is defined. For the most part, we’ve been dealing with global variables. However, variables that we’ve defined within conditional statements or loops are confined in scope to those statements.

    Let’s take the example of the addMe Function above:

    function addMe(var x:Number, var y:Number):Number {
     var z:Number = x + y;
     return z;
    }

    In this case, the variables x, y, z are all local to the addMe function. The problem with this is that the function returns the value of z, but there is no way to directly access this value outside of the function, because it only has meaning within the function. If you want to do more with z, you could either call the function and assign it’s return value to a new variable, like this:

    var addResult:Number = addMe(4,5);

    Or  you could  define z outside the function:

    var z:Number;
    function addMe(var x:Number, var y:Number):Number {
     z = x + y;
     return z;
    }

    Now, when you call this function you will have access to the returned value of z. Note, however, that x and y are still local variables, because you defined them within the parameters of the function.

    About Functions


    Objects and Classes, Properties and Methods

    Absolutely everything that you use in ActionScript is an Object, and each of those Objects is defined by a Class. Classes are stored in external .as files. When you installed the Flash IDE on your computer, you also installed the entire library of built-in classes that are the foundation of the ActionScript language. Objects represent a specific instance of a Class. Another way to look at it is that a Class is a blueprint for an Object.

    Classes in ActionScript are composed of three elements: Methods, Properties, and Events.

    • Properties are what Objects are
    • Methods are what Objects do
    • Events track when something happens that ActionScript can respond to, like user input

    Methods and properties have a relationship to programming concepts that we have already explored. You can think of Properties as Variables that belong exclusively to a class, and Methods as Functions that do the same.

    Let’s look at the MovieClip class in the Help system to see how it is organized.

    You’ll notice that the first thing that is listed about the MovieClip class is its Package.

    Packages

    A package is a way of organizing classes. A package is a collection of associated .as files, each of which contains a class. The package that contains the MovieClip class is the flash.display package. This package contains all the core classes which describe objects that are displayed visually on the stage (including the stage itself!).

    Inheritance

    One of the most powerful aspects of OOP is the concept of inheritance. Classes can inherit properties and methods from other classes. This sets up parent/child relationships in a hierarchy of classes that allow a class to share, or inherit, properties and method from the parent classes, in much the same way that you inherit biological traits from your parents. A better analogy is actually your relation as a organism to the human race. You share with all humans the trait (or properties) of having two arms, two legs, hair on your head, etc. You can do the things that humans do (methods!) like walk upright on two legs, and talk in human verbal language. Beyond that, you are a member of the larger class of mammals, and share traits and behaviors with that class, like being warm-blooded, and breathing oxygen. In fact, the whole taxonomy of biological classification that you learned in high school (you know, Kingdom, Phylum, Class, Order ….) could be looked at as a series of Objects or Classes in a OOP system.

    The MovieClip class inherits properties and methods from the SpriteDisplayObjectContainer, InteractiveObjectDisplayObjectEventDispatcher, and  Object Classes.

    Subclasses

    The MovieClip is a subclass of all the class it inherits from, and it has a subclass of its own, LivePreviewParent. Subclasses inherit the properties and methods of their parents, but also have characteristic that are unique to themselves. A well-defined OOP system has very generic classes at the top of the hierarchy, and gets more specific as you go down the hierarchy.

    Properties

    The next thing about the MovieClip class that we see, after the description of it, are its Properties. These are the Properties that are specific to the MovieClip class, currentFrame, currentLabels, currentScene, etc. You’ll perhaps notice that these properties are related to the timeline. This is because MovieClip is a display object with a timeline, and this is the primary difference between it and its parent, the Sprite!

    Methods

    Next are the methods, and you will notice that they are also pretty much timeline-related: goToAndPlay, goToAndStop, nextFrame, etc.


    Accessing Properties and Calling Methods

    We access properties and call methods using the dot (.) operator. Before the dot you specify the name of the variable in which the object is stored, and after the dot the name of the property or method you wish to access:

    ObjectName.propertyname;

    ObjectName.methodname(arguments);

    For a string, you can access the length property like this:

    greeting.length

    Or call the String method charAt() like this:

    greeting.charAt(4);

    A string is actually an array of characters, and the charAt method allows you to access a character at a specifc place in the array.

    Basics of OOP


    The Display List, DisplayObjects, Sprites, and MovieClips

    The Display List

    Anything that appears on the stage is part of the Display List. The Display List is a hierarchy of the visual objects in your Flash movie. All Display Objects are descended from the DisplayObject class in the flash.display package. The Display List of any Flash movie has a tree structure that is made up of nested Display Objects:

    The Display ListThe Display List

    The Stage is the base container. Each movie has a main class associated with it. When the .swf is run, the movie calls the constructor method of that class.

    Display Object Core ClassesDisplay Object Core Classes

    The above diagram details all of the objects in the Display package. Today we are going to go over a portion of them.

    Display Object

    This is the base object, all other Display Objects inherit the properties and methods from this class. It contains generic properties such as x/y coordinates, width and height. All other Display Objects extend this class, either directly or indirectly.

    Interactive Object

    This class adds methods, properties and events that allow you to add user interactivity to a Display object.

    Display Object Container

    This class adds the ability of a Display Object to hold other Display Objects.

    The three classes above are abstract classes, which means that you can’t create instances of them, they are designed only to hold properties and methods that will be utilized by the child classes.

    Sprite

    This is a new type of Object in ActionScript 3.0, and there is no way to create a Sprite through the IDE, only via ActionScript. The Sprite is a stripped down version of the MovieClip, without any properties, methods, or events related to the timeline. Because of this reduced functionality, the Sprite is much lighter weight than the MovieClip.

    MovieClip

    The most important of the Display Objects, MovieClip inherits all the properties and methods of a Sprite, and adds timeline oriented properties and methods.


    Manipulating Display Objects with ActionScript

    Any MovieClip symbol on the stage can be manipulated with ActionScript, as long as it has an instance name.

    Manipulating Display Object Properties

    You can manipulate the properties of any display object on the stage that has an instance name. These properties include:

    • x
    • y
    • width
    • height
    • scaleX
    • scaleY
    • rotation
    • alpha

    Getting and Manipulating the Depth of Display Objects

    Each display object is assigned a depth according to the order in which it was added to the stage, starting with zero and ascending. There are a number of methods for getting and setting object depths:

    • getChildIndex(objectname)
    • getChildAt(indexnumber)
    • setChildIndex(objectname, depth)
    • swapChildren(object1,object2)
    • swapChildrenAt(index1, index2)

    Controlling Playback on a Movie Clip

    If your MovieClip has a timeline, then that timeline will automatically play and loop when you play the swf. ActionScript allows you to control playback with a number of built-in methods of the MovieClip Class:

    • gotoAndPlay() Starts playing the SWF file at the specified frame.
    • gotoAndStop() Brings the playhead to the specified frame of the movie clip and stops it there.
    • nextFrame() Sends the playhead to the next frame and stops it.
    • prevFrame() Sends the playhead to the previous frame and stops it.
    • play() Moves the playhead in the timeline of the movie clip.
    • stop() Stops the playhead in the movie clip.

    Events

    So far all of the code we have written has executed all at once, with no passage of time. It also has not allowed for any user interaction. In order for us to add temporality or interactivity to our ActionScript, we must take advantage of Events.

    All events are instances of the Event class, with properties and methods like all classes. The Event model in ActionScript 3.0 has three objects associated with it:

    1. Events
    2. Event Dispatchers
    3. Event Listeners

    The key to utilizing events is to set up an event listener. This is an object that keeps watch for a certain event to happen. When you set up a listener, you provide it with two things, the type of event you are listening for and the method that you want called when that event occurs. This is the syntax for an event listener:

    yourObject.addEventListener(event_type, listener_method);

    The event type includes Mouse and Keyboard inputs, frame events, and the loading of external data, among others.

    The listener method is the method you want to call when the event happens. It is also sometimes referred to as the “event handler” This method takes a single parameter, specifying the type of event being listened for. Generally these will either be “Event” or “MouseEvent”. The return type for listener methods is always “void”. The method will look something like this:

    private function methodName(event:EventClass):void {
    // this code will execute when the event is dispatched
    }

    Mouse Events

    These are the AS 3.0 Mouse Events that you can set up a listener for:

    • CLICK
    • DOUBLE_CLICK
    • MOUSE_DOWN
    • MOUSE_MOVE
    • MOUSE_OUT
    • MOUSE_OVER
    • MOUSE_UP
    • MOUSE_WHEEL
    • ROLL_OUT
    • ROLL_OVER

    So if you wanted to put an event listener on the click event of an object, you’d write it like this:

    yourObject.addEventListener(MouseEvent.CLICK, yourFunction);

    Enter Frame Event

    You can also set up an event listener to trigger a function everytime your movie enters a new frame:

    yourObject.addEventListener(Event.ENTER_FRAME, yourFunction);

    Creating a Simple Button

    1. Draw a shape on the timeline that will serve as your button. Add a text label if you like.
    2. Make a new symbol with the shape, make sure that you choose “Button” instead of “MovieClip” under symbol type.
    3. Double-click on the new button symbol to open up its timeline. You’ll see that it has four frames called “Up” “Over” “Down” and “Hit”. This allows you to quickly set the different states for the button. Test the movie to see the new states.
    4. Now create an event and event listener for the button.

    Creating a Simple Form

    The “text” property allows you to get and set the current value of a text field. If the text field is set to “dynamic” and has an instance name, you can change the contents of it with ActionScript like so:

    myTextField.text = "new text";

    If the text field is set to “input”, you can also get the current value of the text property like so:

    trace(myTextField.text);

    Combine these and button events, and you can create a simple form and do something with the user input.


    Homework

    Take your madlib assignment from last week and create a user interface by add elements on the stage so that a user can input words and then see their Madlib.

    Week 8: Flash Part 2, Intro to ActionScript

    October 27th, 2009
    • More Ways to Manipulate Objects on the Stage
      • Gradient Fills
      • Gradient Transform Tool
      • Transform Window
      • Masks
      • Guide Layers
    • ActionScript
      • What is ActionScript?
      • Two ways to create ActionScript – The Actions Panel and .as files
      • ActionScript Syntax – Expressions and Statements
      • Case-sensitivity and naming conventions
      • Using the Trace function
      • Defining and Using Variables
        • Syntax
        • Datatypes
        • Naming conventions
        • Assigning Values
      • Concatenation
      • Mathematical Operators
      • Commenting your code

    What is ActionScript?

    ActionScript Example files

    ActionScript is the programming language built into Flash.

    To date, there have been three distinct versions of ActionScript – 1.0, 2.0, and 3.0. In this class, we will be exclusively using version 3.0. In order to use ActionScript 3.0, you will need to be running Flash CS3 or Flash CS4.

    Object Oriented Programming

    ActionScript 3.0 uses a programming methodology called Object Oriented Programming (OOP). This technique involves organizing your ActionScript into modular pieces of reusable code called Objects, which have distinct properties and functions. Older programming languages used procedural methods, where the code was written and executed in a linear fashion. OOP is a much more nimble and manageable approach to programming, and has the following advantages:

    • You can break your project down into small, managable programming tasks
    • You can easily reuse functionality from one project to another
    • It is much easier to debug, since you can isolate and troubleshoot discreet pieces of functionality

    Two ways to create ActionScript

    You can add ActionScript to your Flash project in two ways – either within your .fla file via the Actions panel, or by using external .as files. We’re going to learn the first way this week.

    The Actions panel

    You can place code on the timeline of your project by using the Actions Panel.  Open the Actions panel from the Main Menu by choosing Window > Actions, or by pressing F9 (Windows) or Option+F9 (Mac). You can attach ActionScript to any frame of any layer in your movie by selecting the frame in the timeline and typing the code into the actions panel. However, it is good housekeeping to place most of your code on a separate layer in the main timeline. I usually call this layer “Actions” and place it as the very top layer of the main timeline.

    ActionScript Syntax – Statements and Expressions

    All ActionScript code is written in Statements and Expressions.

    A Statement is a complete instruction in ActionScript. In other words, it is the “sentence” of the AS language, and like a sentence, it represents a complete thought. The most important thing to remember about statements is that they must be terminated by a semicolon – ; If you do not do this, your code will not work!

    An Expression is an incomplete instruction, like a clause in a sentence.

    Variables and Data Types

    A variable is a construct that is designed to store information for later use in the program. In ActionScript, variables have distinct data types that determine what kind of data you can put in them.

    There are five basic data types we will use today:

    • String
    • Number
    • int
    • uint
    • Boolean

    A String is a single character or sequence of characters, in other words, text. Strings are always represented between double quotes – “String here”.

    A Number is any kind of numerical value, including positive, negative, fractional and whole numbers.

    An int (integer) is a postive or negative whole number

    A uint (unsigned integer) is a postive whole number

    A Boolean stores only two values, true or false.

    Declaring Variables

    Before you can store a value in a variable, you have to define, or declare it. There is a specific syntax to do this, using the keyword var. and then a unique identifier for the variable. You must also specify the data type when you declare the variable. Here’s an example of how to declare a string variable:

    var firstName:String;

    Here’s a number:

    var age:Number;

    Assigning a Value to a Variable

    Once you have defined a variable, you can assign a value to it:

    firstName = "Katy";

    You can see above that I put the value in double quotes (””). This is only necessary for String values. This is how you would assign a value to a Number:

    age = 12;

    You can also declare a variable and assign it a value all in one statement:

    var underAge:Boolean = true;

    This is called intializing the variable.

    The trace function

    So, declaring and assigning values is all very fine, but what can we do with them? This is where we are going to introduce a useful thing called a function. A function is one of those reusable bits of code I mentioned earlier, and we are going to get much more into them in future classes. For now, however, we are going to make use of a function that is built into Flash called trace. This function allows us to write data to the output window, and here is how it is used:

    trace(underAge);

    Invoking the trace function here allows us to retrieve the value stored in the votingAge variable and output it. Until we learn how to use ActionScript to control objects on the stage, we’re going to be seeing a lot of our friend trace.

    Naming Conventions for Variables

    There are a few rules for variable names in ActionScript, ignore them at your peril:

    • ActionScript is case-sensitve – that means that Name, name and NAME would indicate three different variables. Choose a naming scheme for yourself now, and stick with it.
    • No spaces in variable names
    • Use only letters, digits, the underscore character and the dollar symbol
    • Do not start your variable name with a number
    • Do not use a reserved word
    • Must be unique within the project

    Constants

    If there is a value that you will use repeatedly throughout your code, but will not change, you can define this as a constant:

    const DAYS_PER_WEEK:uint = 7;

    This defines a positive integer with the name DAYS_PER_WEEK and the constant value of 7.

    Arithmetic Operators

    There are a number of symbols defined within Flash as operators. These general link two expressions and define how to combine or compare them. We’ve already seen one operator, in assigning a value to a variable, the assignment operator, which is the equals sign (=)

    The other arithmetic operators are as follows, and most should be familiar to you since primary school:

    • + Addition / Concatenation
    • - Subtraction
    • * Multiplication
    • / Division
    • % Modulo

    Most of these should be self explanatory, but the modulo operator may be new. This operator returns the remainder after the second operand has been divided by the first. For example, 4 goes into 10 twice with 2 left over – 10 % 4 = 2.

    You can use these operands to perform mathematical operations on variables like so:

    currentYear - age = birthYear;

    Concatenation

    The + symbol is a special operator, its function depends on the context. When used with two numerical values, the two values are added together:

    operand + operand = sum;

    However, if either of the values are a String, then the values are “concatenated”, which basically means combined into one.

    string + string = stringstring;

    Commenting your Code

    Comments are text that you place in your code that gets ignored by the compiler. They are intended to be  hints, instructions, and explanations to yourself and other developers about the code, what it is for, what it does, why you did it that way, etc. A single line comment looks like this:

    // I am a single-line comment. Hi there!

    A multi-line, or block comment looks like this:

    /* I am a block comment

    and I take up multiple lines */

    Homework

    In the Actions Panel, using variables and the trace function, create your own Mad Lib, using variables to store the blank nouns, verbs, adjectives and adverbs, etc. Include the following:

    • At least 6 variables
    • At least one of each datatype: String, Number, Boolean
    • At least one mathematical calculation using Number variables
    • To turn in your homework, zip  your .fla file, upload it, and link it to your blog / homework page

    Week 7: Intro to Flash

    October 20th, 2009
    • Intro to Flash
      • Creating a New Flash Document
      • Understanding the Flash Workspace
      • Setting Document Preferences and Properties
      • Help System
      • Panels
        • Timeline
        • Properties
        • Tools
        • Library
      • Drawing Objects on the Stage
      • Working With Text
      • Symbols
        • Types of Symbols
      • Importing Assets into the Library
      • Layers
        • Using Layers
        • Layer Modes
      • Animation
        • Frames and Keyframes
        • Tweening
          • Motion
          • Shape
          • Classic
        • Easing
        • Motion Paths
      • Testing your Flash Movie
      • Publishing your Flash Movie

    Resources

    Homework

    Create a 20-30 second flash movie that has at least six layers and at least four animated elements. Include both Shape and Motion Tweens. Animate position, rotation, color, alpha. Use both elements that you draw in Flash and those that you import into the library. Have Fun!!!

    Week 6: Work Session

    October 15th, 2009

    No new homework this week, so it’s a good time to catch up if you are behind!

    Week 5: CSS Image Replacement, Intro to JavaScript

    October 6th, 2009
    • Rounded Corner Boxes
    • Image Replacement Techniques
    • Creating a rollover menu from a single image
    • JavaScript Basics

    Rounded Corner Boxes

    This is an html page makes use of a very small background graphic to create a full page gradient effect and one method of creating rounded corners on a content box.

    More CSS Image Techniques:

    Thinking through your images:

    Foreground vs. Background Images. The best way to think about this is as a picture and a frame. Background images are the frame, foreground images are the picture. Background images should be restricted to interface elements, foreground images to content.

    Live Text vs. Graphic Text. In order to keep your pages as semantic and machine readable as possible, not to mention keeping download time to a minimum, it is important to use as much “live” text as possible. However, there are times when you don’t want to be limited to the web safe fonts. Today we’re going to explore a few ways that you can get the best of both worlds.

    There are three techniques displayed in this example:

    • Image with background color rollover
    • Head tag replacement
    • Single Image Navigation Rollover

    JavaScript Basics

    JavaScript is an object-oriented scripting language. It is a client-side language, which means that the code is processed after the page is loaded on the browser.

    Basic syntax

    • Code lines should end in a semi-colon (;) unless the line ends in a block delimiter ({ and })
    • Blocks of code (such as if/then statements) should be enclosed by braces ({ and })
    • Although not required, it’s a good idea to declare your variables explicitly
    • Using functions to define code fragments allows you to reuse code
    • Like CSS, JavaScript can be embedded in your html or used as an external file

    Variables

    Like most programming languages, JavaScript allows you to define variables of a number of types. To declare a variable, use the following syntax:

    var name = "variable_name";

    Functions

    Built-in Functions

    There are a number of functions built-in to JavaScript. You can find a list of them at W3schools.

    User-defined Functions

    You can also create your own functions. User-defined functions use the following syntax:

    function functionname (argument1, argument2) {
         function codereturn value_to_return
    }

    You can then call the function later in your code:

     functionname (argumentvalue1, argumentvalue2);

    Arguments are values that you that you pass in when you call a function.


    Objects

    The document object model or DOM allows you access to document objects. The syntax for the DOM is as follows:

    document.element_in_document.sub-element_of_element

    Events and event handlers

    An event is an action taken by the user (such as moving the mouse) or by the browser (such as finishing a page load). Any input can generate an event that JavaScript can react to. You can see a complete list of Javascript links here: JavaScript Event Reference


    JavaScript Examples

    Popup windows

    New windows are created with the JavaScript window.open function. The window.open function is invoked like this:

    window.open(url, name, optional parameters);

    The parameters that are passed between the parentheses are defined as folllows:

    • url: any url, relative or absolute name: name of the new window parameters: instructions for how the pop-up will display
    • top: distance of pop-up from top of screen in pixels
    • left: distance of pop-up from left of screen in pixels
    • width: width of the new window in pixels
    • height: height of new window in pixels
    • location: (1/0 or yes/no) show or hide the location bar (where urls appear)
    • toolbar: (1/0 or yes/no) determines whether or not the toolbar buttons (back, forward, home, etc.) show up
    • menubar: (1/0 or yes/no) show or hide the menu bar
    • status: (1/0 or yes/no) show or hide status bar at the bottom of the page
    • resizable: (1/0 or yes/no) 1 or yes allows users to resize the window
    • scrollbars: (1/0 or yes/no) determines whether scrollbars appear in window

    A basic pop-up function:

    This code would go in an external document or in the <head> section of your html:

    <script type="text/javascript">
    <!--
    function popUp(URL,name,w,h){
         myW = 'width=' + w + ',';
         myH = 'height=' + h + ',';
         params = 'toolbars=1, scrollbars=0, location=0,statusbars=0, menubars=1, resizable=1,';
         window.open(URL,name,myW + myH + params);
    }
    -->
    </script>

    Or you can put this code, without the script tags, into another document, and include it, also in the head tag of your html, like this:

    <script type="text/javascript" src="popUp.js"></script>

    To use the function, you invoke from within an anchor tag, using a mouse event such as onclick:

    <a href="myfilename.html" onClick="popUp(this.href,'myWindow','550','450'); return false;">

    Popup Example


    Multiple Image Rollovers

    In the popup example above, there is an example page where the user action of mousing over a thumbnail causes the larger image to change. Let’s take a look at this:

    Image Gallery example

    The first part of the JavaScript that makes this work is the script in the head tag of the document:

    <!-- This code was adapted from Jeremy Keith's JavaScript Image Gallery at http://www.alistapart.com/articles/imagegallery/ -->
    <script type=“text/javascript” language=“javascript”>
    function showPic (whichpic) {
          if (document.getElementById) {
               document.getElementById('fullimg').src = whichpic.href;
               if (whichpic.title) {
               document.getElementById('caption').childNodes[0].nodeValue = whichpic.title;
          } else {
               document.getElementById('caption').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
        }
          return false;
       } else {
          return true;
       }
     }
     </script>

    This function, showPic, describes how the images and captions should be loaded when the function is invoked.

    Next, we add a div into the html that is hidden using the display:none style. This allows us to preload the image so that there is no delay on the rollover.

    <!-- Use a hidden div to preload the images -->
    <div style="display:none">
      <img src="images/1.jpg" />
      <img src="images/2.jpg" />
      <img src="images/3.jpg" />
      <img src="images/4.jpg" />
    </div>

    Last, we create the code that will display the images on the page:

    <div id="container">
    <div id="leftcol">
      <ul>
    <!-- The onmouseover event calls the showPic function -->
        <li><a onmouseover="return showPic(this)" href="images/1.jpg" title="Saharan on Sunset"><img src="images/th_1.jpg" alt="image 1" width="65" height="65" border="0" /></a></li>
        <li><a onmouseover="return showPic(this)" href="images/2.jpg" title="Sedona Skyline"><img src="images/th_2.jpg" alt="image 2" width="65" height="65" border="0" /></a></li>
        <li><a onmouseover="return showPic(this)" href="images/3.jpg" title="Cape Cod Beach Fence"><img src="images/th_3.jpg" alt="image 3" width="65" height="65" border="0" /></a></li>
        <li><a onmouseover="return showPic(this)" href="images/4.jpg" title="Unguarded Area"><img src="images/th_4.jpg" alt="image 4" width="65" height="65" border="0" /></a></li>
      </ul>
    </div>
    <div id="rightcol">
      <img id="fullimg" src="images/1.jpg" width="400" height="300" border="0" alt="image 1"/>
      <h2 id="caption">Saharan on Sunset</h2>
    </div>
    <div id="kicker"></div>
    </div>

    Reading

    This is a good general resource for JavaScript:

    DOM Scripting: Web Design with JavaScript and the Document Object Model
    by Jeremy Keith, Friends of Ed

    Homework

    1. Take last week’s 50 states homework, and add rounded corners to at least one of the divs.
    2. Create your own single-image rollover menu like the example we went over in class today
    3. Create a rollover image gallery like the Javascript example, using your own images.

    Week 4: Images, Advanced CSS

    September 21st, 2009
    • Working With Images
      • Image File Formats
      • Image Size
      • Saving Images out of Photoshop/Illustrator
      • Using the image tag
      • Using images as links
      • Background images
      • Making a simple thumbnail gallery
    • Advanced CSS
      • Understanding the Document Tree
      • Selector Types
      • Cascade, Specificity and Inheritance
      • Styling Links
      • Styling Lists
      • Background Images

    Image File Formats

    There are three primary image file formats used for graphics viewed on the web. Each of these file types were designed for the purpose of compressing memory usage. Each file type does this a different way.

    • Jpeg
    • Jpegs work well on photographs, naturalistic artwork, and similar material; not so well on lettering, simple cartoons, or line drawings. JPEG is “lossy,” meaning that the decompressed image isn’t quite the same as the one you started with. (There are lossless image compression algorithms, but JPEG achieves much greater compression than is possible with lossless methods.) JPEG is designed to exploit known limitations of the human eye, notably the fact that small color changes are perceived less accurately than small changes in brightness.

    • Gif
    • Graphics Interchange Format. A format used for displaying bitmap images on World Wide Web pages, usually called a “gif” because .gif is the filename extension. These files use “lossless” compression and can have up to 256 colors.

    • Png-8 and Png-24
    • PNG is a compression scheme that has two main benefits: it is a lossless compression image format and it holds alpha channel information. Originally, the Portable Network Graphics (PNG) format was designed as a royalty-free format, which would replace GIF and JPEG. Png-24 allows for smooth blending between alpha and opaque.


    Image Size

    When speaking about image size on the web, there are three possible interpretations of this that you must take into account.

    • File Size refers to the amount of disk space an image occupies (in KB or MB)
    • Image Dimensions refers to the physical size of the image, expressed in height and width.
    • Resolution refers the pixel density of an image. This is expressed in pixels per inch (ppi). Images are displayed on the web at 72 dpi. Printed images are generally of higher resolution.

    Saving images out of Photoshop or Illustrator

    Both Photoshop and Illustrator have excellent options for optimizing images for the Web, via the “Save for Web” menu. It is better to use this option rather than “Save As” or “Export” options, as you will have more control over the output settings and the final file size will be smaller because no preview image is saved with the file.


    Adding images to your pages

    Image tag

    Images are displayed on the web using the image tag:
    <img>

    This is the basic syntax for using the image tag:
    <img src="image_name" />

    The “alt” attribute is used for the text that will display if an image does not load in the browser, and in some browsers is visible when you hover over the image with the mouse:
    <img src="image_name" alt="alt_text" />

    The image tag also allows you to input a numeric value for the height and width of an image. It is a good idea to specify the height and width, as this allows the browser to render the page faster.
    <img src="image_name” height=”height” width=”width” />


    Images as Links

    You can use an image to link to another document by simply wrapping an image tag in a link tag:
    <a href="filename.html”><img src=”image_name“></a>


    Background Images

    You can set an image as a background in any page element. The properties of background images are detailed here:


    A Simple Thumbnail Gallery

    This method creates a flexible grid of thumbnail images and captions that dynamically fills rows based on the browser width. This is what it looks like in action:

    Each thumbnail and caption is part of an unordered list (ul) with the id “thumbnails”. The list items (li) are set to display:inline and float:left and have background, margin and padding set to create the white boxes around them.


    Advanced CSS Application:

    Selector types:

    Cascade, Specificity and Inheritance


    Styling Links

    Using the pseudo classes related to the anchor tag, you can apply a wide variety of styles. Let’s look at two examples on W3schools:


    Styling Lists

    The <ul> and <ol> list constructs are highly styleable and useful for a wide variety of purposes. Let’s look more specifically today at what we can do with them:


    Background Images

    Now that you know how to include images in your HTML, you should also know that you can use an image as a background in any element.


    Horizontally Centered Layouts

    Because browsers implement centering differently, in order to center any element on the page, you must use two methods. Any element that has “text-align: center” will center in IE, but Firefox and Safari only use this attribute for text. To center an element for those browsers, you must use the “auto” value for your left and right margins:

    element { text-align: center; margin: 0px auto; width: 800px }


    Homework | Week 4

    1. Thumbnail Gallery
      1. Take any 15 images. They can be photos, your artwork, anything. Create two different sizes of these images, one thumbnail image and one full size image. The full size image should not exceed 800×600 pixels. Use the “Save for Web” process to optimize the images, saving them in the file format most appropriate for each image. Save these images to the “images” folder you created in week two.
      2. Create HTML / CSS using the thumbnail size of the images that duplicates the functionality of the thumbnail gallery that we went over in class today.
      3. Take the thumbnail gallery one step further – link each thumbnail to its full sized image.
      4. Post the files and images to your server.
    2. Using this HTML Document create a CSS stylesheet that applies different background colors, heading, link, and list styles for each of the three divs. Lay out the page however you wish. Also, apply a background image to at least one element on the page. The more properties you manipulate, the more credit you will get for this assignment.

    Week 3: Intro to CSS, CSS Positioning

    September 15th, 2009
    • Homework Review
    • Commenting and Formatting Your Code
    • Color in HTML
    • Web Safe Fonts
    • Intro to Cascading Style Sheets
      • What is CSS?
      • The Box Model
      • CSS Syntax
      • Classes and IDs
      • Three ways to use style sheets
      • Manipulating Basic CSS Properties
    • Box Model Quirks
    • Intro to CSS Positioning
      • Absolute
      • Relative
      • Fixed
      • Floats
    • Browser Testing

    Commenting your Code

    You can place a comment tag in your HTML to put a note into the code that will not be rendered by the browser. This is especially handy in a long and complex page. A comment is formatted as follows:
    <!-- This is a comment -->

    Everything between the <!– and –> tags will be hidden from the browser, but visible when you view the source.


    Color

    All color in Web pages, whether it is in text, background color, or other interface elements, is expressed in the HTML via hexidecimal codes. These codes consist of a # followed by 6 letters and numbers. For example, the code for white is #FFFFFF.

    Below are two excellent references for the hex codes for the Web-safe palette. The Web-safe palette is a collection of colors that have been determined to be consistently rendered across boundaries.

    Webmonkey Color Code Chart
    Visibone Webmaster’s Palette


    Fonts

    Because a Web browser can only utilize those fonts installed on the end-user’s machine, there are a limited number of fonts reliably available across platforms. Here’s an up-to-date list of them:

    Web Safe Fonts for Mac & PC

    You should only use these fonts, or generic font designations, in your style sheets.

    Here is a great resource for viewing how Web fonts will look in a browswer:

    Typetester


    What is CSS?

    • Cascading Style Sheets (CSS) are a standard developed to allow designers control over presentational elements of a Web page and effectively separate content from presentation.
    • A style is a group of attributes that are called by a single name.
    • A style sheet is a group of styles.
    • The cascade part of CSS means that more than one stylesheet can be attached to a document, and all of them can influence the presentation. It also means that different applications of CSS can be applied to a page in order of precedence: inline, embedded, external and default.

    The CSS Box Model, Types of Elements

    The three types of HTML elements to apply styles to:

    An important concept to understand is that there are basically three types of HTML tags: block-level elements, inline elements, and replaced tags.

    1. Think of block-level elements as boxes that have a line break before and after. Block-level elements are the ones you will spend most of your time applying style rules to, or manipulating with scripting. They include h1-h6, p, div, ul, ol, blockquote.
    2. Inline elements on the other hand, don’t have line breaks before and after. Inline elements are used in the middle of another element, and include a, b, strong, italic, em, span
    3. The third kind of HTML tag is called a replaced tag. What it means is simply that these elements have a set width and height. The most-used replaced tag is the <img> tag, which you must specify a height and width for.

    If an element is not explicitly defined, it is known as an anonymous element. You will not be able to style this element directly.


    CSS Syntax

    The CSS syntax is a little different from the tag and attribute format of HTML. A CSS style is made up of a selector, which is the HTML element or class name you wish to define rules for, and a set of properties and values. A property and its value are separated by a colon (:). You can define multiple properties for a style, separating them with a semi-colon(;). Property/value sets are enclosed in brackets{}.

    For example, if you wanted to redefine all HTML in your <p> tags to look like this, then your style would look like this:

    p {
    color: #00CC00;
    font-size: 13px;
    font-family: "Courier New", Courier, monospace;
    font-weight: bold; text-decoration:none;
    }

    The order of properties doesn’t matter, as long as you separate them with a semi-colon. Property values that have multiple words are surrounded by double quotes: “Courier New”.

    You can apply the same style to multiple selectors by grouping them:

    h1, h2, h3, h4 {
    color: #00CC00
    }

    There is a full CSS reference and extensive code examples at:

    W3 Schools CSS Tutorial


    Sizing in CSS

    There are a number of different measurement schemas within xHTML / CSS. Which one to use depends on context, and you can mix and match them.

    • px – number of pixels, relative to the screen size. This is the most consistent across machines, browsers, monitors
    • %percentage of the total width or height
    • em – size relative to the em size of the base font

    We will go into when it is appropriate to use the various schemes in later weeks. For now, use the px units in your stylesheets.


    Classes and IDS

    Classes and Ids are a way to designate specific elements in your HTML. You can apply either a class or id or both to any element:

    <div id="navigation">

    <p class ="main" id="introduction">

    There is one key difference between a classes and ids:

    • IDs can only be applied to one element per page
    • Classes can be applied to multiple elements per page

    When naming classes and ids, it is good practice to name them logically and semantically. The names should not describe the physical attributes of the style you plan to apply to them, but the type of thing that they are in the structure of your page. For example, if you have a unordered list of links that will serve as your navigation, this:

    <ul id = "navigation">

    is better than this:

    <ul id = "top">

    The reason for this once again we want to separate the structure from the presentation. Naming your classes and ids logically means that if you radically change the color scheme or layout defined by your style sheet, the structure will still make sense.


    3 Ways to use style sheets

    There are three methods of accessing style sheets from your HTML:

    1. Inline as part of an HTML tag.
    2. Embedded in the <head> section of your page between <style></style> tags
    3. In an external document that is linked to the page

    Here is an example of a page that uses inline and embedded styles:

    We are going to focus primarily on using external style sheets. The are a couple of advantages to this. First, you can apply the same styles to some or all pages of your site. Second, you can make a change on the external style sheet and all the pages it is linked to will change. And last, with a simple change to your code, you can switch style sheets and completely alter the look of your page.

    Style sheets work in 4.x or later browsers (but still not consistently) such as Navigator 4.5 or 6 and IE 4 or 5. Most earlier browsers ignore them.

    A good place to see style sheets in action, and to really understand how powerful they are, is the CSS Zen Garden.


    Creating and linking to your own external style sheet

    An external style sheet is a plain text document containing all the style declarations you wish to apply to the linked pages. It does not have the structural tags (html, head, body) that your HTML documents have.
    Once you have created your style sheet, you can associate it with your page using the link tag in your HTML, placed between the <head> tags:

    <link href="my_style_sheet.css" rel="stylesheet" type="text/css"/>

    Resume with Linked Style sheet


    Manipulating Basic CSS Properties


    Box Model Quirks

    There are a few things that it is important to understand about the box model. This was in the reading, but let’s review.

    Width Differences

    Mozilla Browsers, Internet Explorer 7+

    In most browsers, the width value of a box includes only the content of the box, and the left-right padding, border, and margin values are added to that to calculate the total width the element occupies on the page.

    Normal Box Model

    IE 6 and below

    In Internet Explorer versions 6 and below, the width includes the content, padding, and border of the element – that is, everything inside the box.

    IE Box Model

    Margin Collapse

    In non-IE browsers, when elements are stacked on top of each other, their vertical margins collapse into the larger margin of the two.

    Stacked Margin Collapse

    The same is true of nested elements, if there is no border or padding between them.

    Nested Margin Collapse


    Intro To CSS Positioning

    You read about the various types of CSS positioning, now let’s look at some examples.  We’re going to look a page with the same HTML and a number of alternate stylesheets attached. You can read more about alternate stylesheets here.

    Normal Flow

    If no positioning is specified, a document is rendered with Normal or Static Flow. All boxes are drawn from left to right, top to bottom, stacked in the browser window.

    Relative Positioning

    Relatively positioned elements are placed relative to their place in the normal flow.
    position: relative; top: 20px; left: 20px

    Relative Positioning

    Absolute Positioning

    This takes the element and its children out of the normal flow. An absolutely positioned element is positioned relative to its parent. If the parent is not absolutely positioned, the element will be positioned relative to the browser window edges:

    position: absolute; top: 20px; left: 20px

    Absolute Positioning

    Fixed Positioning

    This is a subset of absolute positioning, in which the element remains in place relative to the edge of the browser window as it is resized or scrolled:

    position: fixed; top: 20px; right: 20px

    Floating and Clearing

    Setting a float on an element causes it to “float” to the left or right of the containing element. This takes the element out of the normal flow, and as a result, other elements act as if it is not there. To avoid overlap of following elements, you must put a clear attribute in their style, either clearing floats on the left, right, or both:

    float: left;
    float: right;
    clear: left;
    clear: right;
    clear: both;

    Float Positioning


    Browser Testing

    The quirks of the box model are just the tip of the iceberg as far as differences in how the browsers interpret your CSS and HTML. So its important that you test your pages in all the major browsers to ensure a consistent user experience.

    For the purposes of this class, for all work that you do from this point on, I will require that your pages have a consistent appearance across the following browsers:

    • Safari (Mac)
    • Firefox (Mac and PC)
    • Internet Explorer 6 and 7 (PC)

    In an ideal situation, you will be able to develop and test with access to both a Mac and PC. However, since life is rarely ideal, fortunately there is Browsershots, a free screen grabbing service that will capture screenshots of any URL you feed in for selected browsers.


    Homework | Week 3

    1. Using all the properties we have covered today, create a single, external stylesheet and apply it to your resume pages. Manipulate the colors, fonts, borders, positioning of the elements, etc. Create additional divs or spans, or apply classes and ids, as necessary. Make it look good, a real representation of your style and taste. The more you put into your stylesheet, the more credit you will get for the assignment.
    2. Using the positioning models we learned today, create pages with layouts as close to the following examples as possible. Use only HTML and CSS to create these layouts (no tables or images!)
    3. Upload your new homework files and create a post on your blog with links to them.

    Week 2: SFTP, Blogs, Links, Intro to CSS

    September 7th, 2009
    • Uploading your files using FTP/SFTP
    • Setting up your WordPress blog
    • Manage your Site: Remote vs. Local File Systems
    • Linking files
    • Tools and Best Practices
      • Web Developer Add-ons
      • Validating your Code

    Uploading your files using FTP/SFTP

    Your html files are uploaded to the Web server using FTP, or File Transfer Protocol. You will need an FTP client to do this. If you are using the A server, you will need a program that supports SFTP, or Secure File Transfer Protocol. Here are likes to some popular programs:

    All these programs function essentially the same. To connect to your remote server, you enter the address of the FTP server, your username and password.

    The A server FTP address is:
    a.parsons.edu

    Once you are logged in to the server, you will see a listing of the directories and files on your remote server. Some FTP clients also allow you to browse your local files as well. You can now upload and download files to and from your remote server via the FTP client’s interface.

    Important: On the A server, in order for your files to be visible in a Web browser, you must upload them to the public_html directory (or any subdirectory under it)


    Setting Up Your Wordpress Blogs

    1. Download Wordpress
    2. Create the database
    3. Edit the config file
    4. Upload Wordpress files
    5. Install Wordpress
    6. Log In
    7. Changing Your Password
    8. Posts vs. Pages
    9. Settings
    10. Themes

    Manage your Site: Remote vs. Local File Systems

    When we build a Web site, we develop them on our local (or “desktop”) machine, and publish them to a remote “Web server”. A Web server is a computer that is essentially the same as your desktop machine, but has server software installed that allows it to take http requests from an internet user’s computer (or “client”), and deliver the requested html document to the user’s browser. This client / server relationship is the basis of all Web activity.

    What we call a “site” is really just a collection of html documents that we associate via internal references (links) between them. In order to keep your site organized, and to ensure that it functions exactly the same online as on your desktop, you must keep the file and directory structure exactly the same on the local and remote machines.

    The first step in doing this is to organize your local file structure. First, create a “root” folder on your local machine or flash drive from which you are going to work. I suggest using something like your A server username.

    Within your root directory, create two subdirectories:

    • working_files
    • public_html

    From now on, the “working_files” directory will hold documents and images that you use as resource files for building your site, but not any files that will uploaded to the site itself. Put the resume text file that you brought today into this directory.

    The “public_html” directory will contain all files that will actually become part of your site. Upload the resume html file that you created as homework in that directory now.

    Within the html directory, also create a subdirectory called:

    • images

    We will use this directory later in the course to store any images that will appear in your Web site.


    Linking files

    File linking is done through the use of the <a> or anchor tag.

    Use the following syntax for linking to another document:

    <a href="URL_of_target_document">link_text</a>

    For example, if you were to link to Google, you would use the following code:

    <a href="http://www.google.com/">Google</a>

    To link to an email address, which will spawn the user’s designated email client, you simply need to add the “mailto” parameter:

    <a href="mailto:emailaddress@server.com">email_text</a>

    You may also link to “anchors” in the same file.

    To do this, you must create both the link:

    <a href="filename.html#anchor_name">anchor_text</a>

    and the anchor to link to:

    <a name="anchor_name">anchor_text</a>

    Absolute vs. relative links

    When citing the URL of the target document, you may use an “absolute” or “relative” path.

    An “absolute” path is the full web address of the document, with protocol. This path will not change depending on the document that is linking to it. This type of link is primarily used when you are linking to an address that is external to the site you are linking from.

    For example, the absolute path of this site is:

    http://classes.catherinegarnier.com/fall07/intro_to_web

    A “relative” path is one where the information is given relative to the document on which the link appears. This type of linking will only work within a given site directory, it can not be used for external URLs.

    With relative links, you must be aware of where the document is located in the file directory in relation to the file being linked to.

    In the same directory:

    filename.html

    In a lower (sub) directory:

    subdir_name/filename.html

    In a higher (parent) directory:

    ../filename.html

    Relative to the site root:

    /filename.html

    (note: it is unusual to use paths relative to the site root)

    Link targets

    Unless instructed otherwise, a Web browser will open a target document in the same window as the linking document. The user of the “target” attribute allows you to direct the target document to an alternate window. Some of the attributes below only apply to framesets, which we will cover briefly later in the course.

    Target Attribute Values

    _blank Opens the linked document in a new window
    _self Opens the linked document in the same frame as the link
    _parent Opens the linked document in the parent frameset
    _top Opens the linked document in the main browser window, replacing all frames
    name Opens the linked document in the window with the specified name


    Web Developer Add-Ons

    There is an excellent suite of Firefox add-ons that will help you in your site development. We’re going to install them now, and I highly recommend that you install them on your home machine:

    As the course goes on, we are going to learn to use the various tools included in the suite.


    Validating Your Code

    It is essential to make sure that you are writing valid xHTML code. Improperly formatted code can cause your pages to render in unpredictable ways or not at all in various browsers.

    The W3C offers a free validator that you can run any html page through:

    You can also access the validator through the “Tools” menu in the Web developer toolbar.


    Homework | Week 2

    1. Customize your new Wordpress blog with the theme of your choice. Create a category for posts related to this class.
    2. Run your resume html through the HTML validator. Resolve any errors and then upload it to your A server account
    3. Create an index file for your A server site. You can do anything you want with this page, but it should have at least a link to your blog on it.
    4. Create a post on your blog with a link to your resume file
    5. If you haven’t already done so, post your A server address to the comments of this post