Build a Simple Website Template Using SWFAddress
Jun 1st in S.E.O.
by George Kendros
SWFAddress is a Javascript/ActionScript library which gives you the power to change the browser's URL, add entries to its history list and fire off ActionScript events when the URL changes. It also allows search engines to find specific content in your site. This is all functionality which, according to its creators, is missing in today's rich web technologies.
Let's take a look..
Hey guys, my name is George Kendros. I hail from Mississauga, Ontario, Canada. I enjoy developing with flash/html/javascript. My current interests include flash/wordpress integration, creating html-like flash pages with various js libraries and creating flash-like html pages with js.
Check out my portfolio to see some of the work I’ve uploaded to FlashDen.
Background
Before we jump right into the code, we'll explore what SWFAddress is and how we need to adjust our work flow to use it. Essentially, SWFAddress is a javascript/ActionScript library which gives you the ability the change the browser's URL, add entries to it's history list and fire off ActionScript events when the browser changes its URL. SWFAddress will listen for specific browser events (URL changes) and signal its ActionScript counterpart to trigger certain events. The ActionScript class also gives us an easy to use API for controlling various browser actions (ie. changing the URL, changing the page title).
SWFAddress sites differ from some traditional sites because the navigation logic must be string based and it must have a central junction. It's common for many flash based sites to have a unique function attached to every navigation element. For example, the first button may trigger a function showPage1() and the second could trigger a function showPage2() etc. In a SWFAddress page every navigation element will trigger the same function, namely the one that instructs SWFAddress to change the URL.
SWFAddress will also simultaneously trigger its change event at which point you will need to evaluate the current URL and decide what action to take. Once you get comfortable with this difference you'll find that SWFAddress creates little resistance to your regular workflow. In fact, many developers already use a similar navigation architecture on their non-SWFAddress sites.
This tutorial will begin by building a basic page with 4 navigation elements. We'll then introduce SWFAddress into the mix to give us some deeplinking support. Finally, for the advanced users, we'll swap out our static menu/text and use an external XML file to supply the content.
Step 1: Setting Up the Workspace
Our SWFAddress powered website will consist of a few key files. We'll need our main FLA, the SWF it compiles, an HTML page, the SWFAddress .as libraries, the SWFAddress .js libraries and the SWFObject libraries (the javascript libraries are in the swfaddress and swfobject folders).
Step 2: The HTML File
Our HTML page is a basic SWFObject dynamic embed with a line for SWFAddress. We won't go too in depth into it since the HTML and js are beyond the scope of this tutorial. Suffice to say, the only differences between a typical SWFObject HTML template and this is the HTML on line #7 (see the line highlighted in blue).
Step 3: Basic FLA Setup
Now that the source files are in place we'll start making our FLA. Create a new AS3 document, set its dimensions to 600 x 400px then save it to the project directory as "tutorial.fla". We'll also set the background color to #999999 so it looks less boring.
Step 4: Menu Items Array
For this tutorial we're going to make an array to hold our menu items. This will make it easier to incorporate an XML based menu at a later date if you want. We'll start by making a new layer on the timeline which we'll call "actions". We'll then pull up the actions panel (with that layer selected) and use the following code:
var menuArray:Array = new Array("Home", "About Us", "Services", "Contact Us");
It should look something like this:
Step 5: Drawing the Menu Holder
Now we're going to start making the menu. We'll make a new layer (call it "menu") and begin by drawing a simple 400 x 50px rectangle with a 2px corner radius on the new layer. The color isn't important because we'll tweak it later.
Step 6: Converting the Menu to a Movie Clip
Now we'll select the menu and press F8 to convert it to a movie clip. We'll give it a library identifier of "menu" and an instance name of "menuHolder".
Step 7: Making the Menu Background
Double-click on the newly created menu movie clip to enter its edit mode. We'll select the shape inside and again convert it to a movieclip (F8). This time however, we'll be applying a 9 slice scaling grid to it. We do this so we can have a background for the menu that we can scale cleanly without having to scale the menu itself. We'll give it a library and instance name of "menubg".
I've also added a subtle blue glow to the menu using a glow filter with the blurx and blury set to 6, strength set to 50% and the color set to #32CCFF.
Step 8: Drawing the Menu Items
Now we'll go back to the main document and begin creating the actual menu items (ie. the "links" that will populate the menu). Although we're drawing these on the main document we could draw them anywhere as they'll be dynamically added to the stage later. We'll first create a textfield and set it to dynamic and give it an instance name of "txt". We'll set the font to Arial, the size at 22pts and the color to white #ffffff. Make sure the textfield is not selectable (the first button below the anti-alias drop down menu). Finally, we'll embed the font. You can use any font you like, but you'll need to remember to adjust the font size so that it fits the menu height wise.
Step 9: Exporting Menu Items for ActionScript
We'll now convert the menu items to movie clips, but we'll need to take an extra step since we'll be re-using this movie clip in our ActionScript. Select the textfield and press F8 to bring up the movieclip dialog, input "menuItem" into the name field then select the "Export for ActionScript" check box. Once done click OK, then click OK again on the following confirmation dialog (it may not appear depending on your settings).
Step 10: Creating the Menu Items (ActionScript)
We'll use the following code to populate the menu with the appropriate menu items:
var xval = 20;
for (var i:int = 0; i<menuArray.length; i++){
var clip = new menuItem
clip.txt.autoSize = 'left'
clip.txt.text = menuArray[i]
clip.x = xval
clip.y = (menuHolder.height/2) - (clip.height/2)
xval += clip.width + 30
menuHolder.addChild(clip);
}
menuHolder.menubg.width = menuHolder.width + 20;
menuHolder.x = (stage.stageWidth/2) - (menuHolder.width/2)
Basically we're looping through the elements of our array and for each element creating a new instance of menuItem. Then we're setting the textfield inside menu item to "autoSize = left" so that it expands to fit the text that's placed inside it. The next line sets the text inside the textfield according to the array element which corresponds with the current iteration of the loop. xval is a variable we use that stores the position of the menu item so we can place them beside each other. Then we center the menu Item within the menu and finally add the menu Item's width and the padding value to xval. Next we add the menu item to the menuHolder. The last 2 lines of code make the menuHolder's background stretch to fill the menu holder (we add 20px for padding) and center the menu on the stage.
Step 11: Creating the Content Area
Before we move on to assigning actions to the menu items and setting up SWFAddress, we'll need to create some content to display. For the sake of simplicity we'll use the default flash tweening engine. Create a new layer called content. On this layer create a rectangle measuring 500 x 250px and convert it to a movie clip with an instance name of "content".
Step 12: Adding Textfield to Content Area
Now that we've created the content area we'll double click it to enter edit mode and place a dynamic textfield on it. This textfield should be the almost as large as the "content" movie clip. We'll use the same text settings as the menu (arial 22pt, white) with fonts embeded. We'll give it an instance name of txt and change the behavior (under paragraph settings) to multi line.
Step 13: Creating the content
Now let's create some content that we can populate the content area with when menu items are selected. For the sake of simplicity we'll just create 4 different string variables, but in a more advanced site you would likely be replacing this with some external data source. Add the following 4 variables to our ActionScript code:
var text1:String = "This is the text for the Home page"
var text2:String = "Here is the text that you would see on the About Us page"
var text3:String = "This page would feature the various services we provide"
var text4:String = "These are the various methods you can get in contact with us. You will also find a map here"
You can place these near the top of the code.
Step 14: Making the Textfield's Change Function
We'll now create a simple function that changes the textfield's content and animates the transition. Paste in the following code then we'll explore it line by line:
import fl.transitions.Tween;
import fl.transitions.easing.*;
var cTween:Tween = new Tween(content, "x", Regular.easeOut, 50, 50, .1,true);
var mainText:String
function textChange(){
cTween.continueTo(-800, .4);
cTween.addEventListener("motionFinish", setText)
}
function setText(e:Event){
content.txt.text = mainText
cTween.continueTo(50,.4)
}
The first 2 lines simply import the tween class and easing functions. The next line initializes the tween so we can more easily manipulate it with the continueTo function. The 4th line creates a variable which holds the current string, this variable will be set by SWFAddress and the content area will load this variable into its textfield whenever it's tweening back into position. The textChange function tweens the content area off to the side and sets an event listener to trigger the setText function when it's done. The setText function tweens the content area back on stage and sets its textfield to whatever mainText has been set to by SWFAddress.
Step 15: Initializing SWFAddress
To initialize SWFAddress we simply need to add its CHANGE event and create that event's handler. These few lines of code will do it;
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, addressChange)
function addressChange(e:Event){
//stuff to do when address changes
}
The "addressChange" function will run every time the browser changes the URL (via back/forward buttons, re-writing the address bar URL or any other method) or you change the URL (via the SWFAddress.setValue function).
Step 16: Adding Actions to the Menu Items
Our next step is to add some behavior to the menu buttons we created earlier. We'll be doing this by revisiting the menu creation loop we built earlier.
var xval = 20
for (var i:int = 0; i<menuArray.length; i++){
var clip = new menuItem
clip.txt.autoSize = 'left'
clip.txt.text = menuArray[i]
clip.x = xval
clip.y = (menuHolder.height/2) - (clip.height/2)
xval += clip.width + 30
menuHolder.addChild(clip);
clip.addEventListener('click', menuClicked)
}
The last line before the closing brace is the one we need to add. It creates an event on the menu items that fires when a menu item is clicked. We'll now need to add the corresponding event handler.
var xval = 20;
for (var i:int = 0; i<menuArray.length; i++){
var clip = new menuItem
clip.txt.autoSize = 'left'
clip.txt.text = menuArray[i]
clip.x = xval
clip.y = (menuHolder.height/2) - (clip.height/2)
xval += clip.width + 30
menuHolder.addChild(clip);
clip.addEventListener('click', menuClicked)
}
function menuClicked(e:Event){
SWFAddress.setValue(e.currentTarget.txt.text)
}
The last three lines of code we added are executed every time a menu item is clicked. It instructs SWFAddress to execute its setValue function which changes the page and fires its CHANGE event handler. The parameter we're passing to the setValue function is the text of the menu item that the user has clicked.
At this point, if we uploaded the files to our web server and tested the HTML file, we would have the address URL changing as we clicked the buttons but the file wouldn't do anything as we haven't told SWFAddress what to do when the address changes.
Step 17: SWFAddress Actions
We now have the menu set up and the menu buttons are properly triggering SWFAddress. The last part of the equation is to tell SWFAddress what to do when it's triggered. Earlier in the tutorial (Step 15) we created the SWFAddress event listener and handler. We'll revisit that block of code and add the following:
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, addressChange)
function addressChange(e:Event){
if(SWFAddress.getValue() == "/Home"){
mainText = text1
textChange()
}
if(SWFAddress.getValue() == "/About Us"){
mainText = text2
textChange()
}
if(SWFAddress.getValue() == "/Services"){
mainText = text3
textChange()
}
if(SWFAddress.getValue() == "/Contact Us"){
mainText = text4
textChange()
}
SWFAddress.setTitle(SWFAddress.getValue());
}
The key difference is all the code inside the "addressChange" function. We created several conditional statements that check what the current page is, set "mainText" to the appropriate text then launch the "textChange" function which is responsible for animating the transition and setting the text of the content area. The last line sets the page's HTML title to the current page. This function could be cleaned up with a switch case, but for the sake of simplicity we'll leave it as is.
Step 18: All Done
Your files should now match the ones in the source files. Publish the FLA, upload the files to your server and you'll now have a fully functional page.
Conclusion
We've now completed our simple SWFAddress powered page. This file should serve as a suitable base for any SWFAddress site and can easily be extended with dynamic content with minimal extra code. I hope you enjoyed following along!
User Comments
( ADD YOURS )Clemente G June 1st
Nice basic tut on SWFAddress.
( )Mike June 1st
Good tutorial, And I suggest people start implementing SWFAddress from the start of a project. Trying to go back and implement it after a project is already completed can be extremely difficult.
( )Ibesoringola June 2nd
Hey man! It seems to me that you know a lot about Flash Web Design and Actionscript coding, can’t you share with us. I visited your website it’s actually pretty cool work. Big up!
( )Mike June 3rd
I’m still a Flash newb myself. I try to continually learn new things as I go. I’ve actually tried writing up a couple tutorials before. Not going to lie, it takes a lot of time and work. Much more than I thought when I sat down to create one. I definitely give props to the tutorial writers here.
Matt Przybylski June 1st
Good tutorial but you should definitely condense your code I’m step 17 to a switch statement and run the textChange method outside the switch as the second to last line since all cases run it. Try to condense your code as much as possible in cases like this where such repetition is not necessary and messy.
( )Andrew Scarborough June 24th
Maybe you should make a tutorial too Matt.
( )Dario Gutierrez June 1st
Nice tut, my next project maybe can be with Swf Address.
( )Nik June 1st
Great tutorial, thanks!
( )i downloaded the source files but they dont seem to work. Will it only work when its uploaded to a server?
André June 1st
Nice, better if used doc class but thanks for sharing…
but i really need to correct something…
function addressChange(e:Event){ should be:
function addressChange(e:SWFAddressEvent){
and here you get the value with e.value instead of getting by SWFAddress.getValue(); this is the functionally of SWFAddressEvent =)
And a suggestion for anyone, to use with a Loader or URLLoader, or anything else…
function addressChange(e:SWFAddressEvent):void{
( )loaderinstance.load(new URLRequest(e.value.substr(1)+’.swf’));
}
George Kendros June 2nd
I wanted to make sure I specifically used SWFAddress.whateverFunction() because I wanted to clearly point out all the instances where we trigger one of the class’ functions or read one of it’s properties.
I felt like in any situation where someone could fill in their personal expertise to improve the code it would be better to go with the more basic version. For example, someone who knows how to use switch statements would have no problem converting those repetitive booleans, but someone who doesn’t really understand switch statements would basically be lost at that point if I used a switch case instead. In most situations I’d use an array with a key value pair or XML and reduce that function to 2 or 3 lines with no booleans but then I would have to spend and extra 10 steps describing key value array’s and the methods of traversing them.
( )André June 2nd
Everytime you call the SWFAddress.value it will call for an Externalinterface.call to get a value from a javascript function that will read it from the hash value of the browser…
With e.value will get the value from a getter function that will read it from a variable inside the SWFAddressEvent class… so wich one would be faster??
If you dont teach about the SWFAddressEvent class, the people who will read your tut wont guess that have a much faster and correct way to get the value when using listeners… the reason to exist the SWFAdrress.getValue() is because you can call this function from anywhere in your code without needing to add an event listener, when you can´t get by e.value, but inside the listener you can, and you should get by e.value… i am sorry to say but using SWFAddress.getValue() inside the listener works but it´s wrong…
And the suggestion i gave before, is for the people that already if a little bit fammiliar to this class, just an example on how can this class be used in other sittuations…
Just adding something here, the SWFAddress enables the history navigation,but also you can use can refresh the page and go back where you were before refresh, and another cool thing is that you can copy the address and paste in e-mail for a friend for example… but it´s important not using spaces at the hash links…for example Contact us would work better if used an underline instead of space: contact_us
The reason is if you paste for a friend, the space will look like %20, so contact us would like contact%20us, and the SWFAddress wont get this.. try yourself by pasting the addresses of your demonstration directly at the browser…
Doesnt work:
http://flashtuts.s3.amazonaws.com/034_SWFAddress/preview/preview_html/index.html#/Contact Us
Works:
http://flashtuts.s3.amazonaws.com/034_SWFAddress/preview/preview_html/index.html#/Services
Just an example of a website i´ve used this feature:
http://www.balancascascavel.com.br
But thanks again for sharing
André June 2nd
*** the link to Contact us need to be copied and pasted, because of the space between the Contact and the Us, just the US is unlinked
George Kendros June 3rd
I’m not sure if were looking at different parts of the class but getValue() doesn’t launch a call. The _getValue function does but that’s not the public function. The public getValue() only executes the following:
return decodeURI(_strictCheck(_value || ”, false));
The only place I see _getValue (the one that makes the external interface call) launched is in the handler for the initTimer. In other words, SWFAddress launches it’s external call on a timed basis any any call to getValue() is simply reading the _value variable.
In case you were wondering about _strictCheck, all it does is check if the strict variable is set and modifies the string accordingly.
Pasting it directly works fine. SWFAddress uses encodeURI and decodeURI on everything.
Franky June 1st
Cooool!
( )Diego SA June 1st
Man, you chose the right subject to teach about. Some websites I did a time ago always had a problem with SWFAddress (actionscript 2.0). The last one I couldn’t figure out the source of the problem.
( )visual things June 2nd
great tutorial though this functionality is present for quite a time …
( )Worley June 2nd
just what i was going to look for today! thanks man
( )BJ June 2nd
is it only working server side. How can i test on my computer?
( )Web design Bangladesh June 3rd
It happens. Not only with flash but also with php/mysql databases. However i also want to know why it happens.
( )André June 3rd
it´s not only server side… its 100% client side, but can integrate server-side with PHP, ASP or anything else
( )Gareth Hardy June 3rd
Great post indeed!
( )Glendon Guttenfelder June 3rd
Nice tutorial. I have just began using SWFAddress, and I’ve implemented it on several sites I have built. I’m experiencing a very strange problem…
I have used the EXACT same actionscript on 6 sites, all of which call the .js files from a central location on a separate domain (so I can update one .js file instead of having to update it on EVERY domain).
Of those 7 sites, 4 work fine and 3 only change the TITLE, but not the URL in the address bar. And one of the sites WAS working, and then mysteriously STOPPED.
Working on:
bfrstudios.com
jimsoldfashionservice.com
rockbarnstorage.com
garypriceinsurance.com
NOT working on:
herbsforlifejoplin.com
atouchofcharmmassage.com
bkstonepavers.com
Any suggestions on what I should be checking for? Again, the same code and same files react differently based on being hosted from different domains.
( )Glendon Guttenfelder June 3rd
One more note: if I upload the .swf files from one of the non-working sites to the domain of one of the working sites, they then begin to work. So I know it is NOT the .swf files. Rather, it’s something to do with the individual settings of the domains on the server. All of the accounts are on the same server, but under different domains.
( )George Kendros June 3rd
Seems like this could be your issue;
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/system/Security.html#allowDomain()
Anime7Graphic June 6th
very useful, special thank’s for George Kendros
it is simple tips and we can modifying source be advance.
I hope you can write next tutorial like this with a sample widget and tool for true website.
( )kweku June 13th
please check out this site okay, it does not have deeplinkiing and i am trying to apply your tutorial, but it is AS2, can u help pls
( )Skyfred June 14th
I’m sorry, I’m a beginner, and the .fla file isn’t working. Can you re-upload it ?
My english isn’t perfect and I have some difficulties to understand some steps…
Anyway, thank you !! Nice tutorial !
( )Ian Yates June 14th
Which version of Flash are you using?
( )Skyfred June 14th
Adobe Flash Pro CS3.
( )Skyfred June 15th
I sent it to a friend and he has the same problem…
( )pouetcha June 16th
Hello, i’m his friend and there is the same error for me : “Unexpected format”
( )Skyfred June 19th
Can someone re-up the file .FLA file with another version of flash ?
TX
( )George Kendros June 30th
Skyfred, click on my name at the top of the article, it will send you to my FlashDen page where you’ll see a link to email me in the right sidebar. Send me an email and I’ll try to get you a working version of the FLA.
i don't think so July 31st
the .fla is not opening for me either.
so i am supposed to go to flash den and become a member to be able to email the author, who will “try” to send me a working file?
right…
( )David Moreen August 8th
My lord, this is so simple yet I find it so invigorating! Love it.
( )craigk September 7th
what if you are using a dynamic xml menu, do you have any example of that?
( )Rudeless2 September 14th
Hi; nice tut.
Can we change the textfield by a movie ?
example :
if( SWFAddress.getValue() == “/Home” )
{
mainContent = homeMC ;
contentChange() ;
}
mainContent = homeMC = MovieClip
( )wiyono September 27th
halloo my name is Wiyono.
this go with flash pro 8?, because i try to instal source then i open, there staya unknown format…
can u help me plissssss….
thanksss…
( )Dustin October 16th
thank you so much! I have spent hours trying to make some more complicated examples work. This simple bare bones tutorial is just what i needed.
( )Gabe November 5th
Hey, I notice in the demo if I just click once to go to a page and then click the back button to return to the home page the back button isn’t working. It does if I first go to more than one page and then try it. Is that fixable? I am using osx firefox and also tested it with opera and safari.
( )