Actionscript to Reference Dynamically created instances Flash Movie Clip | Array notation | Tutorial

Overview:

Often I’ve had some dynamically created movieclip and then wanted to reference it in my code. This is hard to do if it is named dynamically as well, such as with an incrementing variable. If you use one (or more) variable to name an instance in run time, you can’t always know what it will be called.
There are two ways (that I know of) to reference these clips, one is the array operator [] and the other is using the eval() function is as2 (but I’ve noticed that as3 has removed the eval function, so I’d recommend getting used to array notation).

Steps:

  1. Create the object dynamically (or with a variable) (_root.myClip.duplicateMovieClip (“myClip”+i, i);)
  2. Reference it with either array notation or with eval. (thisOne = _root[“myClip”+i];) or (eval(“myClip” + i))

Example:

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/07/reference-dynamically-named-clips.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”500″]

Get Adobe Flash player

[/kml_flashembed]

I create some movie clips dynamically using a for loop and name them all incrementally with a variable (myClip+i). But then i want to refer to some of them later, specifically. I don’t know what they are named though. They are all myClip1 myClip2 myClip3 and so on. I can use array notation to reference these (or eval). I’ve found it’s easiest to create a reference to the name once and then use it to refer to the clip I want. I imagined a scenario that when you click a mc you would want a different one to be moved. So clicking myClip3 moves myClip4 and so on. I’ve made it wrap so that 5 moves 1… They change the _y property of the next to match the one that’s clicked. Clicking the refresh button will loop through all the clips and (this time using eval) randomize the y coordinate.

Actionscript:

[cc lang=”actionscript” tab_size=”2″ lines=”40″]

var myLimit = 5;
//myClip._visible = false;

for(var i=1; i<=myLimit; i++) {
_root.myClip.duplicateMovieClip (“myClip”+i, i);

thisOne = _root[“myClip”+i];
thisOne._y = Math.random() * Stage.height;
thisOne._x = Stage.width/(myLimit+1) * i ;
thisOne.id = i;
thisOne.idDisplay.text = i;

thisOne.onRelease = function() {
nextOne = (this.id == myLimit) ? _root[“myClip”+1]: _root[“myClip”+(this.id+1)];
nextOne._y = this._y;
}
}

myClip.onRelease = function() {
for (var i=1; i<=myLimit; i++) {
eval(“myClip” + i)._y = Math.random() * Stage.height;
}
}

[/cc]

Download:

Source fla file: download

Reference:

Nuno Mira shows a good example:

[cc lang=”actionscript”]
this.createEmptyMovieClip(“outer_mc”, 1); // create a mc called outer_mc
outer_mc.createEmptyMovieClip(“inner_mc”, 1); // create a mc called inner_mc inside outer_mc
// 3 different ways of targeting inner_mc
trace(outer_mc.inner_mc);
trace(outer_mc[“inner_mc”]);
trace(this[“outer_mc”][“inner_mc”]);
// all output _level0.outer_mc.inner_mc
[/cc]

TheCanadian@Kirupa states it nicely:
The Problem
How can I reference objects using a variable? This is commonly a problem with dynamically created buttons:

ActionScript Code:
for(i = 0; i < 3; i++) { button+i.someProp = "Hello World!"; //error }

The Answer
This is probably the question that gets asked the most. Referencing an object with a variable is done using something called associative array referencing or array notation. The fundamental concept behind this is that:

ActionScript Code:
myObject.prop = "value"; //and myObject["prop"] = "value";

Are the same thing. Associative array referencing follows the pattern of scope[“prop”] where scope is the object which contains the property and prop is the name of the property you wish to reference. Save appearance, array notation works in exactly the same way as dot notation.

Going back to the original, problematic, example, the correct code would look like this:

ActionScript Code:
for(i = 0; i < 3; i++) { this["button"+i].someProp = "Hello World!"; }

The button string is concatenated (joined) with the i variable, forming a new reference with each iteration of the loop. First button0, then button1, et cetera.

That’s the quick, but some of you may think that that’s the same notation that is used with instances of the Array class. While that is true, the converse is actually more correct: Array instances use that notation.

Arrays are exactly the same as generic Objects, the only difference is that they have a collection of methods to deal with their properties. And because they require a need for organization, they typically only use numerical properties. Given the array myArray = [“a”, “b”, “c”], you could theoretically reference the indices using myArray.0, myArray.1 and myArray.2. The reason that we must use array notation is because the compiler doesn’t allow the reference of numerical properties with dot notation.

StomperTools: Ranker & Scrutinize This

StomperTools Plugin

StomperLabs is proud to announce another cool, FREE software tool. The StomperTools Firefox plug in! We’re going to pack many tools into this plugin in the future, but to start it off we’ve bundled two functions into this plug in.

ranker logo

StomperNet Ranker

The first is called StomperNet Ranker, and it allows your prospects to quickly survey the rankings for a keyword query. We built an interactive graphical representation of a search showing results from three top search engines: Google, Yahoo and MSN.
snranker page

How to use StomperNet Ranker?

I’ll give an example… Here’s the page as it loads a search for ‘circlecube’. The green nodes represent Google results, red is Yahoo, and blue is MSN. Each result that is for an identical page is connected with a thin line, and when you hover over a node it will grow and also any nodes for identical pages. Nodes for same domain pages will grow slightly as well to give an idea of the saturation on the search results by the specific domain. Below you can see that I’m hovering over the top-left node (the screen shot helpfully removed my cursor), the title of the page is shown and you can see that the same page (my home page) ir ranked number 1 in Google and MSN (hence the line connecting them, and also they have both grown to be large nodes). Also notice that pages of the same domain (circlecube.com) are at the top 2 slots in Google, the top 3 in Yahoo, and the top 2 in MSN (the medium sized nodes). Hovering over a node displays information to the right of the node chart. Clicking on a node loads that url below the ranker ui. You can also click the Google, Yahoo, and MSN buttons above the chart to see the actual search results at each engine specifically.
snranker closeup
Ranker had the potential to become a great comparative tool for search engine optimization and comparison.

scrutinizer logo

Scrutinize This

Not only does StomperTools give you access to Ranker right in your browser, but also you can instantly “Scrutinize” any page you’re viewing right from the browser (once you have the Stomper Scrutinizer tool, so go get it too!) Use the plug in to seamlessly aim your Scrutinizer browser to whatever page you’re browsing in Firefox.
stomper tools menu

Brownian Movement in Actionscript | Random Motion Tutorial

Overview

Having things drift around or move randomly has always interested me. Having an animation that is never going to be the exact same thing is very exciting. The focus turns from key-ing exact animations to programming a feel and letting the animations take car of themselves! One type of seemingly random motion is Brownian motion. This gives the movement a random walk wandering look, it will just drift around with no real direction.

Steps

Step by step this process is very simple. In every random motion you create the random number, and apply it to the property. If you want constant random action (motion) rather than just random placement, you repeat that over and over.

  1. Make a random number (random velocity)
  2. Apply the random number (apply velocity to property)
  3. Repeat (if needed)

To create a random number in actionscript, use Math.random(), which creates a random number between 0 and 1. Usually you’ll want to scale it to a range you want to use. If you want a number between 50 and 100, you’d do Math.random() * 50 + 50. *50 to scale it to 0-50, and + 50 to bring it up to 50 – 100. Also if we want to get a 100 range around 0 (-50 – 50) we would do Math.random() * 100 – 50. In the code below I’ve abstracted this to Math.random() * this.randomRange – this.randomRange/2.

Example

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/06/randomMotion.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”500″]

Get Adobe Flash player

[/kml_flashembed]

Here I’ve got dots created and placed randomly, with randomly set scale and alpha. On every frame each dot has a random velocity applied to it’s x and y coordinates.
The yellow dot is the simple example (code below) and the rest are included in the complex example below.

Actionscript

Simple Example:
[cc lang=”actionscript”]
dotOne.onEnterFrame = function() {
//create a random velocity for x and y direction
vx = Math.random() * 4 – 2;
vy = Math.random() * 4 – 2;
//apply velocity to coordinates
this._x += vx;
this._y += vy;
}
[/cc]

Complex example:
[cc lang=”actionscript”]
var numDots = 25;
var randomRange = 1;

for(var i=1; i<=numDots; i++) {
//create a new dot
duplicateMovieClip(_root.dot, “dot”+i, i);
//save it’s ref path for use
theDot = _root[“dot”+i];
//give it random coordinates
theDot._y = Math.random() * Stage.height;
theDot._x = Math.random() * Stage.width;
//give each dot a distinct random range
theDot.randomRange = i/numDots;
//give each dot a random size and transparency
theDot._xscale =
theDot._yscale =
theDot._alpha = i*4;

//apply this code on the dot every frame
theDot.onEnterFrame = function() {
//create a random velocity for x and y direction within the specifically created random range for each dot
vx = Math.random() * this.randomRange – this.randomRange/2;
vy = Math.random() * this.randomRange – this.randomRange/2;
//apply velocity to coordinates
this._x += vx;
this._y += vy;
}
}
[/cc]

Download

randomMotion.fla

Firefox 3 + StomperTools Release and Atlanta Party

Serious internet businesses require serious internet tools.

Firefox 3 is a dramatic step forward! Help Mozilla.org set a Guiness Book record by downloading the new release on Tuesday the 17th of June 2008 (11 AM PST).

To celebrate, StomperNet and Appcelerator are hosting a release party in Atlanta at Park Tavern as a part of a world-wide network of celebration Tuesday, June 17th at 7pm. RSVP at upcoming.org.

Join us if you’re in town, otherwise, check the downloads for Firefox 3:
StomperTools with SN Ranker and Scrutinize this, and the recent Scrutinizer 1.0 release.

Park Tavern
www.parktavern.com
500 10th St Ne
Atlanta, GA 30309
(404) 249-0001

Tuesday, June 17th 2008
7pm-9pm

Get the Stomper Scrutinizer browser vision simulator. Plus get StomperTools … featuring Scrutinize This and the SN Ranker SEO tool.

StomperNet's Scrutinizer Update v1.0

StomperNet‘s Scrutinizer has recieved some updates!

  • New help documentation
  • Keyboard Shortcut Functionality
    • saving a screenshot
    • bookmarking a page
    • toggling the visualization
    • toggle auto-zoom
  • Aesthetic improvements
  • Performance optimizations
  • Improved auto-update.

If you’re wondering what the heck StomperNet‘s Scrutinizer is:

What is it?

The Scrutinizer is a web browser, based upon the Adobe AIR toolkit and the WebKit browser, that offers a simulation of the human visual system. Specifically, it illustrates the distinction between foveal and peripheral vision in visual acuity and color perception. Using this simulation, you can get a better idea of how users interact with your site design. We explain this, and some of the succes we’ve had, in a 30 minute video called Click Fu. It’s also a great tool for observing users interacting with your pages. By slowing them down, the Scrutinizer makes it easier for you to figure out what information the user is consuming and what actions they are considering. Learn about other ways to use the tool at our Top Ten list.

How it Works

The Scrutinizer browser applies a visual filter to where the mouse is located, simulating foveal vision centered around the mouse. For parts of the screen far away from themouse, the display deteriorates into lower resolution, both in detail and color. You can use the browser to get a better understanding of the low level mechanics of how users interact with your site design. Attempting to accomplish a key task on your site using the Scrutinizer can be very enlightening. Watching a user unfamiliar with your site attempt a key task with the Scrutinizer is even better at revealing how your site design affects the way the user extracts meaning from your presentation. Learn more in the Click Fu video, covering practical examples of improved e-commerce, or the 52 second ” Your Vision is an Illusion“, presenting a dramatic illustration of foveal vision. Finally, check out using the Scrutinizer for a findability challenge on Amazon.com.

Top Ten Things You Can Do with the Scrutinizer

  1. Simulate eye tracking in a usability task
  2. Assess the ease of use of multi-step processes
  3. Give your designer a fresh pair of eyes
  4. Find out what “pops� in your design
  5. Conduct findability challenges
  6. Ask: does your visual grid work?
  7. Evaluate your site’s contrast levels
  8. Insure learnability in your template
  9. Avoid button gravity errors
  10. Tell the story of how your eyes work

Calling actionscript functions through HTML text | asfunction Tutorial

Add this to the list of things I should have already known!

Story

I’ve got an html enabled text box and was trying to devise a way that I could have a hyperlink anchor tag not link to a webpage but actually do something flash. It didn’t seem possible, and I looked through all the different html css combinations I could think of. I finally resorted to trying to use some component like Deng or FlashML. FlashML had a smaller footprint and seemed to do more what I wanted, so I started investigating it. To my dismay, the support for it was few and far between. I found an older version that came with an example file and then a newer one with some documentation but no example and I found no examples any where else. So Lee, if you ever read this, some new examples could be nice. In the documentation I was reading about a functino called AddASFunction and the example html line was very interesting:
[cc lang=”html”]
link
[/cc]
I started looking through the rest of the documentation to find this asfunction use. But all it had was:
The href attribute can include the asfunction string which allows the link provided by the anchor to call a function in Flash. More of this can be found within the addASFunction definition in this help document.
I knew I was on to something, asfunction. So a quick google search and I found the official doc! I was shocked that I had the tool to do this the whole time! Well, shocked and feeling like an idiot for never having heard of it before. I knew it could be done somehow, but had no idea that it was already a feature of htmlText in flash! So now that you know my embarrassing story, I’ll let you in on the secret.

Overview

In flash, you can allow html text within a text area. You either set the text html property as true with actionscript (my_txt.html = true;) or click the ‘Render text as HTML’ button in the properties window of the text area. You cannot enable html text on static text areas however. You can have links and various html elements (but not full html). Usually links have a url in the href attribut of the anchor tag, but flash will read a special value of ‘asfunction’ which specifies that an actionscript function is to be called rather than a url. The correct syntax is asfunction followed by a colon and then the name of the actionscript function to be called, optionally followed by a comma and a possible single argument to be passed to the specified function (href=”asfunction:functionName,argument”).

Steps

  1. Enable html in the text box.
  2. Have your function (ex: functionName) ready to be called from the html link.
  3. Give the href attribute of the anchor tag a property “asfunction:functionName,argument” Notice that the official documentation calls for spaces after punctuation, but any space you put after the colon (:) or comma (,) will be sent to the function in the argument, or will expect a space in the function name and give you a headache.

Example

In this example I’ve got an html enabled text box with 4 links. The first is a standard link (I hope you know what that does). The next link calls an actionscript function with asfunction. The third link sends a single argument to another function. And the last link sends multiple arguments to yet another function. Wait! Multiple arguments? I thought I said only one was supported, well this example shows how to send multiple arguments disguised as a single param and parse them. It’s pretty simple actually.
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/05/asfunction.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”375″]

Get Adobe Flash player

[/kml_flashembed]

Actionscript

[cc lang=”actionscript” lines=”40″]
import TextField.StyleSheet;

myHTMLText = “Sample text in an html enabled text box. “+
“Here’s a normal link to circlecube! “+
“And some more links that don’t go anywhere, they call functions in actionscript. “+
Click this one, “+
“to see the actionscript function called from the html text box. “+
Click this too, “+
“and see that the actionscript function you’re calling can have an argument passed to it. And “+
click me three and four “+
“to see a way to send multiple arguments from your htmlText. “+
“Also, one last example of what not to do “+
Click for nothing“;

//create and initialize css
var myCSS:StyleSheet = new StyleSheet();
myCSS.setStyle(“a:link”, {color:’#0000CC’,textDecoration:’none’});
myCSS.setStyle(“a:hover”, {color:’#0000FF’,textDecoration:’underline’});

myHTML.html = true;
myHTML.htmlText = myHTMLText;
myHTML.styleSheet = myCSS;

//function to be called from html text
function clickLink() {
giveFeedback(“Hyperlink clicked!”);
}

//another function to be called from html text, recieves one argument
function clickWithArg(arg) {
giveFeedback(“Hyperlink clicked! Argument: “+arg);
}

//a simple trick to allow passing of multiple arguments
function clickWithMultipleArgs(args) {
giveFeedback(“Hyperlink clicked! Multiple arguments passed: “+args);
argArray = new Array();
argArray = args.split(‘,’);
for (i = 0; i < argArray.length; i++) { giveFeedback("arg "+i+": "+argArray[i]); } }function giveFeedback(str) { trace(str); feedback.text += str +"\n"; feedback.scroll = feedback.maxscroll; } [/cc]

HTML

[cc lang=”html”]
Sample text in an html enabled text box.
Here’s a normal link to circlecube!
And some more links that don’t go anywhere, they call functions in actionscript.
Click this one,
to see the actionscript function called from the html text box.
Click this too,
and see that the actionscript function you’re calling can have an argument passed to it. And
click me three and four
to see a way to send multiple arguments from your htmlText.
Also, one last example of what not to do
Click for nothing
[/cc]

Download Source

asfunction.zip

Intro to Flashvars | Passing variables to actionscript from the html embed | Tutorial

I’ve had a couple special requests to explain flashvars and how to use it and show it in action.

Overview

The property “FlashVars” can be used to import root level variables to the flash movie or swf. The flashvars propery is used in codes for embedding flash in the html page. The string of variables passed in as flashvars, will be imported into the top level of the movie when it is first instantiated. Variables are created before the first frame of the SWF is played. The format of the string is a set of name=value combinations separated by ampersand (&) symbols.

Steps

  1. Include the flashvars property in your embed codes and voila! You have these variables to use in your swf.
  2. That’s the one step

Code

HTML Embed Codes

[cc lang=”html” tab_size=”2″ lines=”40″]
Here’s some sample embed codes, including object and embed tags:

[/cc]

Actionscript using flashvars

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//flashvars=”var1=val1&var2=val2&var3=val3″;

display(“var1 = “+ var1);

display(“var2 = “+ var2);

display(“var3 = “+ var3);

display(“var4 = “+ var4);

function display(todisplay:String){
feedback.text += todisplay+”\n”;
trace(todisplay);
}
[/cc]

Example

Page 1 (var1=val1&var2=val2&var3=val3)
Page 2 (var1=here&var2=are&var3=my&var4=flashvars)

Source

Download the html files and the fla and swf in this flashvars.zip

Using CSS Attribute Selectors to Stylize HTML | Style outbound links | Tutorial

Intro to CSS

We use css to apply styles to certain elements on the page, we can target any div like this:

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Text

[/cc]

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
div {
css-property: value;
}
[/cc]
Any class selector <div class=”divClass”> like this:

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Text

[/cc]
with this:

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
div.divClass {
css-property: value;
}

.divClass {
css-property: value;
}
[/cc]
or any id selector, <div id=”divID”> like this:

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Text

[/cc]
with this:

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
div#divID {
css-property: value;
}

#divID {
css-property: value;
}
[/cc]
These are the basics of css. Use an element tag name to target it, use a dot to access class names and a hash (#) to represent id names. A lot can be done with just that, but sometimes you may want to access something differently, an option is to use attribute selection.

Overview

More advanced we can apply styles to elements based on their attributes. Attribute selectors use the attributes of the tag.
We can use attribute selection to specify certain elements to stylize. For example if we have a page with many images but only certain ones have title attributes, which we want to stand out more, this css rule would do the trick:

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
img [title] {
border: 2px solid #000000;
}
[/cc]
It would cause any image with a title tag (no matter what the value of the title tag is) to have a 2px wide solid black border, such as <img title=”MyImage” src=”/images/sample.jpg” /> or <img title=”” src=”/images/sample.jpg” /> but not <img src=”/images/sample.jpg” /> because it has no title attribute.

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]
would style

or even

but not

because it has no title attribute.
[/cc]

Further we can specify which values of the title attribute we want to target. If we want to stylizee links to a certain site we can do this: a[href=”https://circlecube.com/circlecube”] { }

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[href=”https://circlecube.com/circlecube”] {
background-color: #EBEBEB;
}
[/cc]
it would style <a href=”https://circlecube.com/circlecube”>This link</a> but not <a href=”https://circlecube.com/circlecube/2008/05/21/”>this one</a> because it is not an exact match, nor <a href=”http://www.google.com”>this one</a> because it isn’t a match either, or at all.

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]
it would style
This link
but not
this one
because it is not an exact match, nor
this one
because it isn’t a match either, or at all.
[/cc]

For another example, if we want to stylize local links differently than absolute links, we’d want to look at the beginning of the attribute’s value only so we’d use ‘^=’. We could have something like this:
a[href^=”http://”], a[href^=”https://”] {
background: url(/images/external.gif) no-repeat right center;
padding-right:20px;
}
it would style <a href=”http://www.google.com”>This link</a> because it begins with ‘http://’ but not <a href=”/2008/05/21/”>this one</a> because it is does not begin with ‘http://’. But it would also style <a href=”https://paypal.com”>this</a> because it matches the selector after the comma ‘https://’, and even <a href=”https://circlecube.com/circlecube/2008/05/21/”>this</a> will be styled, because the link is absolute (even though it is local) so be careful with how you use it.

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]
it would style
This link
because it begins with ‘http://’ but not
this one
because it is does not begin with ‘http://’.
But it would also style
this
because it matches the selector after the comma ‘https://’,
and even
this
will be styled, because the link is absolute
(even though it is local) so be careful with how you use it.
[/cc]

Summary

Hoping you will see the pattern and can use the rest of these somehow (I’m drawing blank on interesting examples),

1 is: [attribute] exists

target anchors with any titles attributes.

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title] {
background-color:#0000FF; (blue)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

2 equal: [attribute=x] equals x

target only anchors where the title attribute contains something exactly

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title=”Only”] {
background-color:#FF0000; (red)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

3 hat: [attribute^=x] starts with x

target instances where something comes at the beginning of the attribute. This can prefix a word or even be the first word in a phrase or sentance.

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title^=”Super”] {
background-color:#00FF00; (green)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

4 dollar: [attribute$=x] ends with x

instances where something comes at the end of the attribute. This can be the suffix of the word or the last word in a phrase.

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title$=”ious”] {
background-color:#FFFF00; (yellow)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

5 asterisk: [attribute*=x] contains x

or even titles which contain a certain word somewhere/anywhere in the attribute. This wildcard be anywhere, in a word, as a word, whatever.

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title*=”tic”] {
background-color:#FF00FF; (magenta)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

6 tilde: [attribute~=x] one of which is exactly x.

a space-separated list of “words”, one of which is exactly x.

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title~=”tic”] {
background-color:#FF00FF; (magenta)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

7 pipe: [attribute|=x] which first word is exactly x.

a hyphen-separated list of “words”, first word is exactly x.

CSS

[cc lang=”css” tab_size=”2″ lines=”40″]
a[title|=”Super”] {
background-color:#FF00FF; (magenta)
}
[/cc]

HTML

[cc lang=”html” tab_size=”2″ lines=”40″]

Link

[/cc]

view all examples on this page.
refer to w3 for more

Let me know what you come up with or if I’ve left out any essentials.

Shared Object – utilizing the Flash cookie

Overview

The Shared Object is like a cookie for flash. It lets flash store some data on the local machine, so between sessions it can remember things. Learn more from wikipedia.
Shared Objects are used to store data on the client machine in much the same way that data is stored in a cookie created through a web browser. The data can only be read by movies originating from the same domain that created the Shared Object. This is the only way Macromedia Flash Player can write data to a user’s machine. Shared Objects can not remember a user’s e-mail address or other personal information unless they willingly provide such information.

I’ve seen many Local Shared Object tutorials and examples, which have users input their name and/or hometown and other filler data. But I wanted to show how to creatively incorporate shared objects into interactions. So I’ve thrown in many simultaneous examples including the uber-simple ‘input your name and I’ll remember it’ approach. I hope I didn’t throw in so much that it got confusing… just let me know if you have any questions or anything is unclear. Keeping it simply and broad there’s only a few things to know about Shared Objects.

Steps

    Simply put there are only a couple things to worry about with Local Shared Objects

  • Create them.
    • As in create the shared object
  • Write them.
    • As is write to the shared object
  • Set them.
    • As in setting variables in the shared object
  • Get them.
    • As in getting variables back out of the shared object
  • Clear them.
    • As in clearing the shared objec

Actionscript

here’s samples on how to do each of those
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
/* Create them. */
//make Local Shared Object named myLocalSO(in as) called “myflashcookie” on disk
var myLocalSO:SharedObject = SharedObject.getLocal(“myflashcookie”);

/* Write them. */
//flush the SO, write the SO to disk
myLocalSO.flush();

/* Set them. */
//set key’s value to specified value in SO
//key is the name of the data
//val is key’s value
function setVal(key, val) {
myLocalSO.data[key] = val;
trace(key +” set to “+val);
/* including writing to Shared Object in the setter function */
//flush the SO, write the SO to disk
myLocalSO.flush();
}
/* Get them. */
//get key’s value from SO
function getVal(key) {
return myLocalSO.data[key];
trace(myLocalSO.data[key] +” received from “+key);
}
/* Clear them. */
myLocalSO.clear();
[/cc]

Example

here’s my colorful example.
The purple/yellow circle is draggable, so place it where you want it. Enter your name and age in the input boxes. Press the center red ‘Set cookie’ button to copy those values to the shared object that is on your computer now. The red transparent circle represents the cookie positions. You can position the purple/yellow circle from the cookie contents with the dark green ‘Position from cookie’ button, or position it randomly with the blue ‘Position randomly’ button. Erase the cookie with the orange ‘Erase cookie’ button. Toggle easing (animation) with the Bright green button (which changes to dark red when off), it tells the current mode of ease. I have the cookie coordinates displayed and the current coordinates of the purple/yellow circle also displayed.
The cookie includes a date object, which is used to calculate the age of the cookie (watch it reset when you erase the cookie (orange button)).
The ‘All Time Visit’ stat is the only thing that does not get reset when you erase the cookie,
[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/04/sharedObject.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”300″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

and source code:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//////////////////////// Initialize variables ///////////////////////

//make Local Shared Object named myLocalSO(in as) called “myflashcookie” on disk
var myLocalSO:SharedObject = SharedObject.getLocal(“myflashcookie”);
//speed var for easing
var speed = 3;
var w = myCircle._width/2;
//toggle var for easing
var ease = true;
//as var to store alltime cookie
var allTimeVisitCount=0;
countVisit();
cookieFeedback();
//line style for tracing movement
lineStyle(1, 0, 50);

//////////////////////// Functions ///////////////////////

//set key’s value to specified value in SO
//key is the name of the data
//val is key’s value
function setVal(key, val) {
myLocalSO.data[key] = val;
trace(key +” set to “+val);
//flush the SO, write the SO to disk
myLocalSO.flush();
}
//get key’s value from SO
function getVal(key) {
return myLocalSO.data[key];
trace(myLocalSO.data[key] +” received from “+key);
}

function countVisit() {
//if first visit
if (getVal(‘visitCount’) == undefined) {
//create date for now and store in cookie
var todayDate:Date = new Date();
setVal(‘date’, todayDate);
trace(“creating date”);
//start/reset counting visits
var visitCount = 0;
//notice allTimeVisitCount is not reset, but stored still as a var in actionscript
}

//not first visit
else {
visitCount = getVal(‘visitCount’);
allTimeVisitCount = getVal(‘allTimeVisitCount’);
}
//increment visit counter
setVal(‘visitCount’, visitCount+1);
setVal(‘allTimeVisitCount’, allTimeVisitCount+1);
//feedback of visit counting
visitsFeedback.text = getVal(‘visitCount’);
allTimeVisitsFeedback.text = getVal(‘allTimeVisitCount’);
}
//feedback of cookie contents
function cookieFeedback() {
//in defined print coordinate contents
cookiex.text = getVal(‘circleX’) == undefined ? “no cookie” : getVal(‘circleX’);
cookiey.text = getVal(‘circleY’) == undefined ? “no cookie” : getVal(‘circleY’);

//if not easing assign coordinates from cookie
if (!ease) {
myCookie._x = getVal(‘circleX’);
myCookie._y = getVal(‘circleY’);
}
//set target to cookie coordinates
else {
ctargetx = getVal(‘circleX’);
ctargety = getVal(‘circleY’);
}
//if name then trace cookie contents
if (getVal(‘name’) != undefined) {
visitorFeedback.text = “Returning Visitor”;
nameInput.text = getVal(‘name’);
ageInput.text = getVal(‘age’);
}
//no name then a new visitor
else {
visitorFeedback.text = “First Time Visitor”;
nameInput.text = “”;
ageInput.text = “”;
}
calculateCookieAge();
}
function calculateCookieAge() {
//make a date now
todayDate = new Date();
//get the cookie’s stored date
cookieDate = getVal(‘date’);
//difference between two dates
cookieDateAge = Math.floor(todayDate – cookieDate);
//convert miliseconds to a timecode
cookieAge.text = msToTimeCode(cookieDateAge);cookieDateAge;
}

//convert miliseconds to a hh:mm:ss
function msToTimeCode(ms) {
//make sure value is within bounds. if a number grater than zero and less than the duration of video
if (isNaN(ms) || ms< 0) { ms = 0; } //find seconds var sec = ms/1000; //find minutes var min = Math.floor(sec/60); //adjust seconds sec = sec - min*60; //find hours var hour = Math.floor(min/60); //adjust minutes min = min - hour*60; //floor seconds down to whole number sec = Math.floor(sec); //make time code with hours if (hour == 0) { if (sec < 10) { sec = "0"+sec; } if (min < 10) { min = "0"+min; } var tc = min+":"+sec; } //make time code without hours else { if (sec < 10) { sec = "0"+sec; } if (min < 10) { min = "0"+min; } var tc = hour+":"+min+":"+sec; } return tc; }////// Actionscript attached to Objects/handlers ////////////place data on stage into cookie (circle coordinates and input text) setCookieButton.onRelease = function() { setVal('circleX', myCircle._x); setVal('circleY', myCircle._y); setVal('name', nameInput.text); setVal('age', ageInput.text); //update the display on stage cookieFeedback(); } //make random coordinates on stage randomButton.onRelease = function() { //if not easing assign coordinates to myCircle if (!ease) { myCircle._x = Math.random() * (Stage.width - w); myCircle._y = Math.random() * (Stage.height - w); } //if easing assign coordinates to myCircle's target coords else { targetx = Math.random() * (Stage.width - w); targety = Math.random() * (Stage.height - w); } }myCircle.onPress = function() { this.startDrag(); dragging = true; lineStyle(1, 200, 30); }myCircle.onRelease = myCircle.onReleaseOutside = function() { targetx = this._x; targety = this._y;lineStyle(1, 0, 50);dragging = false; this.stopDrag(); }myCircle.onEnterFrame = function() { //print position feedback currentx.text = this._x; currenty.text = this._y; //if eas move to target if (ease) { if (!dragging) { moveTo(this._x+w, this._y+w); this._x+=(targetx-this._x)/speed; this._y+=(targety-this._y)/speed; } //draw line lineTo(this._x+w, this._y+w); } }myCookie.onEnterFrame = function() { //if ease move cookie to target if (ease) { this._x+=(ctargetx-this._x)/speed; this._y+=(ctargety-this._y)/speed; } calculateCookieAge(); }//Position from Cookie cookieButton.onRelease = function() { //if not easing set coordinates from cookie if (!ease) { myCircle._x = getVal('circleX'); myCircle._y = getVal('circleY'); } //if easing set target coordinates from cookie else { targetx = getVal('circleX'); targety = getVal('circleY'); } } easeBtn.onRelease = function () { //toggle easing ease = !ease; //advance the frame of this button... this.play(); } clearCookieBtn.onRelease = function() { //clear the cookie (swipe all data) myLocalSO.clear(); //restart visit count countVisit(); //read cookie and give feedback cookieFeedback(); } [/cc]

Source

download the source for this example: sharedObject.fla

XML and Flash Actionscript made Easy | Parse XML to Object | Tutorial

XML and flash is something that always seemed to be more complicated than it needed to be. Then I had an idea to parse the xml nodes into actionscript as objects, that would make working with xml tons easier for me, I could just parse it once and then forget about the xml, I could refer to something with the familiar dot syntax rather than worry about firstChild and nextChild and so forth…

This is for AS2. (AS3 has similar functionality built-in via E4X!)

And then I found someone who’d already done that with XML2Object.as, here it is:

[email protected] Class

Actionscript Class:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//////////////////
// – Derived from code written by Alessandro Crugnola – http://www.sephiroth.it/file_detail.php?id=129#
// – Refactored and documented by Phil Powell – http://www.sillydomainname.com
// – 25 July 2006 – Added helper method to sanitize Windows line breaks.
//////////////////
// Convert an XML object to an object with nested properties.
//
// Example usage:
//
// import net.produxion.util.XML2Object;
// var contentObj:Object;
// var xml:XML = new XML();
// var xmlLoaded = function( success:Boolean )
// {
// if( success )
// {
// contentObj = XML2Object.deserialize( this );
// this[‘timeline’].play();
// }
// }
//
// xml.ignoreWhite = true;
// xml[‘timeline’] = this;
// xml.onLoad = xmlLoaded;
// xml.load( ‘some.xml’ );
//
/////////////////
// What do you get back?
//
//
//My Title
// // Here be links!
//http://somewhere.com //http://somewhere-else.com //
//

//
// Becomes:
//
// contentObj.content.title.data => “My Title”
// contentObj.content.links.title.data => “Here be links!”
// contentObj.content.links.link => [Array]
// contentObj.content.links.link[0].data => “http://somewhere.com”
// contentObj.content.attributes.created => “22-May-2006”
/////////////////
class XML2Object {private var _result:Object;
private var _xml:XML;
private var _path:Object;
private static var xml2object:XML2Object;public function XML2Object()
{
this._result = new Object();
}

public static function deserialize( xml:XML ):Object
{
xml2object = new XML2Object();
xml2object.xml = xml;
return xml2object.nodesToProperties();
}

public function get xml():XML
{
return _xml;
}

public function set xml( xml:XML ):Void
{
this._xml = xml;
}

private function nodesToProperties( parent:XMLNode, path:Object, name:String, position:Number ):Object
{
var nodes:Array;
var node:XMLNode;

path == undefined ? path = this._result : path = path[name];
if( parent == undefined) parent = XMLNode( this._xml );

if( parent.hasChildNodes() )
{
nodes = parent.childNodes;
if (position != undefined) path = path[position];

while( nodes.length > 0 )
{
node = XMLNode( nodes.shift() );

if ( node.nodeName != undefined )
{
var obj = new Object();
obj.attributes = node.attributes;
obj.data = sanitizeLineBreaks( node.firstChild.nodeValue );

if( path[node.nodeName] != undefined )
{

if( path[node.nodeName].__proto__ == Array.prototype )
{
path[node.nodeName].push( obj );
}
else
{
var copyObj = path[node.nodeName];
delete path[node.nodeName];
path[node.nodeName] = new Array();
path[node.nodeName].push( copyObj );
path[node.nodeName].push( obj );
}
position = path[node.nodeName].length – 1;
}
else
{
path[node.nodeName] = obj;
position = undefined;
}
name = node.nodeName;
}

if( node.hasChildNodes() )
{
this.nodesToProperties( node, path, name, position );
}
}

}
return this._result;
}

private function sanitizeLineBreaks( raw:String )
{
if( raw.indexOf( “\r\n” ) > -1 )
{
return raw.split( “\r\n” ).join( “\n” );
}
return raw;
}
}
[/cc]

Example:

[kml_flashembed fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/04/xmltoobject.swf” targetclass=”flashmovie” publishmethod=”dynamic” width=”500″ height=”400″]

Get Adobe Flash player

[/kml_flashembed]

Source:

Here is my example file. But since you cant really see Objects in the code on the stage, I’ve included a recursive trace function to loop through the object and print the data.
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import XML2Object;

var xmlObject:Object;
var xml:XML = new XML();

var xmlLoaded = function( success:Boolean ){
if( success ) {
xmlObject = XML2Object.deserialize( this );
this[‘timeline’].play();
recurseTrace(xmlObject, ” “);
myTrace(“\n\n”)
myTrace(“xmlObject.catagories.catagory[10].name.data = “+xmlObject.catagories.catagory[10].name.data);
}
}

xml.ignoreWhite = true;
xml.onLoad = xmlLoaded;
xml.load( ‘sampleXML.xml’ );

function recurseTrace(info:Object, indent:String) {
for (var i in info) {
if (info[i] == null){}
else if (typeof info[i] == “object”) {
myTrace(indent + i + ” -“);
recurseTrace(info[i], indent);
}
else {
myTrace(indent + i + ” = ” + info[i] +”, “);
}
}
}

function myTrace(myLine:String){
feedback.text += “|”+myLine;
trace(myLine);
}
[/cc]

And here’s my sample xml file: (it’s the same one I use in my Dynamic Flash Scrolling Link List files)
[cc lang=”xml” tab_size=”2″ lines=”40″]


3D
https://circlecube.com/circlecube/tag/3d/


abstract
https://circlecube.com/circlecube/tag/abstract/


actionscript
https://circlecube.com/circlecube/tag/actionscript/


animation
https://circlecube.com/circlecube/tag/animation/


blog
https://circlecube.com/circlecube/tag/blog/


book
https://circlecube.com/circlecube/tag/book/


CG
https://circlecube.com/circlecube/tag/cg/


charcoal
https://circlecube.com/circlecube/tag/charcoal/


circle cube
https://circlecube.com/circlecube/tag/circle-cube/


collage
https://circlecube.com/circlecube/tag/collage/


color
https://circlecube.com/circlecube/tag/color/


css
https://circlecube.com/circlecube/tag/css/


drawing
https://circlecube.com/circlecube/tag/drawing/


dreamweaver
https://circlecube.com/circlecube/tag/dreamweaver/


experiment
https://circlecube.com/circlecube/tag/experiment/


film
https://circlecube.com/circlecube/tag/film/


final cut
https://circlecube.com/circlecube/tag/final-cut/


flash
https://circlecube.com/circlecube/tag/flash/


[/cc]

Download:

Here’s the XML2Object.as class: XML2Object.as class

 

Here’s a zip containing everything and the working example: xmlToObject.zip