<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Activetuts+ &#187; XML</title>
	<atom:link href="http://active.tutsplus.com/category/tutorials/xml/feed/" rel="self" type="application/rss+xml" />
	<link>http://active.tutsplus.com</link>
	<description>Flash, Flex &#38; ActionScript Tutorials</description>
	<lastBuildDate>Fri, 12 Mar 2010 17:01:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using Google Maps&#8217; New Features for Flash</title>
		<link>http://active.tutsplus.com/tutorials/xml/make-the-most-of-google-maps-new-features-for-flash/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/make-the-most-of-google-maps-new-features-for-flash/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 12:00:24 +0000</pubDate>
		<dc:creator>Niels Musschoot</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=3127</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/preview.jpg" alt="Using Google Map's New Features for Flash">]]></description>
			<content:encoded><![CDATA[<p>After such a positive response to my first tutorial <a href="http://active.tutsplus.com/tutorials/xml/implement-a-map-using-the-google-map-api-for-flash/">Implement a Map Using the Google Map API for Flash</a> I decided to write a second. Since that first tut the Google Map API has been updated, allowing developers to (amongst other things) add 3D viewing to maps. This is a great feature and during this tutorial I&#8217;ll explain how to use it.</p>
<p>Also, lots of people requested an explanation for adding custom markers; that&#8217;s the second thing we&#8217;ll discuss here today.</p>
<p><span id="more-3127"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/Archive.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/preview_2.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: Download The SDK Component</h2>
<p>I won&#8217;t build further on our previous map because we need to download the new Google Map Component. There is no way to use the component from my previous tutorial as that one does not support the 3D functions.  So&#8230; go to <a href="http://code.google.com/intl/nl/apis/maps/documentation/flash/">http://code.google.com/intl/nl/apis/maps/documentation/flash/</a>
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image1.jpg" border="0" /></div>
<h2>Step 2: Install the SDK Component</h2>
<p>We need to install the SDK component to use it in Flash. To do so, navigate to the location where you saved the Google Maps SDK Component and find the non-Flex version of the interface library. In my case this is (lib/map_1_18.swc). Now copy the &#8220;map_1_18.swc&#8221; file.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image2.jpg" border="0" /></div>
<h2>Step 3: Folders</h2>
<p>Afterwards, if you have Flash currently open, quit the application and search for this folder:</p>
<ul>
<li>
        	(Windows) C:\Program Files\Adobe\Adobe Flash CS3 (or your Flash version)\en (or your language)\Configuration\Components
        </li>
<li>
        	(Mac OS X) Macintosh HD/Applications/Adobe Flash CS3 (or your Flash version)/Configuration/Components
        </li>
</ul>
<p>Inside that folder create a new folder named &#8220;google&#8221; and Paste the &#8220;map_1_18.swc&#8221; file inside it. Flash is now set up to<br />
    support the Google Maps API for Flash.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image3.jpg" border="0" /></div>
<h2>Step 4: The Google Map API Key</h2>
<p>Ok we have the component now but before we can get to work we still need a Google Map API Key to get our map working online. A Google Map API Key is free and you can get one here:<br />
    <a href="http://code.google.com/intl/nl/apis/maps/documentation/flash/"></p>
<p>http://code.google.com/intl/nl/apis/maps/documentation/flash/</p>
<p>    </a>.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image4.jpg" border="0" /></div>
<h2>Step 5: Sign Up</h2>
<p>Clicking the &#8220;Sign up for a Google Maps API Key&#8221; link brings us to the next page where we can generate our personal API Key. Scroll down the page, agree with the terms and conditions (you could read these too if you&#8217;re really interested) and add the url of the website where you want to use the application (you will need a different API Key for every domain where you want to place a map). After that, click &#8220;Generate API Key&#8221;.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image5.jpg" border="0" /></div>
<h2>Step 6: Save It!</h2>
<p>Now you&#8217;ll see your personal API Key for the selected domain. Copy the API Key and paste or save it somewhere as we&#8217;ll need it very soon.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image6.jpg" border="0" /></div>
<h2>Step 7: New ActionScript 3.0 File</h2>
<p>OK, the boring work is done, now we can start with the fun stuff! Let&#8217;s dive into Flash and create a new ActionScript 3.0 file, default stage size (550 x 400).
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image7.jpg" border="0" /></div>
<h2>Step 8: Save It</h2>
<p>I prefer to start off by saving the file. While I&#8217;m working I really like to Hit &#8220;Ctrl+S&#8221; all the time, so go ahead hit<br />
    &#8220;Ctrl+S&#8221; or click &#8220;File > Save&#8221; in the menu. Save it to the location you want and name it whatever you want. I will name it<br />
    &#8220;google_map&#8221;.
</p>
<h2>Step 9: The GoogleMapsLibrary</h2>
<p>Open the Components panel &#8220;Ctrl+F7&#8243; or click Window > Components in the menu. Drag the GoogleMapsLibrary into your library.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image9.jpg" border="0" /></div>
<h2>Step 10: The Actions Layer</h2>
<p>To keep organized I like to rename the first layer to &#8220;actions&#8221;.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image10.jpg" border="0" /></div>
<h2>Step 11: Import</h2>
<p>With the actions layer selected open the actions panel (hit &#8220;F9&#8243; or click &#8220;Window > Actions&#8221;) and add these lines of code:</p>
<pre name="code" class="javascript">
		import com.google.maps.LatLng;
        import com.google.maps.Map;
        import com.google.maps.Map3D;
        import com.google.maps.MapEvent;
        import com.google.maps.MapType;
        import com.google.maps.View;
        import com.google.maps.geom.Attitude;
	</pre>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image11.jpg" border="0" /></div>
<h2>Step 12: Create the Map</h2>
<p>Now we&#8217;ll create our first function. First we want to declare our Map variable:</p>
<pre name="code" class="javascript">
    	// Variables
        var map:Map3D;
    </pre>
<p>Now we can add our function that we will call to add the main map on the stage:</p>
<pre name="code" class="javascript">
    	// Function that adds the map on stage
        function add_map()
        {
			map = new Map3D();
    		map.key = "YOUR_API_KEY_HERE";
            map.setSize(new Point(stage.stageWidth, stage.stageHeight));
    		map.addEventListener(MapEvent.MAP_READY, onMapReady);
    		this.addChild(map);
		}
    </pre>
<p>OK, as you can see we added an eventlistener that will fire once our map is loaded, so lets also create that function:</p>
<pre name="code" class="javascript">
    	// Function that will fire once map is created
		function onMapReady(event:MapEvent):void
		{
		    map.setCenter(new LatLng(50.899197766773284, 4.486040573103489), 13);
			map.setAttitude(new Attitude(20,30,0));
		}
    </pre>
<p>Here we&#8217;ve set the map to center. This function has 3 values and will define the location where the map will open. The<br />
    values are like this &#8220;map.setCenter(new LatLng(<b>latitude</b>, <b>longitude</b>), <b>zoom</b>);&#8221;. Then we define the view mode;<br />
    as we are using the new 3D map I will use the Perspective view. If you like a normal map view you can change this value to<br />
    &#8220;View.VIEWMODE_2D&#8221;. </p>
<p>Then we set the Attitude. This will define how we view the map. In this case we will add a little Perspective view to it and<br />
    turn the map a little to create a nicer view angle. You can play around with these values a bit and see what you like best.</p>
<p>OK, it&#8217;s time for a first check! What do we have so far? Well, nothing yet! We first need to call our function to create the<br />
    map! Let&#8217;s add this line of code just under our variables:</p>
<pre name="code" class="javascript">
        // Variables
        var map:Map3D;

        // Call the function to create the map
        add_map();
    </pre>
<p>There we go! Now just test your movie &#8220;Ctrl+Enter&#8221; or click Control > Test Movie in the menu&#8230;</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image12.jpg" border="0" /></div>
<h2>Step 13: The Navigation Tools</h2>
<p>Yes! We have a map zoomed in on Brussels Airport! Isn&#8217;t that great?! Perhaps not&#8230; Let&#8217;s take a look at what we have here. We have the map and we can drag the map around. So what we need next are tools to navigate around the map, zoom in and out on the map. Let&#8217;s start with those navigation tools first!</p>
<p>First of all let&#8217;s import 3 extra classes; add these lines under the other import code in our script:</p>
<pre name="code" class="javascript">
    	import com.google.maps.controls.NavigationControl;
    	import com.google.maps.controls.MapTypeControl;
    	import com.google.maps.controls.OverviewMapControl;
    </pre>
<p>No go to the onMapReady() function and add these 3 lines of code under the other lines:</p>
<pre name="code" class="javascript">
    	map.addControl(new MapTypeControl());
    	map.addControl(new OverviewMapControl());
    	map.addControl(new NavigationControl());
    </pre>
<p>Here we&#8217;re adding the map type controls, so now we can change the map type. Then we add a map overview control to the right bottom of our map. And we add the map navigation tools. This is our full source code as it should look right now:</p>
<pre name="code" class="javascript">
    	import com.google.maps.LatLng;
		import com.google.maps.Map;
		import com.google.maps.Map3D;
		import com.google.maps.MapEvent;
		import com.google.maps.MapType;
		import com.google.maps.View;
		import com.google.maps.geom.Attitude;
		import com.google.maps.controls.NavigationControl;
		import com.google.maps.controls.MapTypeControl;
		import com.google.maps.controls.OverviewMapControl;

		// Variables
		var map:Map3D;

		// Call the function to create the map
		add_map();

		// Function that adds the map on stage
		function add_map()
		{
			map = new Map3D();
    		map.key = 'YOUR_API_KEY_HERE';
			map.setSize(new Point(stage.stageWidth, stage.stageHeight));
    		map.addEventListener(MapEvent.MAP_READY, onMapReady);
    		this.addChild(map);
		}

		// Function that will fire once map is created
		function onMapReady(event:MapEvent):void
		{
			map.setCenter(new LatLng(50.899197766773284, 4.486040573103489), 13);
			map.viewMode = View.VIEWMODE_PERSPECTIVE;
			map.setAttitude(new Attitude(20,40,0));
			map.addControl(new MapTypeControl());
    		map.addControl(new OverviewMapControl());
    		map.addControl(new NavigationControl());
		}
    </pre>
<p>Go ahead and test your movie again. You can see that you can move around the map very easily now with these funky looking new<br />
    controls!
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image13.jpg" border="0" /></div>
<h2>Step 14: A Bar Without Beer</h2>
<p>I think it&#8217;s time to move on to the markers part; a map without markers is like a bar without beer isn&#8217;t it? No silly stuff this time! Let&#8217;s move to the Custom markers straight away!</p>
<p>We want to place our custom markers onto the map with information that will be stored in an external XML file. Let&#8217;s begin by creating a custom marker, then we&#8217;ll create the XML file and after that we&#8217;ll load it into Flash.
</p>
<h2>Step 15: Creating the Custom Marker</h2>
<p>I&#8217;m not much of a designer so I think you&#8217;ll be able to create a much cooler marker than I have! Thats why I&#8217;m not going spend too much time on this. Just draw a few circles, put them on top of each other, select everything, hit F8, select movieClip, name it &#8220;marker_mc&#8221; and select Export For Actionscript. Hit &#8220;OK&#8221;. </p>
<p>As I mentioned before, I hope you will create a cooler and better looking marker than this! Just draw your own marker and<br />
    covert it to a moviclip as explained above.</p>
<p>Once you&#8217;ve created the movieclip it will appear in your library. You can then delete it from the stage as we will import it using<br />
    ActionScript (that&#8217;s why you had to select the option &#8220;Export For ActionScript&#8221;). In our library we now have 2 items; the<br />
    GoogleMapsLibrary and our marker_mc.
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image14.jpg" border="0" /></div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image15.jpg" border="0" /></div>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image15_b.jpg" border="0" /></div>
<h2>Step 16: The XML file</h2>
<p>OK, here we are. We have a map and (in your case) a very good looking marker! Now let&#8217;s create the XML file. Open your favorite code editor, create this file and save it as locations.xml.</p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
 &lt;map_xml&gt;

  &lt;location&gt;
   &lt;lat&gt;50.899197766773284&lt;/lat&gt;
   &lt;lon&gt;4.486040573103489&lt;/lon&gt;
   &lt;name_tip&gt;Brussels&lt;/name_tip&gt;
   &lt;title_tip&gt;&lt;![CDATA[Brussels]]&gt;&lt;/title_tip&gt;
   &lt;content_tip&gt;&lt;![CDATA[Brussels Airport.]]&gt;&lt;/content_tip&gt;
  &lt;/location&gt;

  &lt;location&gt;
   &lt;lat&gt;49.004024443647324&lt;/lat&gt;
   &lt;lon&gt;2.571113562006575&lt;/lon&gt;
   &lt;name_tip&gt;Paris&lt;/name_tip&gt;
   &lt;title_tip&gt;&lt;![CDATA[Paris]]&gt;&lt;/title_tip&gt;
   &lt;content_tip&gt;&lt;![CDATA[Paris Airport.]]&gt;&lt;/content_tip&gt;
  &lt;/location&gt;

  &lt;location&gt;
   &lt;lat&gt;51.4699229971675&lt;/lat&gt;
   &lt;lon&gt;-0.45367874251784013&lt;/lon&gt;
   &lt;name_tip&gt;London&lt;/name_tip&gt;
   &lt;title_tip&gt;&lt;![CDATA[London]]&gt;&lt;/title_tip&gt;
   &lt;content_tip&gt;&lt;![CDATA[London Airport.]]&gt;&lt;/content_tip&gt;
  &lt;/location&gt;

 &lt;/map_xml&gt;
</pre>
</p>
<h2>Step 17: Loading the XML</h2>
<p>We need to get the XML data into our flash movie. To do so we need to create a new function that will load our xml. Add<br />
    this piece of code to the bottom of the script. Inside our onMapReady() function we call this new load_xml() function. Once our map is ready we will start loading the xml.</p>
<pre name="code" class="javascript">
        // Function that will load the xml
    	function loadXML(e:Event):void
        {
	        XML.ignoreWhitespace = true;
	        var map_xml:XML = new XML(e.target.data);
        }

        function load_xml()
        {
			var xmlLoader:URLLoader = new URLLoader();
			xmlLoader.addEventListener(Event.COMPLETE, loadXML);
			xmlLoader.load(new URLRequest("locations.xml"));
		}
    </pre>
<h2>Step 18: Loop Through the Locations</h2>
<p>As we have 3 locations in our XML file we&#8217;ll need to create a &#8220;For&#8221; loop and store all the data in some Arrays. Inside our<br />
    loadXML() function we add this piece of code to create the For loop:</p>
<pre name="code" class="javascript">
    	for (var i:Number = 0; i &lt; map_xml.location.length(); i++)
        {
		    trace(map_xml.location[i].title_tip);
	    }
    </pre>
<p>If we test our movie now we can see our movie outputs the xml data. Now let&#8217;s work with it.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image18.jpg" border="0" /></div>
<h2>Step 19: Create the Variables</h2>
<p>Next we have to create some variables to store our data loaded from the XML file. Inside our For loop we add these variables:</p>
<pre name="code" class="javascript">
    	var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
		var tip = map_xml.location[i].name_tip;
		var myTitle:String = map_xml.location[i].title_tip;
		var myContent:String = map_xml.location[i].content_tip;
    </pre>
<p>You can delete the &#8220;trace()&#8221; line we used before as we know things are working.
</p>
<h2>Step 20: Adding the Markers on the Map</h2>
<p>Now that we have all of our xml data stored in variables we can get over to load our markers onto the map. First we add some extra classes to our code. Add this piece of code under the other classes:</p>
<pre name="code" class="javascript">
    	import com.google.maps.overlays.*;
		import com.google.maps.InfoWindowOptions;
        import com.google.maps.MapMouseEvent;
    </pre>
<p>Create a new function called createMarker(). We want to add this function just before our loadXML() function.</p>
<pre name="code" class="javascript">
    	// Add Markers On The Map
        function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker
        {
            var i:Marker = new Marker(
									  latlng,
									  new MarkerOptions({
                                                             hasShadow: true,
				                                             tooltip: ""+tip
                                                       })
									 );
            return i;
        }
    </pre>
<p>We can call the createMarker() function for every marker we need to add to the map, so inside our For Loop we add this line of code:</p>
<pre name="code" class="javascript">
    	map.addOverlay(createMarker(latlng, i, tip, myTitle, myContent));
    </pre>
<p>If you test the movie now you can see that we have markers on our map on the locations we specified in our xml file! That&#8217;s great, but we didn&#8217;t create that great custom marker for nothing did we? We&#8217;ll remove those standard markers and add our custom markers.
</p>
<h2>Step 21: Add Custom Marker</h2>
<p>First we need to create our custom marker object. Add this code into the createMarker() function, above the rest of the code:</p>
<pre name="code" class="javascript">
    	// create Custom marker object
        var markerPin:marker_mc = new marker_mc();
        // If your marker is to big you can scale it down here
	    markerPin.width = 20;
	    markerPin.height = 20;
    </pre>
<p>Afterwards, we&#8217;ll go to the next piece of code where we have to add a line to the markerOptions. Search for this piece of code:</p>
<pre name="code" class="javascript">
    	new MarkerOptions({
                               hasShadow: true,
				               tooltip: ""+tip
                         })
    </pre>
<p>and change it to:</p>
<pre name="code" class="javascript">
    	new MarkerOptions({
                               hasShadow: true,
                               icon: this.addChild(markerPin),
				               tooltip: ""+tip
                         })
    </pre>
<p>Ok! Test your movie and check the result!
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image21.jpg" border="0" /></div>
<h2>Step 22: Moving On</h2>
<p>OK, what&#8217;s next? The Info windows! When we click our marker we need to get the information we added to our XML file.Before we add the information windows I just want to remove that ugly yellow line around our map, have you noticed already? When you focus on the map it shows a yellow line around it. I personally really don&#8217;t like that, so let&#8217;s remove it. Just add this line of code under our variables section:</p>
<pre name="code" class="javascript">
    	// No focus line
        stage.stageFocusRect = false;
    </pre>
<p>Ok thats done! Let&#8217;s add Info windows. Add a little more code to our createMarker() function:</p>
<pre name="code" class="javascript">
    	i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void
        {
            map.openInfoWindow(event.latLng, new InfoWindowOptions({
                                                                        titleHTML: ""+myTitle,
                                                                        contentHTML: ""+myContent
                                                                   }));

		});
    </pre>
<p>This is what our createMarker() function now looks like:</p>
<pre name="code" class="javascript">
    	function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker
		{
			// create Custom marker object
			var markerPin:marker_mc = new marker_mc();
			// If your marker is to big you can scale it down here
			markerPin.width = 20;
			markerPin.height = 20;

			var i:Marker = new Marker(
							  		latlng,
							  		new MarkerOptions({
														    hasShadow: true,
															icon: this.addChild(markerPin),
				            		                        tooltip: ""+tip
                    		                           })
									 );
			i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void
    		{
				map.openInfoWindow(event.latLng, new InfoWindowOptions({
																	       titleHTML: ""+myTitle,
                    		                                               contentHTML: ""+myContent
            		                                                  }));

    		});
			return i;
		}
    </pre>
<p>Test your movie and you will now have info windows too.</p>
</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/065_googleMaps/images/image22.jpg" border="0" /></div>
<h2>Step 23: Complete Code</h2>
<p>Well thats it! Congratulations, you just created a Google Map With 3D navigation and Custom markers! Very good job! Let&#8217;s have a<br />
    final look at our code:</p>
<pre name="code" class="javascript">
    	import com.google.maps.LatLng;
import com.google.maps.Map;
import com.google.maps.Map3D;
import com.google.maps.MapEvent;
import com.google.maps.MapType;
import com.google.maps.View;
import com.google.maps.geom.Attitude;
import com.google.maps.controls.NavigationControl;
import com.google.maps.controls.MapTypeControl;
import com.google.maps.controls.OverviewMapControl;
import com.google.maps.overlays.*;
import com.google.maps.InfoWindowOptions;
import com.google.maps.MapMouseEvent; 

// Variables
var map:Map3D;

// No focus line
stage.stageFocusRect = false; 

// Call the function to create the map
add_map();

// Function that adds the map on stage
function add_map()
{
	map = new Map3D();
    map.key = 'YOUR_API_KEY_HERE';
	map.setSize(new Point(stage.stageWidth, stage.stageHeight));
    map.addEventListener(MapEvent.MAP_READY, onMapReady);
    this.addChild(map);
}

// Function that will fire once map is created
function onMapReady(event:MapEvent):void
{
	map.setCenter(new LatLng(50.899197766773284, 4.486040573103489), 13);
	map.viewMode = View.VIEWMODE_PERSPECTIVE;
	map.setAttitude(new Attitude(20,40,0));
	map.addControl(new MapTypeControl());
    map.addControl(new OverviewMapControl());
    map.addControl(new NavigationControl());

	// Load the xml
	load_xml();
}

// Add Markers On The Map
function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker
{
	// create Custom marker object
	var markerPin:marker_mc = new marker_mc();
	// If your marker is to big you can scale it down here
	markerPin.width = 20;
	markerPin.height = 20;

	var i:Marker = new Marker(
							  latlng,
							  new MarkerOptions({
												    hasShadow: true,
													icon: this.addChild(markerPin),
				                                    tooltip: ""+tip
                                               })
							 );
	i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void
    {
		map.openInfoWindow(event.latLng, new InfoWindowOptions({
															       titleHTML: ""+myTitle,
                                                                   contentHTML: ""+myContent
                                                              }));

    });
	return i;
}

// Function that will load the xml
function loadXML(e:Event):void
{
	XML.ignoreWhitespace = true;
    var map_xml:XML = new XML(e.target.data);
	for (var i:Number = 0; i &lt; map_xml.location.length(); i++)
	{
		var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
		var tip = map_xml.location[i].name_tip;
		var myTitle:String = map_xml.location[i].title_tip;
		var myContent:String = map_xml.location[i].content_tip;

		map.addOverlay(createMarker(latlng, i, tip, myTitle, myContent));
	}
}

function load_xml()
{
	var xmlLoader:URLLoader = new URLLoader();
	xmlLoader.addEventListener(Event.COMPLETE, loadXML);
	xmlLoader.load(new URLRequest("locations.xml"));
}
    </pre>
<h2>Conclusion</h2>
<p>You can use this map on your website, edit the locations as you want, it&#8217;s up to you. Go ahead and experiment, if you have any cool results be sure to share them with us.</p>
<p>I hope you liked this tutorial, thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/make-the-most-of-google-maps-new-features-for-flash/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Create a Dynamic Bar Graph Generator Using XML + AS3</title>
		<link>http://active.tutsplus.com/tutorials/xml/create-a-dynamic-bar-graph-generator-using-xml-as3/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/create-a-dynamic-bar-graph-generator-using-xml-as3/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 12:00:54 +0000</pubDate>
		<dc:creator>Carlos Yanez</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=2639</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/028_graph/Preview/Preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>A  bar chart or bar graph is a chart with rectangular bars whose lengths are proportional to the values they represent. They&#8217;re commonly used for comparing two or more values that were taken over time or under different conditions, usually on small data sets.</p>
<p>In this tutorial, we&#8217;ll create a bar graph generator using XML and AS3.</p>
<p><span id="more-2639"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/028_graph/Src.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a><br />
<a href="http://activetuts.s3.cdn.plus.org/tuts/028_graph/Src/preview.html" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: Brief Overview</h2>
<p>Using ActionScript 3, we will get the necessary graph data from an XML file, then display the converted data into animated bars and an info area.</p>
<h2>Step 2: Starting</h2>
<p>Open Flash and create a new Flash File (ActionScript 3).</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/028_graph/Tutorial/1.jpg" alt="" /></div>
<p>Set the stage size to  600&#215;300 and add a gray radial background (#E6E6E6, #CCCCCC).</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/028_graph/Tutorial/2.jpg" alt="" /></div>
<p>Our graph generator will be created entirely by code, so this will be the only thing you will do in the Stage.</p>
<h2>Step 3: XML</h2>
<p>Open yout favorite XML editor (any text editor will work) and add the following lines:</p>
<pre name="code" class="xml">
&lt;?xml version=&quot;1.0&quot;?&gt;
	&lt;graphs width=&quot;50&quot;&gt;
		&lt;graph name=&quot;Yellow&quot; value=&quot;50&quot; color=&quot;0xFDC13E&quot;/&gt;
		&lt;graph name=&quot;Blue&quot; value=&quot;80&quot; color=&quot;0x25B7E2&quot;/&gt;
		&lt;graph name=&quot;Green&quot; value=&quot;30&quot; color=&quot;0xB8CF36&quot;/&gt;
		&lt;graph name=&quot;Red&quot; value=&quot;10&quot; color=&quot;0xE7473F&quot;/&gt;
	&lt;/graphs&gt;
</pre>
<p>This is the XML that we&#8217;ll use to get the data, we won&#8217;t be using the childrens&#8217; names, but the attributes.</p>
<ul>
<li><strong>width</strong>: The width of each bar.</li>
<li><strong>name</strong>: The name of the element, to be displayed in the info area.</li>
<li><strong>value</strong>: The value of that element, displayed at the top of the bars.</li>
<li><strong>color</strong>: The color of the bar, in Hexadecimal.</li>
</ul>
<p>This is the file that the end user will need to edit to show their own data.</p>
<h2>Step 4: ActionScript!</h2>
<p>It&#8217;s ActionScript time.</p>
<p>Create a new ActionScript File (Cmd + N) and save it as &quot;Graph.as&quot;, in your classes directory.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/028_graph/Tutorial/3.jpg" alt="" /></div>
<h2>Step 5: Package</h2>
<pre name="code" class="javascript">package
{</pre>
<p>The package keyword allows you to organize your code into groups that can be imported by other scripts. It&#8217;s recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: <em>myClasses</em>.</p>
<p>In the example, the class is stored in the same location as the Fla file.</p>
<h2>Step 6: Importing Necessary Classes</h2>
<p>These are the required classes, for a more detailed description about every class, please refer to the Flash Help (F1).</p>
<pre name="code" class="javascript">
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;</pre>
<h2>Step 7: Declaring and Extending the Class</h2>
<p>The <em>extends</em> keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.</p>
<pre name="code" class="javascript">
public class Graph extends Sprite
{</pre>
<p>In this example, the Graph class inherits all the methods and properties of the Sprite Class.</p>
<h2>Step 8: Variables</h2>
<p>These are the variables we will use, explained in the comments.</p>
<pre name="code" class="javascript">
private var graphContainer:Sprite = new Sprite();
private var xmlFile:XML; //The XML Object to parse the XML file
private var urlLoader:URLLoader = new URLLoader(); //The file loader
private var totalBars:int; //Stores the number of bars of the graph

private var tween:Tween; //A Tween object for animation
private var tf:TextFormat = new TextFormat(); //TextFormat</pre>
<h2>Step 9: Constructor</h2>
<p>The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object, or runs using the Document Class.</p>
<pre name="code" class="javascript">
public function Graph():void
{
	/* Text Format */

	tf.color = 0x666666;
	tf.size = 12;
	tf.font = "Helvetica";

	createGraphContainer();
	loadXML();
	createBars();
}</pre>
<h2>Step 10: Graph Container</h2>
<p>This function will create the <strong>x</strong> and <strong>y</strong> axis lines of the graph using the drawing API.</p>
<pre name="code" class="javascript">
private function createGraphContainer():void
{
	graphContainer.graphics.lineStyle(1, 0x9C9C9E);
	graphContainer.graphics.moveTo(30, 30);
	graphContainer.graphics.lineTo(30, 270);
	graphContainer.graphics.lineTo(570, 270);

	addChild(graphContainer);
}</pre>
<h2>Step 11: Load XML Function</h2>
<p>This is the function that handles the loading of the XML file. We specify a default paramenter to avoid calling the function using another .as file, instead we&#8217;re going to call it from the Document Class.</p>
<pre name="code" class="javascript">
private function loadXML(file:String = "graph.xml"):void //Your xml data file
{
	urlLoader.load(new URLRequest(file)); //Loads the file in the parameter
	urlLoader.addEventListener(Event.COMPLETE, parseXML); Calls a function when the load is complete
}</pre>
<h2>Step 12: Parse XML</h2>
<p>This function sets the data loaded to the XML object and calls the functions to create the graph using that data.</p>
<pre name="code" class="javascript">
private function parseXML(e:Event):void
{
	xmlFile = new XML(e.target.data);
	totalBars = xmlFile.children().length();

	createBars();
	displayNames();
}</pre>
<h2>Step 13: Create Bars</h2>
<p>This code handles the bar creation.</p>
<pre name="code" class="javascript">
private function createBars():void
{
	for (var i:int = 0; i < totalBars; i++)//This for checks the number of bars in the xml
	{
		var bar:Sprite = new Sprite(); //A sprite for every bar

		bar.graphics.beginFill(xmlFile.children()[i].@color); //Gets the color of the bar from the xml
		bar.graphics.drawRect(0, 0, xmlFile.@width, xmlFile.children()[i].@value); //Creates the bar according to the xml specified width
		bar.graphics.endFill();

		bar.x = 40 + (xmlFile.@width * i) + (10*i); //Bar position
		bar.y = 270 - bar.height;

		var val:TextField = new TextField(); //A TextField to display the value

		val.defaultTextFormat = tf;
		val.autoSize = TextFieldAutoSize.RIGHT;
		val.text = xmlFile.children()[i]. @ value; //Gets the value from xml

		val.x = 55 + (xmlFile.@width * i) + (10*i); //Textfield position
		val.y = 255 - bar.height;

		tween = new Tween(bar,"height",Strong.easeOut,0,bar.height,1,true); //Animates the bar

		addChild(bar); //Adds the sprites to stage
		addChild(val);
	}
}      </pre>
<h2>Step 14: Info Area</h2>
<p>Information about the graph will be displayed in the top-right corner, this function will take care of that.</p>
<pre name="code" class="javascript">
private function displayNames():void
{
	for (var i:int = 0; i &lt; totalBars; i++)
	{
		var color:Sprite = new Sprite(); //Creates sprites and textfields for every bar
		var names:TextField = new TextField();

		names.defaultTextFormat = tf;
		names.autoSize = TextFieldAutoSize.LEFT;
		names.text = xmlFile.children()[i]. @ name;

		/* Position */

		names.x = 500;
		names.y = 30 + (20 * i);

		/* Color squares */

		color.graphics.beginFill(xmlFile.children()[i].@color);
		color.graphics.drawRect(0, 0, 10, 10);
		color.graphics.endFill();

		color.x = 490;
		color.y = 31 + (20 * i);

		addChild(names);
		addChild(color);
	}
}</pre>
<h2>Step 15: Document Class</h2>
<p>Go back to the .Fla file and in the Properties Panel add &quot;Graph&quot; in the Class field to make this the Document Class.</p>
<h2>Conclusion</h2>
<p>Test your movie and see your graph appear on stage.</p>
<p>You can customize your graphs in many ways, using the XML file, and also adding new features with ActionScript. Try it!</p>
<p>I hope you liked this tutorial, Thanks for reading.</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/create-a-dynamic-bar-graph-generator-using-xml-as3/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Create a Super Modern Elastic Menu in AS3</title>
		<link>http://active.tutsplus.com/tutorials/xml/creating-a-super-modern-elastic-menu-in-as3/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/creating-a-super-modern-elastic-menu-in-as3/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 12:00:51 +0000</pubDate>
		<dc:creator>Sebastian Bratu</dc:creator>
				<category><![CDATA[Web Design]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://active.tutsplus.com/?p=2627</guid>
		<description><![CDATA[<img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/preview.jpg" alt="Create a Super Modern Elastic Menu in AS3">]]></description>
			<content:encoded><![CDATA[<p>Sometimes you just want to be very modern about your website. And how better to show people how cool you are as a flash programmer than to make them experience it themselves? In this tutorial I will show you how to create a modern menu with spring-like buttons. We&#8217;ll even make it customizable from xml!</p>
<p><span id="more-2627"></span></p>
<div class="tutorial_image">
<a href="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/sources.zip" target="_blank"><br />
<img src="http://activetuts.s3.cdn.plus.org/assets/icons/source.jpg" alt="" style="border:none"></a>
</div>
<h2>Preview</h2>
<p>Let&#8217;s take a quick look at what we&#8217;re working towards:</p>
<div class="tutorial_image">
<object data="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/preview.swf" type="application/x-shockwave-flash" width="600" height="200"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/preview.swf"></object>
</div>
<h2>Step 1: Preparing the document</h2>
<p>Create a new ActionScript 3 flash file and set the dimensions to 600 x 200 pixels. We&#8217;re setting these dimensions in order to have space for the buttons to follow the mouse. Set the framerate to 25 and the DocumentClass to <strong>ElasticMenu</strong>, a class which we will create after the design.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/1.jpg" alt="" /></div>
<p>Let&#8217;s make a background gradient which will be the base for our button. Create a rectangle and make it 150 x 40px. The size doesn&#8217;t matter at this time, because we will resize the rectangle to match the text size of the button.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/2.jpg" alt="" /></div>
<p> I can hear you asking: why not create a rectangle programatically with <em>Sprite.graphics.drawRectangle()</em>? I&#8217;ll show you why I chose this path. The reason behind making a movieclip on the stage is that we can actually cut through the rectangle to create a cool cut-out button like in this preview:</p>
<div class="tutorial_image">
<object data="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/preview2.swf" type="application/x-shockwave-flash" width="600" height="200"><param name="src" value="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/preview2.swf"></object>
</div>
<p>I&#8217;m not going into how to make this example here, but this method&#8217;s better in case you want to spice up the background of the button. That&#8217;s just a tip.</p>
<h2>Step 2: Creating the Background Movieclip</h2>
<p>Select the rectangle you just created and press F8 (Modify > Convert to Symbol) to make the background graphic and check Export for ActionScript. Give this movieclip the class name &#8220;GradBackground&#8221;. We will use this class name from ActionScript.</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/3.jpg" alt="" /></div>
<h2>Step 3: The XML File</h2>
<p>Now we&#8217;ll create the xml file to hold our configuration. From this file the flash movie will get the button name, the link location and the color. Create a new file next to the .fla source and name it <strong>menu.xml</strong> with the following:</p>
<pre name="code" class="xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;menu&gt;

        &lt;button&gt;
            &lt;name&gt;Home&lt;/name&gt;
            &lt;url&gt;http://flash.tutsplus.com&lt;/url&gt;
            &lt;color&gt;0xff0000&lt;/color&gt;
        &lt;/button&gt;

        &lt;button&gt;
            &lt;name&gt;About us&lt;/name&gt;
            &lt;url&gt;http://net.tutsplus.com&lt;/url&gt;
            &lt;color&gt;0xccff00&lt;/color&gt;
        &lt;/button&gt;

        &lt;button&gt;
            &lt;name&gt;Projects&lt;/name&gt;
            &lt;url&gt;http://vector.tutsplus.com&lt;/url&gt;
            &lt;color&gt;0x446677&lt;/color&gt;
        &lt;/button&gt;

        &lt;button&gt;
            &lt;name&gt;News&lt;/name&gt;
            &lt;url&gt;http://psd.tutsplus.com&lt;/url&gt;
            &lt;color&gt;0x004488&lt;/color&gt;
        &lt;/button&gt;

        &lt;button&gt;
            &lt;name&gt;Forum&lt;/name&gt;
            &lt;url&gt;http://photo.tutsplus.com&lt;/url&gt;
            &lt;color&gt;0x2244ff&lt;/color&gt;
        &lt;/button&gt;

        &lt;button&gt;
            &lt;name&gt;Contact&lt;/name&gt;
            &lt;url&gt;http://audio.tutsplus.com&lt;/url&gt;
            &lt;color&gt;0x232323&lt;/color&gt;
        &lt;/button&gt;

    &lt;/menu&gt;</pre>
<p>What happens here? We&#8217;re creating a &lt;button&gt; node for every button. You can add as many as you need, but not too many because they won&#8217;t have space to &#8220;be elastic&#8221; <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  In every button node there is a name tag, a url tag and a color tag, pretty basic.</p>
<h2>Step 4: Begin the Programming</h2>
<p>Now let&#8217;s get to building the actual flash menu. Create a new ActionScript file and name it <strong>ElasticMenu.as</strong>. For speed I have used the wildcard * to import all the classes in the package. After you finish the flash menu, you can modifiy the imports to only include what you need, to make the filesize smaller. Create the usual package and class name <strong>ElasticMenu</strong> with the required variables:</p>
<pre name="code" class="javascript">
package {

    import flash.display.*;
    import flash.text.*;
    import flash.net.*;
    import flash.events.*;
    import flash.utils.Timer;

	public class ElasticMenu extends MovieClip {

	var xml:XML;
	var buttons:Array;
	var tm:Timer;
	var maxdist:Number = 50;

	} 

}</pre>
<p>The <strong>xml</strong> variable will hold the actual xml loaded from the <strong>menu.xml</strong> file. The <strong>buttons</strong> variable is an array that will hold the button references.</p>
<p>The <strong>tm</strong> is a timer that will take care of the actual check for distance.</p>
<p>The <strong>maxdist</strong> variable will define at what distance the button will break from the mouse and return to its place.</p>
<h2>Step 5: XML Loading and Handling</h2>
<p>Ok, let&#8217;s create the constructor function, add the load operations and process the xml:</p>
<pre name="code" class="javascript">
public function ElasticMenu(){
	var req = new URLLoader();
	req.addEventListener( Event.COMPLETE, xml_loaded );
	req.load( new URLRequest('menu.xml') );
	buttons = new Array();
	tm = new Timer( 40 );
	tm.addEventListener( TimerEvent.TIMER, check_buttons );
}

private function xml_loaded( e:Event ){
	xml = XML( e.target.data );
	createButtons();
}
</pre>
<p>What&#8217;s happening here? We create a URLRequest object and add a complete event handler that will trigger the xml_loaded function when the xml is loaded.</p>
<p>We initialize the <strong>buttons</strong> array and the timer, and we tie the TIMER event to the <strong>check_buttons()</strong> function. This is the function that will check for the distance of the buttons. Once the xml is loaded, we pass it to the <strong>xml</strong> variable and build the buttons with the <strong>createButtons()</strong> function, which we will create next.</p>
<h2>Step 6: The createButtons Function</h2>
<p>Continue by creating the buttons and position them on the stage programtically:</p>
<pre name="code" class="javascript">

public function createButtons(){
	var sectw = (stage.stageWidth/(xml..button.length()+1) );
	for( var i=0; i&lt; xml..button.length(); i++){
		var m = new ElasticButton();
		m.x = sectw + (sectw*i);
		m.y = stage.stageHeight/2;
		m.init( xml..button[i] );
		addChild( m );
		buttons.push( m );
	}
	tm.start();
}
</pre>
<p>Ok, so we are defining the <strong>sectw</strong> variable, which is the stage split into the number of buttons plus one. Why? Because we will arrange the buttons to be exacly the same distance from each other and occupy all the stage width. To better understand this, look at the following image:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/4.jpg" alt="" /></div>
<p>Because we are centering the buttons on x and y axis, they will end up being at equal distances from one another. Then we are creating a for loop, insidew which we define every button as a new <strong>ElasticButton</strong> class, which we will code shortly. We place every button at <strong>sectw</strong> distance from one another and set their y to half the stage to center them. Then we add them to the stage and push them into the buttons array, for later use. But there is another function we call on the button which we&#8217;ll define in the ElasticButton class, which we pass the current xml button node.</p>
<h2>Step 7: The checkButtons Function</h2>
<p>Let&#8217;s continue with the main function triggered every 40 miliseconds by the timer:</p>
<pre name="code" class="javascript">

private function check_buttons( e:TimerEvent ){
	for( var b in buttons ){
		if( buttons[b].dragging ){
			buttons[b].x = mouseX;
			buttons[b].y = mouseY;
			if( buttons[b].getDistance() &gt; maxdist ){
				buttons[b].reset();
			}
		}
	}
}
</pre>
<p>Ok, let&#8217;s quickly explain what&#8217;s going on here so we can move on to the ElasticButton class:</p>
<p>First of all, we loop through all the buttons in the array and for each one we check if they have a dragging property with the value &#8220;true&#8221;. Basically if the mouse is over the button and if &#8220;yes&#8221;, we check if the <strong>getDistance()</strong> method of the <strong>ElasticButton</strong> class is higher than the <strong>maxdist</strong> variable. If it is higher, we call a <strong>reset()</strong> function on the button. We don&#8217;t know anything yet about these functions.</p>
<h2>Step 8: Making the ElasticButton Class</h2>
<p>OK, finally the class we have all been waiting for, the button class. This is where all the important things happen: finding out the distance, creating the text, background and calling <strong>reset()</strong> to return the button to its location.</p>
<pre name="code" class="javascript">

package {

	import flash.display.*;
	import flash.text.*;
	import flash.net.*;
	import flash.events.*;
	import flash.geom.ColorTransform;
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.*;
	import fl.motion.Color;

	public class ElasticButton extends MovieClip {

		var origin:Object;
		var textfield:TextField;
		var tf:TextFormat;
		var dragging:Boolean = false;
		var bg:Sprite;
		var url:String;
		var twx:Tween;
		var twy:Tween;
		var padding:Number = 8;
		var color:uint;
		var msk:Sprite;

		public function ElasticButton(){
			//do nothing
		}

	}
}
</pre>
<p>Let me explain the lines:</p>
<p>You&#8217;ll find that apart from importing the normal classes, we also import fl.transitions.Tween and TweenEvent, easing and the fl.motion.Color classes. We need the tween classes to tween the movie back to its origin and the color class to tint the background to the color in the xml.</p>
<p>We have a couple of variables here: </p>
<p>The <strong>origin</strong> object is an object which will hold the x and y position of the button. I could have made it a flash.geom.Point object but I&#8217;m too lazy to include another class for 2 variables!</p>
<p>We have a <strong>textfield</strong> variable which will hold the button label textfield, the <strong>tf</strong> variable which is a TextFormat object for text styling, the known <strong>dragging</strong> propery, a <strong>bg</strong> var which will be the background movieclip, a string with the url for the button, two variables to hold the tweens, a <strong>padding</strong> variable which will make the button a bit bigger, the <strong>color</strong> object and a <strong>msk</strong> var which will be a mask for the movieclip. We need this to make the rounded corner you saw in the preview!</p>
<h2>Step 9: init() Function</h2>
<p>Let&#8217;s do the init function, triggered by our parent class:</p>
<pre name="code" class="javascript">
public function init( node ){
	textfield = new TextField();
	tf = new TextFormat();
	tf.size = 14;
	tf.font = '_sans';
	tf.bold = true;
	tf.color = 0xffffff;
	tf.align = TextFormatAlign.CENTER;
	textfield.defaultTextFormat = tf;
	textfield.text = node..name;
	textfield.width = 65;
	textfield.height = 20;
	textfield.x = -(textfield.width / 2 );
	textfield.y = -(textfield.height / 2 );
	textfield.mouseEnabled = false;
	addChild( textfield );
	origin = new Object();
	origin.x = this.x;
	origin.y = this.y;
	color = node..color;
	createBG();
	url = node..url;
	dragging = false;
	this.buttonMode = true;
	this.addEventListener( MouseEvent.MOUSE_OVER, mouse_over );
	this.addEventListener( MouseEvent.CLICK, mouse_click );
}</pre>
<p>There is a lot already!</p>
<p>We create the textfield, assign it a textformat with certain properties (I won&#8217;t get into details here), set the colour to white, because the backgrounds will tend to be darker, we give it the text from the node passed as a parameter. Pretty standard. </p>
<p>It&#8217;s best to create a width and align the text to center so that different words will be beautifully aligned. You just have to make sure not to include a very long word, or the button will look ugly!</p>
<p>Next we have an interesting positioning of the textfield. We set the x to minus half the width and the y to minus half the height of the textfield, thus aligning the textfield exactly in the center. We need this in order to have a uniform calculation of maximum distance.</p>
<p>We set <strong>mouseEnabled</strong> to false for the textfield, to disable the mouse rolling off the button. I looked for this property for a <em>whole day</em> when I first started AS3 <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The <strong>origin</strong> object is initialized next and we create x and y properties with the x and y of the current movieclip (the ElasticButton class). When the button goes beyond the maxdist, we will return the button to these origin points.</p>
<p>There are a couple of more things going on here: We hold the color from the xml node in the <strong>color</strong> var, we hold the url of the button in the <strong>url</strong> var amd we call a <strong>createBG()</strong> function which we are yet to code.</p>
<p>We set dragging to false, buttonMode for the current ElasticButton to true and create the mouse over and click handlers.</p>
<h2>Step 10: createBG Function</h2>
<p>This function will take care of making the background and tint it according to the color in the xml:</p>
<pre name="code" class="javascript">
public function createBG(){
	bg = new GradBackground();
	var dbpad = padding*2;
	bg.width = textfield.width+dbpad;
	bg.height = textfield.height+dbpad;
	bg.x = -( (textfield.width+dbpad)/2);
	bg.y = -( (textfield.height+dbpad)/2);
	addChild(bg);
	var col = new Color(1,1,1,1);
	col.setTint( color, 0.4 );
	bg.transform.colorTransform = col;
	setChildIndex( bg, 0 );
}</pre>
<p>Here we make a GradBackground class, which is the movieclip we created in the fla source and give it the class name GradBackground. We set the width and height of the movieclip to the textfield width plus a variable <strong>dbpad</strong>. You&#8217;ll notice that I defined this variable for speed, so that I don&#8217;t type (padding * 2). Defining a new variable with the precomputed double padding is faster than calling this operation many times. We have to take care of the CPU too!</p>
<p>Why am I adding a padding variable? So that the button is bigger than the textfield. Look at this image to get a better understanding:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/5.jpg" alt="" /></div>
<p>I am also centering the bg movieclip like I did with the textfield: I set the x to minus half the height and minus half the width of the bg movieclip.
<p>Next I create a new Color with default attributes (rgb and alpha 1) and later use the <strong>setTint</strong>() function to make it a shade of the xml color. Because the Color class is a subclass of ColorTransform class, we can pass this colour directly to the movieclip transform.colorTransform object.</p>
<p>Lastly, we set the bg movieclip the depth 0, so everything will be above the background.</p>
<h2>Step 11: Event Handlers</h2>
<p>I&#8217;ll quickly go through the event handlers:</p>
<pre name="code" class="javascript">
private function mouse_over( e:MouseEvent ){
	dragging = true;
}

private function mouse_click( e:MouseEvent ){
	navigateToURL( new URLRequest( url ) );
}</pre>
<p>The event handlers are pretty simple: I set the dragging to true when the mouse hovers over the button. For the click handler I use the <strong>navigateToURL()</strong> function to go to the url requested. If you are building a flash site, this is where the action for page change would go.</p>
<h2>Step 12: The getDistance Function</h2>
<p>This is the most important function in the menu. Remember, we&#8217;re calling the <strong>getDistance</strong> function to see if it&#8217;s bigger than the <strong>maxdist</strong> var so we can reset the button. We&#8217;re using the algebraic equation of Pitagora to find the distance between 2 points:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/6.jpg" alt="" /></div>
<pre name="code" class="javascript">
public function getDistance(){
	return Math.sqrt( (this.x-origin.x)*(this.x-origin.x) + (this.y-origin.y)*(this.y-origin.y) );
}</pre>
<p>This will give us the distance between the button x and y and the origin x and y. That&#8217;s why we hold the origin variable.</p>
<h2>Step 13: The Reset Function</h2>
<p>This function is triggered when the distance from the origin is too high. At that point we tween the button back to its origin:</p>
<pre name="code" class="javascript">

public function reset(){
	dragging = false;
	twx = new Tween( this, 'x', Elastic.easeOut, this.x, origin.x, 0.4, true );
	twy = new Tween( this, 'y', Elastic.easeOut, this.y, origin.y, 0.4, true );
}
</pre>
<p>We set the dragging to false and create two tweens; one for the x and one for the y. We could have used another tweening library, used only one tween and passed an array to the tweening function, but the built-in Tween class from AS3 doesn&#8217;t support multiple properties, as far as I&#8217;m aware.</p>
<h2>Step 14: Rounding the Buttons</h2>
<p>Let me show you, as a bonus, how to make the first and last button round, like you saw in the preview. We create a new function <strong>makeStartButton()</strong> where we will build the rounded mask:</p>
<pre name="code" class="javascript">
public function makeStartButton(){
	msk = new Sprite();
	msk.graphics.beginFill(0x000000,1);
	msk.graphics.moveTo( 0, padding );
	msk.graphics.curveTo( 0, 0, padding, 0 );
	msk.graphics.lineTo( (padding*2)+textfield.width, 0 );
	msk.graphics.lineTo( (padding*2)+textfield.width, (padding*2)+textfield.height );
	msk.graphics.lineTo( 0, (padding*2)+textfield.height );
	msk.graphics.lineTo( 0, padding );
	msk.graphics.endFill();
	msk.x = bg.x;
	msk.y = bg.y;
	addChild( msk );
	bg.mask = msk;
}
</pre>
<p>Ok, this has to be explained:</p>
<p>We create a new Sprite and use the graphic&#8217;s class <strong>beginFill()</strong> to make a fill, the colour doesn&#8217;t matter. In order to understand what is going on let&#8217;s look at this image:</p>
<div class="tutorial_image"><img src="http://activetuts.s3.cdn.plus.org/tuts/025_ElasticMenu/tutorial/7.jpg" alt="" width="600" height="300" /></div>
<p>We construct the rounded background mask and add it to the displayList, setting it as a mask for the <strong>bg</strong> movieclip</p>
<h2>Step 15: Rounding the Second Button</h2>
<p>We use the same procedure, now with the curve on the right:</p>
<pre name="code" class="javascript">
public function makeEndButton(){
	var dbpad = padding*2;
	msk = new Sprite();
	msk.graphics.beginFill(0x000000,1);
	msk.graphics.lineTo( textfield.width + padding, 0 );
	msk.graphics.curveTo( textfield.width + dbpad, 0, textfield.width + dbpad, padding );
	msk.graphics.lineTo( dbpad + textfield.width, dbpad + textfield.height );
	msk.graphics.lineTo( 0, dbpad + textfield.height );
	msk.graphics.lineTo( 0, padding );
	msk.graphics.endFill();
	msk.x = bg.x;
	msk.y = bg.y;
	addChild( msk );
	bg.mask = msk;
}</pre>
<p>You&#8217;ll see that it&#8217;s the same technique, we just make the curve on the right and we add the mask to the <strong>bg</strong> movieclip.</p>
<h2>Step 16: The Final Touch</h2>
<p>We need to modify the ElasticMenu class to call these two functions on the first and the last buttons. In the createButtons() we make the following modifications (lines 8 &#8211; 13):</p>
<pre name="code" class="javascript">
public function createButtons(){
	var sectw = (stage.stageWidth/(xml..button.length()+1) );
	for( var i=0; i&lt; xml..button.length(); i++){
		var m = new ElasticButton();
		m.x = sectw + (sectw*i);
		m.y = stage.stageHeight/2;
		m.init( xml..button[i] );
		if( i == 0 ){
			m.makeStartButton();
		}
		if( i == xml..button.length()-1){
			m.makeEndButton();
		}
		addChild( m );
		buttons.push( m );
	}
	tm.start();
}</pre>
<p>So if the variable <strong>i</strong> is 0 (if it&#8217;s the first button) or if <strong>i </strong>is the <strong>xml..button.length() &#8211; 1</strong> (if it&#8217;s the last) we call the respective function.</p>
<p>Just remember, if you encounter any error, that the functions we call from the parent class, <strong>ElasticMenu</strong> have to be public in the <strong>ElasticButton</strong> class, otherwise you will get an error that the function does not exist!</p>
<p>That&#8217;s it! This is the whole code for the ElasticMenu class:</p>
<pre name="code" class="javascript">
package {
	import flash.display.*;
	import flash.text.*;
	import flash.net.*;
	import flash.events.*;
	import flash.utils.Timer;

	public class ElasticMenu extends MovieClip {

		var xml:XML;
		var buttons:Array;
		var tm:Timer;
		var maxdist:Number = 50;
		var line:Sprite;

		public function ElasticMenu(){
			var req = new URLLoader();
			req.addEventListener( Event.COMPLETE, xml_loaded );
			req.load( new URLRequest('menu.xml') );
			buttons = new Array();
			tm = new Timer( 40 );
			tm.addEventListener( TimerEvent.TIMER, check_buttons );
		}

		private function xml_loaded( e:Event ){
			xml = XML( e.target.data );
			createButtons();
		}

		public function createButtons(){
			var sectw = (stage.stageWidth/(xml..button.length()+1) );
			for( var i=0; i&lt; xml..button.length(); i++){
				var m = new ElasticButton();
				m.x = sectw + (sectw*i);
				m.y = stage.stageHeight/2;
				m.init( xml..button[i] );
				if( i == 0 ){
					m.makeStartButton();
				}
				if( i == xml..button.length()-1){
					m.makeEndButton();
				}
				addChild( m );
				buttons.push( m );
			}
			tm.start();
		}

		private function check_buttons( e:TimerEvent ){
			for( var b in buttons ){
				if( buttons[b].dragging ){
					buttons[b].x = mouseX;
					buttons[b].y = mouseY;
					if( buttons[b].getDistance() &gt; maxdist ){
						buttons[b].reset();
					}
				}
			}
		}
	}
}</pre>
<p>And for the ElasticButton class:</p>
<pre name="code" class="javascript">

package {

	import flash.display.*;
	import flash.text.*;
	import flash.net.*;
	import flash.events.*;
	import flash.geom.ColorTransform;
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.*;
	import fl.motion.Color;

	public class ElasticButton extends MovieClip {

		var origin:Object;
		var textfield:TextField;
		var tf:TextFormat;
		var dragging:Boolean = false;
		var bg:Sprite;
		var url:String;
		var twx:Tween;
		var twy:Tween;
		var padding:Number = 8;
		var color:uint;
		var msk:Sprite;

		public function ElasticButton(){
			//do nothing
		}

		public function init( node ){
			textfield = new TextField();
			tf = new TextFormat();
			tf.size = 14;
			tf.font = '_sans';
			tf.bold = true;
			tf.color = 0xffffff;
			tf.align = TextFormatAlign.CENTER;
			textfield.defaultTextFormat = tf;
			textfield.text = node..name;
			textfield.width = 65;
			textfield.height = 20;
			textfield.x = -(textfield.width / 2 );
			textfield.y = -(textfield.height / 2 );
			textfield.mouseEnabled = false;
			addChild( textfield );
			origin = new Object();
			origin.x = this.x;
			origin.y = this.y;
			color = node..color;
			createBG();
			url = node..url;
			dragging = false;
			this.buttonMode = true;
			this.addEventListener( MouseEvent.MOUSE_OVER, mouse_over );
			this.addEventListener( MouseEvent.CLICK, mouse_click );
		}

		public function createBG(){
			bg = new GradBackground();
			var dbpad = padding*2;
			bg.width = textfield.width+dbpad;
			bg.height = textfield.height+dbpad;
			bg.x = -( (textfield.width+dbpad)/2);
			bg.y = -( (textfield.height+dbpad)/2);
			addChild(bg);
			var col = new Color(1,1,1,1);
			col.setTint( color, 0.4 );
			bg.transform.colorTransform = col;
			setChildIndex( bg, 0 );
		}

		public function getDistance(){
			return Math.sqrt( (this.x-origin.x)*(this.x-origin.x) + (this.y-origin.y)*(this.y-origin.y) );
		}

		public function reset(){
			dragging = false;
			twx = new Tween( this, 'x', Elastic.easeOut, this.x, origin.x, 0.4, true );
			twy = new Tween( this, 'y', Elastic.easeOut, this.y, origin.y, 0.4, true );
		}

		private function mouse_over( e:MouseEvent ){
			dragging = true;
		}

		private function mouse_click( e:MouseEvent ){
			navigateToURL( new URLRequest( this.url ) );
		}

		public function makeStartButton(){
			msk = new Sprite();
			msk.graphics.beginFill(0x000000,1);
			msk.graphics.moveTo( 0, padding );
			msk.graphics.curveTo( 0, 0, padding, 0 );
			msk.graphics.lineTo( (padding*2)+textfield.width, 0 );
			msk.graphics.lineTo( (padding*2)+textfield.width, (padding*2)+textfield.height );
			msk.graphics.lineTo( 0, (padding*2)+textfield.height );
			msk.graphics.lineTo( 0, padding );
			msk.graphics.endFill();
			msk.x = bg.x;
			msk.y = bg.y;
			addChild( msk );
			bg.mask = msk;
		}

		public function makeEndButton(){
			var dbpad = padding*2;
			msk = new Sprite();
			msk.graphics.beginFill(0x000000,1);
			msk.graphics.lineTo( textfield.width + padding, 0 );
			msk.graphics.curveTo( textfield.width + dbpad, 0, textfield.width + dbpad, padding );
			msk.graphics.lineTo( dbpad + textfield.width, dbpad + textfield.height );
			msk.graphics.lineTo( 0, dbpad + textfield.height );
			msk.graphics.lineTo( 0, padding );
			msk.graphics.endFill();
			msk.x = bg.x;
			msk.y = bg.y;
			addChild( msk );
			bg.mask = msk;
		}

	}

}
</pre>
<h2>Conclusion</h2>
<p>Now, that was a pretty long tutorial! I hope I didn&#8217;t bore anybody. If you have any ideas about how we could improve the menu, add them to the comments.</p>
<p>Thank you for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/creating-a-super-modern-elastic-menu-in-as3/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>Build an OOP Tag Cloud in ActionScript 3.0</title>
		<link>http://active.tutsplus.com/tutorials/xml/build-an-oop-tag-cloud-in-actionscript-3-0/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/build-an-oop-tag-cloud-in-actionscript-3-0/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 12:00:11 +0000</pubDate>
		<dc:creator>Bruno Crociquia</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=1597</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/076_TagCloud/previewImage.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>In this tutorial I&#8217;ll show you how to build a flexible, animatable tagcloud using an Object Oriented Programming approach. I don&#8217;t believe in a right or wrong method, but rather several degrees of efficiency. If you have any constructive criticism on my code feel free to comment.</p>
<p>That said, lets start!</p>
<p><span id="more-1597"></span></p>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/076_TagCloud/tagCloud_source.zip" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/source.jpg" alt="" style="border:none"></a><br />
<a href="http://flashtuts.s3.cdn.plus.org/076_TagCloud/Preview/preview.html" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: How to Think Cloud</h2>
<p>This step is the most important one as it will dictate all the following steps. I start by looking at what I want to achieve and then break it into pieces, here&#8217;s my line of thought:</p>
<p><em>I want to be able to add multiple tag clouds in a page. I want it to be simple and customizable</em>. So what do I need to build this tag cloud?</p>
<p>I need a word array, a color, a font, minimum and maximum size definitions, oh and I need tag cloud elements to store that information, these elements should be textField based. Since I want several clouds the obvious choice is to create an instanceable tagCloud class that in this case will extend a Sprite.</p>
<p>Here&#8217;s what my main function should look like:</p>
<pre name="code" class="javascript">var tagCloud:TagCloud = new TagCloud(words,font,color,minFontsize,maxFontsize,fullsize)</pre>
<p>As you can tell there are plenty of parameters which need to be defined, the following will walk you trough the process. Create the following files:</p>
<ul>
<li>MainTagCloud.fla &#8211; this file will instantiate the tagcloud</li>
<li>TagCloud.as &#8211; this is the class that will create the tagcloud</li>
<li>TagCloudElement.as &#8211; this is the element that will populate the tagcloud</li>
</ul>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/076_TagCloud/Tutorial/1.jpg" alt="" /></div>
<h2>Step 2: Building the Mother Class</h2>
<p>Open TagCloud.as and write this code</p>
<pre name="code" class="javascript">
package
{

	public class TagCloud extends Sprite
	{

		public function TagCloud($word_array:Array,$font="Arial",$minFontSize:Number=10,$maxFontSize:Number=30,$elementColor:Number=0xffffff,$fullsize:Number=200):void
		{
			//here I assign the variables I receive to the class's variables
			wordArray = $word_array;
			font = $font
			minFontSize = $minFontSize
			maxFontSize = $maxFontSize
			elementColor = $elementColor
            fullsize = $fullsize
			//after setting the variables I build the cloud
			buildTagCloud();
		}
}
</pre>
<p>import these libraries:</p>
<pre name="code" class="javascript">
	import flash.text.Font;
	import TagCloudElement; // I'll get to this one later on
	import flash.display.Sprite;
	import flash.events.Event;
</pre>
<p>define these variables:</p>
<pre name="code" class="javascript">
		public var cloudElements:Array;
		private var wordArray:Array;
		private var word:String;
		private var relevancy:Number;
		private var size:int;
		private var element:TagCloudElement;
		private var minFontSize:Number;
		private var maxFontSize:Number;
		private var elementColor:Number;
		private var font:String;
		private var wordLength:int
        private var fullsize:Number
</pre>
<p>You&#8217;ll end up with something like this:</p>
<pre name="code" class="javascript">package
{
	//First import these packages:
	import flash.text.Font;
	import TagCloudElement; // I'll get to this one later on
	import flash.display.Sprite;
	import flash.events.Event;

	//Create a class that will extend a sprite
	public class TagCloud extends Sprite
	{
		//we need these variables to be abble to create the tagCloud
		public var cloudElements:Array;
		private var wordArray:Array;
		private var word:String;
		private var relevancy:Number;
		private var size:int;
		private var element:TagCloudElement;
		private var minFontSize:Number;
		private var maxFontSize:Number;
		private var elementColor:Number;
		private var font:String;
		private var wordLength:int
        private var fullsize:Number

		public function TagCloud($word_array:Array,$font="Arial",$minFontSize:Number=10,$maxFontSize:Number=30,$elementColor:Number=0xffffff,$fullsize:Number=200):void
		{
			//here I assign the variables I receive to the class's variables
			wordArray = $word_array;
			font = $font
			minFontSize = $minFontSize
			maxFontSize = $maxFontSize
			elementColor = $elementColor
            fullsize = $fullsize
			//after setting the variables i build the cloud
			buildTagCloud();
		}
	}
}</pre>
<h2>Step 3: Construct Your Main Function</h2>
<p>Here&#8217;s the main function that will build our cloud.</p>
<pre name="code" class="javascript">private function buildTagCloud() {
			//create an element array
			cloudElements = new Array();
			//gets the words lenght so i can iterate trought them and create the elements
			wordLength = getSingleWordList(wordArray).length
			for (var i=0; i&lt;wordLength; i++) {
				//this function returns me an array, its basically a filter, read more about it later on
				word = getSingleWordList(wordArray)[i]
				//this function uses the wikipedia formula to calculate the element size
				size = setElementSize(word, wordArray, minFontSize, maxFontSize);
				//creates a new element
				element = new TagCloudElement(word, size, font, elementColor);
				//stores the new element in the array
				cloudElements[i] = element
				//sets the transparency based on the size
				cloudElements[i].alpha=size/maxFontSize
				//just a random way to display the cloud elements
				cloudElements[i].x = Math.random() * fullsize
				cloudElements[i].y = Math.random() * fullsize
				addChild(cloudElements[i]);
				//performs a hit test trought the created objects
				cloudHitTest(i)
			}
		}</pre>
<h2>Step 4: Adding a Word Counter</h2>
<p>Let&#8217;s see how many words we&#8217;re dealing with.</p>
<pre name="code" class="javascript">private function countWord($word:String,$array:Array):int {
		var count:int=0;
			for (var i:int=0; i&lt;$array.length; i++) {
				if ($array[i].toLowerCase()==$word.toLowerCase()) {
					count+=1;
				}
			}
			return (count);
		}</pre>
<h2>Step 5: Set the Element Size</h2>
<p>I set the element size by using a formula found on wikipedia:</p>
<pre name="code" class="javascript">function setElementSize($word:String, $array:Array, $minSize:Number, $maxSize:Number):Number {
			var $size:Number = $maxSize * countWord($word, $array) / $array.length
			$size *= $minSize
			return $size
		}</pre>
<h2>Step 6: Creating a Single Word List</h2>
<p>This calls a filter for the array.</p>
<pre name="code" class="javascript">private function getSingleWordList($source:Array):Array {
			var $array:Array=$source.filter(singleWordFilter);
			return $array;
		}
</pre>
<p>Now set the filter rules.</p>
<pre name="code" class="javascript">
private function singleWordFilter(element:*, index:int, arr:Array):Boolean {
			if(arr[index+1]){
				if (arr[index].toLowerCase()!=arr[index+1].toLowerCase()) {
					return true;
				} else {
					return false;
				}
			}else {
				return false;
			}
		}</pre>
<h2>Step 7: How to HitTest</h2>
<p>We&#8217;re going to need to test for overlapping positions.</p>
<pre name="code" class="javascript">
		private function cloudHitTest($i) {
			for (var a:int=0; a < $i; a++) {
				//if HITS
				if (cloudElements[a].hitTestObject(cloudElements[$i])) {
					//Reposition
					cloudElements[$i].x = Math.random() * fullsize
					cloudElements[$i].y = Math.random() * fullsize
					addChild(cloudElements[$i]);
					//and test again
					cloudHitTest($i)
				}
			}

		}</pre>
<h2>Step 8: Setting up an Element Getter</h2>
<p>This is just a getter of an element by name, in case I need one over the main timeline.</p>
<pre name="code" class="javascript">
		public function getElementByName($name:String):TagCloudElement {
			var $auxCloudElement:TagCloudElement;
			for (var i:int=0; i &lt; wordLength; i++) {
				if (cloudElements[i].word == $name) {
					$auxCloudElement =  cloudElements[i]
				}
			}
			return $auxCloudElement
		}</pre>
<h2>Step 9: Inside the Element Class</h2>
<pre name="code" class="javascript">package
{

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldAutoSize;
	import flash.text.AntiAliasType;
   	import flash.text.GridFitType;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;

	public class TagCloudElement extends Sprite
	{
		public var word:String;
		public var urlpath:String;

		private var textCloudFormat:TextFormat;
		private var textCloud:TextField;

		public var font:String;
		public var size:Number;
		public var color:Number;

		// Same constructor as TagCloud, the element extends a Sprite
		// and Builds the Element based on a TextField
		public function TagCloudElement($word:String, $size:Number = 10, $font:String = "Arial", $elementColor:Number = 0xffffff):void
		{
			word = $word
			font = $font
			size = $size
			color = $elementColor

			buildElement();
		}

		private function buildElement() {
			//creates the textformat
			textCloudFormat = new TextFormat();
			// defines the font size and color
			textCloudFormat.font = font
			textCloudFormat.size = size
			textCloudFormat.color = color
			// creates a textField
			textCloud = new TextField();
			// embeds the font
			textCloud.embedFonts=true;
			//sets the antialias to readable equivalent
            textCloud.antiAliasType=AntiAliasType.ADVANCED;
			//defines its text
            textCloud.text=word
			//defines its size as automatic
            textCloud.autoSize=TextFieldAutoSize.LEFT;
			//fit to pixel
			textCloud.gridFitType = GridFitType.PIXEL
			// unselectable text
			textCloud.selectable = false;
			// assigns the textformat to the textfield
			textCloud.setTextFormat(textCloudFormat)
			// adds the MouseEvents listeners
			textCloud.addEventListener(MouseEvent.ROLL_OVER,rollOverCloudElement)
			textCloud.addEventListener(MouseEvent.ROLL_OUT,rollOutCloudElement)
			textCloud.addEventListener(MouseEvent.CLICK,clickCloudElement)
			addChild(textCloud);
		}

		private function rollOverCloudElement(e:MouseEvent){
			e.target.textColor = 0x666666;
		}
		private function rollOutCloudElement(e:MouseEvent){
			e.target.textColor = color
		}
		// I've made a link to a twitter search using the word selected.
		private function clickCloudElement(e:MouseEvent){
			navigateToURL(new URLRequest("http://search.twitter.com/search?q="+e.target.text),"_blank");
		}
	}
}</pre>
<h2>Step 10: Implementation</h2>
<p>Now, all that's left to be done is to implement this class in a real .fla file with all the stuff that you are accustumed to (ie:timeline) <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>You'll need to create a font so you can display the textFields, I embeded an Arial font.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/076_TagCloud/Tutorial/2.jpg" alt="" /></div>
<p>Then in the first frame of your .fla import the TagCloud class, set a stage.align to the top left (so that we can find the stage middle position without much work) and create a new instance of the font we just added to the library:</p>
<pre name="code" class="javascript">import TagCloud;

stage.align = StageAlign.TOP_LEFT
var wordArray:Array;
var tagCloud:TagCloud;
var arial:Arial = new Arial();//sets a new instance of Arial (already in the library)

function init() {
	//creates an array to populate the cloud
	wordArray = new Array("In","this","fashion,","text","clouds","may","become","a","generally","applied","tool","for","managing","growing","information","overload","by","using","automated","synthesis","and","summarization","In","the","information","saturated","future","or","the","information","saturated","present");
	//sorts the array alphabetically so i can filter later on
	wordArray.sort();
	// creates a new tagCloud instance
	tagCloud = new TagCloud(wordArray,arial.fontName,15,20,0x000000);
	// center's it to stage
	tagCloud.x = stage.stageWidth*0.5-tagCloud.width*0.5
	tagCloud.y = stage.stageHeight*0.5-tagCloud.height*0.5
	//adds to stage
	addChild(tagCloud);
}

init();</pre>
<h2>Step 11: Build an RSS Feed Request</h2>
<p>Now we need to grab a feed from somewhere so we can cloud it. I chose the CNN news feed. To be able to load an XML you need 4 objects including a urlRequest that will be used as a path to the feed.</p>
<pre name="code" class="javascript">
var requestFeed:URLRequest = new URLRequest("http://rss.cnn.com/rss/cnn_world.rss");
//an urlLoader so that we can load the request we need to make
var loaderFeed:URLLoader = new URLLoader()
// a XML object so we can store the data we recieve from the feed
var xmlFeed:XML;
//and last but not least a title array that i can explode the words from...
var titleWords:Array;
</pre>
<h2>Step 12: The Initialization Method</h2>
<p>Now inside our main function I need to add the complete event handler to the request so that it can be called upon a successful load.</p>
<pre name="code" class="javascript">
function init() {
	loaderFeed.addEventListener(Event.COMPLETE,onFeedComplete)
	//I will need the wordArray to be instantiated so I can store the words inside the feed
	wordArray = new Array()
	//we are ready to load the XML now
	loaderFeed.load(requestFeed);

}
</pre>
<h2>Step 13: The Data Structure</h2>
<p>The data structure is stored inside the e.target.data so we create the XML here by doing:</p>
<pre name="code" class="javascript">
function onFeedComplete(e:Event){
	xmlFeed = new XML(e.target.data)
	//after viewing the source of the rss feed I noticed the structure was something like channel.item.title so i'm using the titles as my word source.
	//I need to make an array to store all the words of a title and then add each on of those words inside the word array
	//for this I cycle through them

	for(var i:uint=0;i&lt;xmlFeed.channel.item.length();i++){
</pre>
<h2>Step 14: Building the Word List</h2>
<p>Instanciate the titleWords in every iteration so that you have a clean array everytime we have a new title.</p>
<pre name="code" class="javascript">

titleWords = new Array()
		//to make single words I split them on &quot;space&quot;
		titleWords = xmlFeed.channel.item[i].title.split(&quot; &quot;)
		//after them being split i iterate them to be added to the wordArray
		for(var j:uint=0;j&lt;titleWords.length;j++){
			//i use lowercase so i don't have any duplicated words
			wordArray.push(titleWords[j].toLowerCase());
		}

	}
    //after that being done I sort the word array alphabetically
	wordArray.sort();
	//and I start the tagCloud
	startTagCloud();    
</pre>
<h2>Step 15: Starting the Tag Cloud</h2>
<p>Now we have all the elements we need to make this tag cloud.</p>
<pre name="code" class="javascript">
try{
		tagCloud = new TagCloud(wordArray,arial.fontName,20,40,0xFFFFCD,300);
	}catch(e:Error){
		startTagCloud()
	}
	//all that is left is to define an X and a Y
	tagCloud.x = stage.stageWidth*0.5-tagCloud.width*0.5
	tagCloud.y = stage.stageHeight*0.5-tagCloud.height*0.5
	//and adding it to the stage
	addChild(tagCloud);
	//tadaaa we are done..
}

//don't forget to initialize the main function <img src='http://active.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
init();
</pre>
<h2>Step 16: The Final Code</h2>
<p>Here's the complete code for you to read fully.</p>
<pre name="code" class="javascript">
import TagCloud;
stage.align = StageAlign.TOP_LEFT

var wordArray:Array;
var tagCloud:TagCloud;
var arial:Arial = new Arial();

var requestFeed:URLRequest = new URLRequest(&quot;http://rss.cnn.com/rss/cnn_world.rss&quot;);
var loaderFeed:URLLoader = new URLLoader()
var xmlFeed:XML;
var titleWords:Array;

function init() {
	loaderFeed.addEventListener(Event.COMPLETE,onFeedComplete)
	wordArray = new Array()
	loaderFeed.load(requestFeed);
}

function onFeedComplete(e:Event){

  xmlFeed = new XML(e.target.data)

  	for(var i:uint=0;i&lt;xmlFeed.channel.item.length();i++){
  		titleWords = new Array()
  		titleWords = xmlFeed.channel.item[i].title.split(&quot; &quot;)
  		for(var j:uint=0;j&lt;titleWords.length;j++){
  			wordArray.push(titleWords[j].toLowerCase());
		}
	}
  wordArray.sort();
  startTagCloud();
}

function startTagCloud(){
  try{
 	  tagCloud = new TagCloud(wordArray,arial.fontName,20,40,0xFFFFCD,300);
   }catch(e:Error){
  	  startTagCloud()
	}
  tagCloud.x = stage.stageWidth*0.5-tagCloud.width*0.5
  tagCloud.y = stage.stageHeight*0.5-tagCloud.height*0.5

  addChild(tagCloud);
}

init();
</pre>
<h2>Conclusion</h2>
<p>I could have used linked lists and while loops to make this a bit faster, but you'll find it reasonably quick. One final note: be sure to set the random size big enough or you'll get a stackOverFlow error when the cloudElement can't find a place to be put.</p>
<p>I hope you liked this tutorial, thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/build-an-oop-tag-cloud-in-actionscript-3-0/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Create a Dynamic Slideshow with Actionscript 3.0 and XML &#8211; Part 3</title>
		<link>http://active.tutsplus.com/tutorials/screencasts/create-a-dynamic-slideshow-with-actionscript-3-0-and-xml-part-3/</link>
		<comments>http://active.tutsplus.com/tutorials/screencasts/create-a-dynamic-slideshow-with-actionscript-3-0-and-xml-part-3/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 12:00:43 +0000</pubDate>
		<dc:creator>Pierre Laveklint</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Screencasts]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=1776</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>Time to implement labels and navigation to our Slideshow Application. We&#8217;ll go over a lot in this third and final part of the series. This screencast is almost one and a half hours in total, so sit back, open up your files from <a href="http://flash.tutsplus.com/tutorials/screencasts/create-a-dynamic-slideshow-with-actionscript-30-and-xml-part-2/">Part 2</a> and let&#8217;s dig in!</p>
<p><span id="more-1776"></span></p>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/Source.zip" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/source.jpg" alt="" style="border:none"></a><br />
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/Preview/index.html" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/demo.jpg" alt="" style="border:none"></a>
</div>
<h3>View Screencast: Section One</h3>
<h4>Introduction</h4>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section1_intro_fontswf.flv" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/screen.jpg" alt="" style="border:none"></a>
</div>
<p>

<div class="tutorial_image">
		<div id="player10"><a href="http://get.adobe.com/flashplayer/">Get the Flash Player</a> to see this player.</div>
		<script type="text/javascript">
		var so = new SWFObject('http://active.tutsplus.com/wp-content/plugins/flash-player/player.swf','player10','600','450','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('flashvars','&file=http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section1_intro_fontswf.flv&bufferlength=1&skin=http://active.tutsplus.com/wp-content/plugins/flash-player/silver.swf&fullscreen=true');
		so.write('player10');
		</script>
		</div>

</p>
<h3>View Screencast: Section Two</h3>
<h4>Labels</h4>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section2_labels_audiofix.flv" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/screen.jpg" alt="" style="border:none"></a>
</div>
<p>

<div class="tutorial_image">
		<div id="player11"><a href="http://get.adobe.com/flashplayer/">Get the Flash Player</a> to see this player.</div>
		<script type="text/javascript">
		var so = new SWFObject('http://active.tutsplus.com/wp-content/plugins/flash-player/player.swf','player11','600','450','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('flashvars','&file=http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section2_labels_audiofix.flv&bufferlength=1&skin=http://active.tutsplus.com/wp-content/plugins/flash-player/silver.swf&fullscreen=true');
		so.write('player11');
		</script>
		</div>

</p>
<h3>View Screencast: Section Three</h3>
<h4>Tween Manager</h4>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section3_tweenmanager_audiofix.flv" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/screen.jpg" alt="" style="border:none"></a>
</div>
<p>

<div class="tutorial_image">
		<div id="player12"><a href="http://get.adobe.com/flashplayer/">Get the Flash Player</a> to see this player.</div>
		<script type="text/javascript">
		var so = new SWFObject('http://active.tutsplus.com/wp-content/plugins/flash-player/player.swf','player12','600','450','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('flashvars','&file=http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section3_tweenmanager_audiofix.flv&bufferlength=1&skin=http://active.tutsplus.com/wp-content/plugins/flash-player/silver.swf&fullscreen=true');
		so.write('player12');
		</script>
		</div>

</p>
<h3>View Screencast: Section Four</h3>
<h4>Navigation</h4>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section4_navigation_audiofix.flv" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/screen.jpg" alt="" style="border:none"></a>
</div>
<p>

<div class="tutorial_image">
		<div id="player13"><a href="http://get.adobe.com/flashplayer/">Get the Flash Player</a> to see this player.</div>
		<script type="text/javascript">
		var so = new SWFObject('http://active.tutsplus.com/wp-content/plugins/flash-player/player.swf','player13','600','450','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('flashvars','&file=http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section4_navigation_audiofix.flv&bufferlength=1&skin=http://active.tutsplus.com/wp-content/plugins/flash-player/silver.swf&fullscreen=true');
		so.write('player13');
		</script>
		</div>

</p>
<h3>View Screencast: Section Five</h3>
<h4>Roundup</h4>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section5_roundup_audiofix.flv" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/screen.jpg" alt="" style="border:none"></a>
</div>
<p>

<div class="tutorial_image">
		<div id="player14"><a href="http://get.adobe.com/flashplayer/">Get the Flash Player</a> to see this player.</div>
		<script type="text/javascript">
		var so = new SWFObject('http://active.tutsplus.com/wp-content/plugins/flash-player/player.swf','player14','600','450','9');
		so.addParam('allowscriptaccess','always');
		so.addParam('allowfullscreen','true');
		so.addParam('flashvars','&file=http://flashtuts.s3.cdn.plus.org/084_DynamicSlideShow3/DSP3_section5_roundup_audiofix.flv&bufferlength=1&skin=http://active.tutsplus.com/wp-content/plugins/flash-player/silver.swf&fullscreen=true');
		so.write('player14');
		</script>
		</div>

</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/screencasts/create-a-dynamic-slideshow-with-actionscript-3-0-and-xml-part-3/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		</item>
		<item>
		<title>Build a Smooth Hot Products List with the Caurina Tweener Class</title>
		<link>http://active.tutsplus.com/tutorials/xml/hot-products-list-with-caurina-tweener-class/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/hot-products-list-with-caurina-tweener-class/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 12:00:06 +0000</pubDate>
		<dc:creator>Yanko</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=1630</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Preview/preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>In this, his first tut at Flashtuts+, Yanko takes you through building a dynamic &#8216;Hot Products&#8217; list using old favourites ActionScript 3.0 and XML. He also smoothes things out by utilizing the Caurina Tweener class. Enjoy..</p>
<p><span id="more-1630"></span></p>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Preview/source.zip" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/source.jpg" alt="" style="border:none"></a><br />
<a href="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Preview/preview.html" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: File Structure</h2>
<p>We&#8217;ll begin by taking a look at the file structure of our project. The folder &#8220;caurina&#8221; is the Tweener class folder. You can download tweener from here:<a href="http://code.google.com/p/tweener/">Tweener</a>. In the folder &#8220;img&#8221; we&#8217;ll store our images that will be used in the application.<br />
The images in my case will have dimensions 60px wide and 55px high.
</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/1.jpg" alt="" /></div>
<h2>Step 2: XML</h2>
<p>Let`s create the XML file. Open your text editor and write:</p>
<pre name="code" class="xml">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;items&gt;
&lt;item title="Apple" price="$10" img="img/apple.jpg" link="http://www.google.com/"/&gt;
&lt;item title="Orange" price="$30" img="img/orange.jpg" link="http://cg.tutsplus.com/"/&gt;
&lt;item title="Lemon" price="$5" img="img/lemon.jpg" link="http://ae.tutsplus.com/"/&gt;
&lt;item title="Banana" price="$100" img="img/banana.jpg" link="http://audio.tutsplus.com/"/&gt;
&lt;item title="Water melon" price="$33" img="img/water_melon.jpg" link="http://vector.tutsplus.com/"/&gt;
&lt;item title="Lime" price="$21" img="img/lime.jpg" link="http://net.tutsplus.com/"/&gt;
&lt;item title="Pinapple" price="$20" img="img/pinapple.jpg" link="http://psd.tutsplus.com/"/&gt;
&lt;item title="Strawberry " price="$6" img="img/strawberry.jpg" link="http://tutsplus.com/"/&gt;
&lt;item title="Grapes " price="$15" img="img/grapes.jpg" link="http://flash.tutsplus.com/"/&gt;
&lt;/items&gt;
</pre>
<p>Save it as &#8220;data.xml&#8221; in the &#8220;project&#8221; folder.</p>
<h2>Step 3: The Idea</h2>
<p>The idea is to pass parameters to the main function &#8220;showData&#8221;. These parameters are &#8220;loopMin&#8221; and &#8220;loopMax&#8221; (see the code) values for a for() loop. Then we&#8217;ll filter the results with an if() statement and show them.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/2.jpg" alt="" /></div>
<h2>Step 4: Starting</h2>
<p>Create a new Flash file (ActionScript 3).</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/3.jpg" alt="" /></div>
<p>Set the stage size to 350&#215;350px</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/4.jpg" alt="" /></div>
<h2>Step 5: Background</h2>
<p>With the Rectangle tool (R) draw a shape with dimensions 350&#215;350px, type linear and colors #d3d3d3,#f1f1f1. Use the Gradient transform tool (F)  to adjust the gradient.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/5.jpg" alt="" /></div>
<p>Click on the shape then open align window and make sure that the &#8220;To stage&#8221; button is enabled. Align your shape vertically and horizontally.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/6.jpg" alt="" /></div>
<p>Create a new layer, then with the rectangle tool draw a shape 350&#215;40px with color #333333 and align it to the bottom.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/7.jpg" alt="" /></div>
<p>Now select both shapes and press F8 or Modify &gt; Convert to symbol, set type to movie clip and name it &#8220;main&#8221;.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/8.jpg" alt="" /></div>
<h2>Step 6: Adding Buttons</h2>
<p>Double-click on the movie clip to open it then rename Layer 1 to &#8220;background&#8221; and lock it. Create a new layer and name it &#8220;btns&#8221;. Select the Oval tool (O) then hold shift and drag a circle with stroke color:#0098FF and fill color:#FFFFFF dimensions 20X20px. Click on the stroke and change the stroke height to 3.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/9.jpg" alt="" /></div>
<p>Select your shape and press F8 to convert it to symbol. Choose type &#8220;Button&#8221; and name it &#8220;btn&#8221;.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/10.jpg" alt="" /></div>
<p>Double-click on the Button then right-click on the &#8220;Over&#8221; frame. Select Insert Keyframe.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/11.jpg" alt=”” /></div>
<p>Select fill color and change it to #d3d3d3.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/12.jpg" alt="" /></div>
<p>Insert Keyframe on the Down frame and change the fill color to #999999. Return to &#8220;main&#8221; movie clip and select the button. Change its instance name to &#8220;btn1&#8243;. Then drag the button to the bottom, drag to the right whilst holding &#8220;Alt&#8221; and release to create a second button. Change the instance name to &#8220;btn2&#8243;.</p>
<p>Repeat the procedure one more time to add a third button to stage and change its instance name to &#8220;btn3&#8243;. Open the Align window and disable &#8220;To stage&#8221; button. Select the three buttons and align them horizontally and verticaly. Enable &#8220;To stage&#8221; once again and align them vertically.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/13.jpg" alt="" /></div>
<h2>Step 7: Items</h2>
<p>Create a new layer and name it &#8220;items&#8221;. Draw a rectangle on it of 320&#215;90px color: type:linear #D3D3D3,#BBBBBB. Again, use the gradient transform tool to adjust the gradient. Select the shape and align it vertically to the stage. Press F8, type:Movie Clip and name it &#8220;item&#8221; &#8211; select top middle as the registration point.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/14.jpg" alt="" /></div>
<p>Double-click on the movie clip item. Them rename &#8220;layer 1&#8243; to &#8220;background&#8221;. Create a new layer and name it &#8220;txt&#8221;. Select the text tool(T) and set the text type to Dynamic Text. Then draw a text field, setting the instance name to &#8220;txt&#8221;. Type some text and set these properties:</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/15.jpg" alt="" /></div>
<p>Create new layer and name it &#8220;price&#8221;. With the text tool draw another text field and set its instance name to &#8220;price&#8221;. Set the text color to :#0099FF.</p>
<p>Now we&#8217;re gonna make a new button..</p>
<p>Create a new layer and name it &#8220;btn_more&#8221;. Now draw a shape with the rectangle tool of 60&#215;20px with color:#666666. Select it and press F8. Choose type:Button and assign it a name of &#8220;more&#8221;. Also, change its instance name to &#8220;more&#8221;. Open the button and add a new layer, call it text. Select the text tool and use it to draw a text field, type:static text. Enter the text &#8220;more&#8221; into the field, color:#FFFFFF;size:12;format:align center;.</p>
<p>Insert keyframes in the Over and Down frames, and change color as you like. I use: over:#999999; down:#333333;</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/16.jpg" alt="" /></div>
<p>Return to the main movie clip, select the item and change its instance name to item1. Hold the Alt key, drag the item down to add a copy to stage. Name the second item instance name to &#8220;item2&#8243;. Add another copy and change the instance name to &#8220;item3&#8243;. Align the items and you should have something like this:</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/17.jpg" alt="" /></div>
<h2>Step 8: Mask</h2>
<p>Now we&#8217;ll make a mask for the items. Make a new layer, name it &#8220;mask&#8221; and on it draw a rectangle 350&#215;310px.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/18.jpg" alt="" /></div>
<p>Right-click on the mask layer, then select mask:</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/081_HotProducts/Tutorial/tut_img/19.jpg" alt="" /></div>
<p>Make new layer, name it &#8220;actions&#8221; and paste the code that is in the following step.</p>
<h2>Step 9: Actionscript</h2>
<p>Take a look at the full code:</p>
<pre name="code" class="javascript">
//import Tweener
import caurina.transitions.*;
//&lt;vars&gt;

//&lt;xml&gt;
var xmlPath:String="data.xml";//holds link to xml file
var data_xml:XML;//XML Object
var data_Req:URLRequest=new URLRequest(xmlPath);//URL Request
var data_Loader:URLLoader = new URLLoader();//Loader
var xml_length:Number;//xml length
//&lt;/xml&gt;

//&lt;timer&gt;
var time:Number=5000;//5000 = 5 seconds
var timer:Timer=new Timer(time);//timer
//&lt;/timer&gt;

//&lt;items&gt;
var imgPath:String;//image path for first item
var imgPath2:String;//image path for second item
var imgPath3:String;//image path for third item
var item1Y:Number=item1.y;//item 1 y value
var item2Y:Number=item2.y;//item 2 y value
var item3Y:Number=item3.y;//item 3 y value
//&lt;/items&gt;

//&lt;other&gt;
var currentBtn:Number=1;//wich btn is pressed
var min:Number;//min value used in function hideNshow()
var max:Number;//max value used in function hideNshow()
//&lt;/other&gt;

//&lt;/vars&gt;
//&lt;functions&gt;----------------------------------------------------
function xmlLoaded(event:Event):void {//xml Loaded function
	data_xml=new XML(data_Loader.data);//get data prom XML file
	xml_length=data_xml.item.length();//xml length
	min=xml_length-6;//set min value to second result
	max=xml_length-2;//set max velue to second resuld
	function showData(loopMin:Number,loopMax:Number) {//Main Function

		var i:Number;//var for for loop
		var loopMaxResult=loopMax-2;//var for third result
		var loopSecondResult=loopMax-3;//var for second result

		for (i=loopMin; i&lt;loopMax; i++) {//for loop
			if (i==loopMin) {//first result item 1

				fData(item1,i);//call fData function to fill item 1
				//&lt;load the image&gt;
				imgPath=data_xml.item[i].@img;//get img url from xml
				var imgRequest:URLRequest=new URLRequest(imgPath);//URL request
				var imgLoader:Loader=new Loader();//image Loader
				imgLoader.load(imgRequest);//load the image
				item1.addChild(imgLoader);//add first image to item 1
				imgLoader.x=-150;//image x value
				imgLoader.y=15;//image y value
				//&lt;/load image&gt;

			}//end if
			if (i==loopSecondResult) {//second result

				fData(item2,i);//call fData function to fill item 2
				//&lt;load the image&gt;
				imgPath2=data_xml.item[i].@img;//get img url from xml
				var imgRequest2:URLRequest=new URLRequest(imgPath2);//URL request
				var imgLoader2:Loader=new Loader();//image Loader
				imgLoader2.load(imgRequest2);//load the image
				item2.addChild(imgLoader2);//add first image to item 2
				imgLoader2.x=-150;//image x value
				imgLoader2.y=15;//image y value
				//&lt;/load image&gt;

			}//end if
			if (i==loopMaxResult) {//third result

				fData(item3,i);//call fData function to fill item 3
				//&lt;load the image&gt;
				imgPath3=data_xml.item[i].@img;//get img url from xml
				var imgRequest3:URLRequest=new URLRequest(imgPath3);//URL request
				var imgLoader3:Loader=new Loader();//image Loader
				imgLoader3.load(imgRequest3);//load the image
				item3.addChild(imgLoader3);//add first image to item 3
				imgLoader3.x=-150;//image x value
				imgLoader3.y=15;//image y value
				//&lt;/load image&gt;

			}//end if

		}// end for
		function fData(item:MovieClip,iValue:int) {//function that fill data into items
			var moreURL:String;//url for button more

			item.txt.text=data_xml.item[iValue].@title;//fill item title
			item.price.text=data_xml.item[iValue].@price;//fill item price
			moreURL=data_xml.item[iValue].@link;//item link
			item.more.addEventListener(MouseEvent.CLICK, gotoURL);//event listener for more btn
			function gotoURL(e:MouseEvent):void {//click event function
				var myURL:URLRequest=new URLRequest(moreURL);//URL request
				navigateToURL(myURL);//go to item link 

			}//end function gotoURL

			// function for show N hide items
			function hideNshow(effTime:Number,effTransition:String,iMin:Number,iMax:Number) {
				//&lt;hide items&gt;
				timer.stop();//stop the timer
				Tweener.addTween(item3, {y:330,alpha:0, time:effTime, transition:effTransition});//hide item 3
				Tweener.addTween(item2, {y:247,alpha:0, time:effTime,delay:0.3, transition:effTransition});//hide item 2
				Tweener.addTween(item1, {y:163,alpha:0,time:effTime, delay:0.6,transition:effTransition,onComplete:Show});//hide item 1,
				//when done call function Show()
				//&lt;/hide items&gt;
				function Show() {//show items
					//&lt;show items&gt;
					currentBtn+=1;//add 1 to current btn value
					if (currentBtn==4) {//if currentBtn value is equal to 4 set value to 1 because we have only 3 btns
						currentBtn=1;//set it to 1
					}//end if

					item1.removeChild(imgLoader);//remove image from item 1
					item2.removeChild(imgLoader2);//remove image from item 2
					item3.removeChild(imgLoader3);//remove image from item 3

					showData(iMin,iMax);//call function showData with parameters iMin and iMax (values of  min and max vars)

					min-=3;//decrease the min value to show next 3 results from xml
					max-=3;//decrease the max value to show next 3 results from xml
					if (max==xml_length-8) {//if max value
						min=xml_length-3;//set min value to show first result
						max=xml_length+1;//set max value to show first result
					}//end if

					Tweener.addTween(item3, {y:item3Y,alpha:1, time:2,delay:0.6, transition:"easeOutExpo"});//show item3
					Tweener.addTween(item2, {y:item2Y,alpha:1, time:2,delay:0.3, transition:"easeOutExpo"});//show item2
					Tweener.addTween(item1, {y:item1Y,alpha:1, time:2, transition:"easeOutExpo"});//show item1
					timer.start();
					//&lt;/show items&gt;
				}//end function Show
			}//end function hideNshow
			function timerEvent() {//function for timer event
				hideNshow(2,"easeInOutQuart",min,max);//call function hideNshow
			}
			//btn 1 function
			function btn1Clicked(e:MouseEvent) {
				min=xml_length-3;//set min value
				max=xml_length+1;//set max value
				hideNshow(2,"easeInOutQuart",min,max);//call function hideNshow
				currentBtn=0;//set surrent Btn
				btnControl(1);//call function btnControl
			}
			//btn 2 function
			function btn2Clicked(e:MouseEvent) {
				min=xml_length-6;
				max=xml_length-2;
				hideNshow(2,"easeInOutQuart",min,max);
				currentBtn=1;
				btnControl(2);
			}
			//btn 3 function
			function btn3Clicked(e:MouseEvent) {
				min=xml_length-9;
				max=xml_length-5;
				hideNshow(2,"easeInOutQuart",min,max);
				currentBtn=2;
				btnControl(3);

			}
			function btnControl(btnNumber:Number) {
				//some case switch......
				switch (btnNumber) {
					case 1 ://when btn 1 is active
						btn1.alpha=0.5;//set alpha
						btn1.mouseEnabled=false;//disable button
						Tweener.addTween(btn1, {width:30,height:30,time:2,transition:"easeOutExpo"});//change btn width and height
						btn2.alpha=1;//set alpha
						btn2.mouseEnabled=true;//enable btn
						Tweener.addTween(btn2, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn3.alpha=1;//set alpha
						btn3.mouseEnabled=true;//enable btn
						Tweener.addTween(btn3, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						break;
					case 2 ://when btn 2 is active
						btn1.alpha=1;//set alpha
						btn1.mouseEnabled=true;//enable btn
						Tweener.addTween(btn1, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn2.alpha=0.5;//set alpha
						btn2.mouseEnabled=false;//disable button
						Tweener.addTween(btn2, {width:30,height:30,time:2,transition:"easeOutExpo"});//change btn width and height
						btn3.alpha=1;//set alpha
						btn3.mouseEnabled=true;//enable btn
						Tweener.addTween(btn3, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						break;
					case 3 ://when btn 3 is active
						btn1.alpha=1;//set alpha
						btn1.mouseEnabled=true;//enable btn
						Tweener.addTween(btn1, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn2.alpha=1;//set alpha
						btn2.mouseEnabled=true;//enable btn
						Tweener.addTween(btn2, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn3.alpha=0.5;//set alpha
						btn3.mouseEnabled=false;//disable button
						Tweener.addTween(btn3, {width:30,height:30,time:2,transition:"easeOutExpo"});//change btn width and height
						break;

				}//end Switch
			}//end function btnControl
			//&lt;event listeners&gt;
			//timer
			timer.addEventListener(TimerEvent.TIMER, timerEvent);
			timer.start();
			//buttons
			btn1.addEventListener(MouseEvent.CLICK, btn1Clicked);//Listens for btn1 click and call function
			btn2.addEventListener(MouseEvent.CLICK, btn2Clicked);//Listens for btn2 click and call function
			btn3.addEventListener(MouseEvent.CLICK, btn3Clicked);//Listens for btn3 click and call function
			//&lt;/event listeners&gt;
			//show wich btns is active
			if (currentBtn==1) {
				btnControl(1);//call btnControl function
			} else if (currentBtn==2) {
				btnControl(2);//call btnControl function
			} else if (currentBtn==3) {
				btnControl(3);
			}//end if
		}//end function fData

	}//end function ShowData
	showData(xml_length-3,xml_length+1);//show First Result

}
//end xml Loaded function
//&lt;/functions&gt;---------------------------------------------------

//&lt;call functions&gt;
data_Loader.load(data_Req);
data_Loader.addEventListener(Event.COMPLETE, xmlLoaded);
//&lt;/call functions&gt;
</pre>
<h2>Step 10: Vars</h2>
<pre name="code" class="javascript">
//import Tweener
import caurina.transitions.*;
//&lt;vars&gt;

//&lt;xml&gt;
var xmlPath:String="data.xml";//holds link to xml file
var data_xml:XML;//XML Object
var data_Req:URLRequest=new URLRequest(xmlPath);//URL Request
var data_Loader:URLLoader = new URLLoader();//Loader
var xml_length:Number;//xml length
//&lt;/xml&gt;

//&lt;timer&gt;
var time:Number=5000;//5000 = 5 seconds
var timer:Timer=new Timer(time);//timer
//&lt;/timer&gt;

//&lt;items&gt;
var imgPath:String;//image path for first item
var imgPath2:String;//image path for second item
var imgPath3:String;//image path for third item
var item1Y:Number=item1.y;//item 1 y value
var item2Y:Number=item2.y;//item 2 y value
var item3Y:Number=item3.y;//item 3 y value
//&lt;/items&gt;

//&lt;other&gt;
var currentBtn:Number=1;//wich btn is pressed
var min:Number;//min value used in function hideNshow()
var max:Number;//max value used in function hideNshow()
//&lt;/other&gt;

//&lt;/vars&gt;
</pre>
<h2>Step 11: xmlLoaded</h2>
<pre name="code" class="javascript">
function xmlLoaded(event:Event):void {//xml Loaded function
	data_xml=new XML(data_Loader.data);//get data prom XML file
	xml_length=data_xml.item.length();//xml length
	min=xml_length-6;//set min value to second result
	max=xml_length-2;//set max velue to second resuld
</pre>
<p>When the xml file is loaded, an event listener calls the xmlLoaded function.</p>
<h2>Step 12: showData</h2>
<pre name="code" class="javascript">
function showData(loopMin:Number,loopMax:Number) {//Main Function

		var i:Number;//var for for loop
		var loopMaxResult=loopMax-2;//var for third result
		var loopSecondResult=loopMax-3;//var for second result
        for (i=loopMin; i&lt;loopMax; i++) {//for loop
			if (i==loopMin) {//first result item 1

				fData(item1,i);//call fData function to fill item 1
				//&lt;load the image&gt;
				imgPath=data_xml.item[i].@img;//get img url from xml
				var imgRequest:URLRequest=new URLRequest(imgPath);//URL request
				var imgLoader:Loader=new Loader();//image Loader
				imgLoader.load(imgRequest);//load the image
				item1.addChild(imgLoader);//add first image to item 1
				imgLoader.x=-150;//image x value
				imgLoader.y=15;//image y value
				//&lt;/load image&gt;

			}//end if
			if (i==loopSecondResult) {//second result

				fData(item2,i);//call fData function to fill item 2
				//&lt;load the image&gt;
				imgPath2=data_xml.item[i].@img;//get img url from xml
				var imgRequest2:URLRequest=new URLRequest(imgPath2);//URL request
				var imgLoader2:Loader=new Loader();//image Loader
				imgLoader2.load(imgRequest2);//load the image
				item2.addChild(imgLoader2);//add first image to item 2
				imgLoader2.x=-150;//image x value
				imgLoader2.y=15;//image y value
				//&lt;/load image&gt;

			}//end if
			if (i==loopMaxResult) {//third result

				fData(item3,i);//call fData function to fill item 3
				//&lt;load the image&gt;
				imgPath3=data_xml.item[i].@img;//get img url from xml
				var imgRequest3:URLRequest=new URLRequest(imgPath3);//URL request
				var imgLoader3:Loader=new Loader();//image Loader
				imgLoader3.load(imgRequest3);//load the image
				item3.addChild(imgLoader3);//add first image to item 3
				imgLoader3.x=-150;//image x value
				imgLoader3.y=15;//image y value
				//&lt;/load image&gt;

			}//end if

		}// end for
</pre>
<p>The function &#8220;showData&#8221; passes two parameters &#8220;loopMin&#8221; and &#8220;loopMax&#8221; these are the values for the for() loop. &#8220;loopMaxResult&#8221; and &#8220;loopSecondResult&#8221; we use in an if() statement to separate three results. If we have an array with 3 elements, the first element will be with key [0] and the last with key[2](0,1,2). To loop through the array with for() our loopMin value must be=0 and our loopMax=4. To know in which item we need to put data we use if (i==loopMin) this will display the first result in the first item, if (i==loopSecondResult) displays the second result and if (i==loopMaxResult) the third result.</p>
<h2>Step 13: Function fData</h2>
<pre name="code" class="javascript">
function fData(item:MovieClip,iValue:int) {//function that fill data into items
			var moreURL:String;//url for button more

			item.txt.text=data_xml.item[iValue].@title;//fill item title
			item.price.text=data_xml.item[iValue].@price;//fill item price
			moreURL=data_xml.item[iValue].@link;//item link
			item.more.addEventListener(MouseEvent.CLICK, gotoURL);//event listener for more btn
			function gotoURL(e:MouseEvent):void {//click event function
				var myURL:URLRequest=new URLRequest(moreURL);//URL request
				navigateToURL(myURL);//go to item link 

			}//end function gotoURL
</pre>
<p>Function fData passes two parameters. One is the movie clip instance name and the second is i value. Here we add data from the xml document to our movie clips and also make the button &#8220;more&#8221; open links from  the xml.</p>
<h2>Step 14: hideNshow</h2>
<pre name="code" class="javascript">
// function for show N hide items
			function hideNshow(effTime:Number,effTransition:String,iMin:Number,iMax:Number) {
				//&lt;hide items&gt;
				timer.stop();//stop the timer
				Tweener.addTween(item3, {y:330,alpha:0, time:effTime, transition:effTransition});//hide item 3
				Tweener.addTween(item2, {y:247,alpha:0, time:effTime,delay:0.3, transition:effTransition});//hide item 2
				Tweener.addTween(item1, {y:163,alpha:0,time:effTime, delay:0.6,transition:effTransition,onComplete:Show});//hide item 1,
				//when done call function Show()
				//&lt;/hide items&gt;
				function Show() {//show items
					//&lt;show items&gt;
					currentBtn+=1;//add 1 to current btn value
					if (currentBtn==4) {//if currentBtn value is equal to 4 set value to 1 because we have only 3 btns
						currentBtn=1;//set it to 1
					}//end if

					item1.removeChild(imgLoader);//remove image from item 1
					item2.removeChild(imgLoader2);//remove image from item 2
					item3.removeChild(imgLoader3);//remove image from item 3

					showData(iMin,iMax);//call function showData with parameters iMin and iMax (values of  min and max vars)

					min-=3;//decrease the min value to show next 3 results from xml
					max-=3;//decrease the max value to show next 3 results from xml
					if (max==xml_length-8) {//if max value
						min=xml_length-3;//set min value to show first result
						max=xml_length+1;//set max value to show first result
					}//end if

					Tweener.addTween(item3, {y:item3Y,alpha:1, time:2,delay:0.6, transition:"easeOutExpo"});//show item3
					Tweener.addTween(item2, {y:item2Y,alpha:1, time:2,delay:0.3, transition:"easeOutExpo"});//show item2
					Tweener.addTween(item1, {y:item1Y,alpha:1, time:2, transition:"easeOutExpo"});//show item1
					timer.start();
					//&lt;/show items&gt;
				}//end function Show
			}//end function hideNshow
</pre>
<p>Function hideNshow passes 4 parameters.</p>
<ol>
<li>effTime &#8211; time in seconds that is used in tweener animation</li>
<li>effeffTransition &#8211; type of tweener transition</li>
<li>iMin &#8211; var min value</li>
<li>iMax &#8211; var max value</li>
</ol>
<p>When item1 animation is completed tweener calls the  function &#8220;Show&#8221; (which brings items back but removes images from each one) and runs the  &#8220;showData&#8221; function to fill them with the next results from our xml file. Additionally, the value of currentBtn is increased by one. Lastly, the timer is started.</p>
<h2>Step 15: timeEvent</h2>
<pre name="code" class="javascript">
function timerEvent() {//function for timer event
				hideNshow(2,"easeInOutQuart",min,max);//call function hideNshow
			}
            </pre>
<p>This function is called when the timer count down 5 seconds.</p>
<h2>Step 16: Buttons functions</h2>
<pre name="code" class="javascript">
//btn 1 function
			function btn1Clicked(e:MouseEvent) {
				min=xml_length-3;//set min value
				max=xml_length+1;//set max value
				hideNshow(2,"easeInOutQuart",min,max);//call function hideNshow
				currentBtn=0;//set surrent Btn
				btnControl(1);//call function btnControl
			}
			//btn 2 function
			function btn2Clicked(e:MouseEvent) {
				min=xml_length-6;
				max=xml_length-2;
				hideNshow(2,"easeInOutQuart",min,max);
				currentBtn=1;
				btnControl(2);
			}
			//btn 3 function
			function btn3Clicked(e:MouseEvent) {
				min=xml_length-9;
				max=xml_length-5;
				hideNshow(2,"easeInOutQuart",min,max);
				currentBtn=2;
				btnControl(3);

			}
</pre>
<p>These are the functions that event listeners for buttons call.</p>
<h2>Step 17: btnControl function</h2>
<pre name="code" class="javascript">
			function btnControl(btnNumber:Number) {
				//some case switch......
				switch (btnNumber) {
					case 1 ://when btn 1 is active
						btn1.alpha=0.5;//set alpha
						btn1.mouseEnabled=false;//disable button
						Tweener.addTween(btn1, {width:30,height:30,time:2,transition:"easeOutExpo"});//change btn width and height
						btn2.alpha=1;//set alpha
						btn2.mouseEnabled=true;//enable btn
						Tweener.addTween(btn2, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn3.alpha=1;//set alpha
						btn3.mouseEnabled=true;//enable btn
						Tweener.addTween(btn3, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						break;
					case 2 ://when btn 2 is active
						btn1.alpha=1;//set alpha
						btn1.mouseEnabled=true;//enable btn
						Tweener.addTween(btn1, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn2.alpha=0.5;//set alpha
						btn2.mouseEnabled=false;//disable button
						Tweener.addTween(btn2, {width:30,height:30,time:2,transition:"easeOutExpo"});//change btn width and height
						btn3.alpha=1;//set alpha
						btn3.mouseEnabled=true;//enable btn
						Tweener.addTween(btn3, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						break;
					case 3 ://when btn 3 is active
						btn1.alpha=1;//set alpha
						btn1.mouseEnabled=true;//enable btn
						Tweener.addTween(btn1, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn2.alpha=1;//set alpha
						btn2.mouseEnabled=true;//enable btn
						Tweener.addTween(btn2, {width:20,height:20,time:2,transition:"easeOutExpo"});//change btn width and height
						btn3.alpha=0.5;//set alpha
						btn3.mouseEnabled=false;//disable button
						Tweener.addTween(btn3, {width:30,height:30,time:2,transition:"easeOutExpo"});//change btn width and height
						break;

				}//end Switch
			}//end function btnControl
</pre>
<p>btnControl passes one parameter &#8220;btnNumber&#8221; which is used in a switch statement to change the properties of buttons when they&#8217;re clicked or active.</p>
<h2>Step 18: Event Listeners</h2>
<pre name="code" class="javascript">
            //&lt;event listeners&gt;
			//timer
			timer.addEventListener(TimerEvent.TIMER, timerEvent);
			timer.start();
			//buttons
			btn1.addEventListener(MouseEvent.CLICK, btn1Clicked);//Listens for btn1 click and call function
			btn2.addEventListener(MouseEvent.CLICK, btn2Clicked);//Listens for btn2 click and call function
			btn3.addEventListener(MouseEvent.CLICK, btn3Clicked);//Listens for btn3 click and call function
			//&lt;/event listeners&gt;
</pre>
<h2>Step 19: Which Button is Active?</h2>
<pre name="code" class="javascript">
//show which button is active
			if (currentBtn==1) {
				btnControl(1);//call btnControl function
			} else if (currentBtn==2) {
				btnControl(2);//call btnControl function
			} else if (currentBtn==3) {
				btnControl(3);
			}//end if
</pre>
<p>We use three if() statements to see which button is currently active.</p>
<h2>Step 20: Call functions</h2>
<pre name="code" class="javascript">
}//end function fData

	}//end function ShowData
	showData(xml_length-3,xml_length+1);//show First Result

}
//end xml Loaded function
//&lt;/functions&gt;---------------------------------------------------

//&lt;call functions&gt;
data_Loader.load(data_Req);
data_Loader.addEventListener(Event.COMPLETE, xmlLoaded);
//&lt;/call functions&gt;
</pre>
<p>After end of function &#8220;ShowData&#8221; we run it with parameters (xml_length-3,xml_length+1) to see the first results when we run the application. We add event listener to data_loader so when the xml file is loaded and ready to use we call the &#8220;xmlLoaded&#8221; function.</p>
<h2>Conclusion</h2>
<p>You can modify the app as you like, change transition types, timer seconds or for example make it to show recent posts, news, tweets etc. I hope you enjoyed following along!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/hot-products-list-with-caurina-tweener-class/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Create a Responsive Image Scroller in ActionScript 3.0</title>
		<link>http://active.tutsplus.com/tutorials/xml/create-a-responsive-xml-image-scroller-in-actionscript-3-0/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/create-a-responsive-xml-image-scroller-in-actionscript-3-0/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 12:00:34 +0000</pubDate>
		<dc:creator>Evan Mullins</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=1412</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>This tutorial will demonstrate how to create a horizontally scrolling image viewer. It will cover xml parsing, loading and resizing external images, and creating intuitive and responsive scrolling!</p>
<p><span id="more-1412"></span></p>
<div class="tutorial_image">
<a href="http://Flashtuts.s3.amazonaws.com/073_CaurinaImageScroller/source.zip" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/source.jpg" alt="" style="border:none"></a><br />
<a href="http://Flashtuts.s3.amazonaws.com/073_CaurinaImageScroller/index.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Quick Introduction</h2>
<p>I&#8217;m a firm believer in learning by coding and tinkering. So in this tutorial, I&#8217;m stating what to do and then showing the equivalent code; please dig into the code, change things and tinker &#8211; I think that&#8217;s one of the best ways to learn! I expect that you have a basic understanding of ActionScript already and I won&#8217;t explain the fundamentals. I hope the descriptions will be helpful, but if I don&#8217;t explain something that you aren&#8217;t quite following, feel free to ask about it in the comments.</p>
<h2>Step 1: Set Up XML</h2>
<p>We&#8217;ll want nodes of images included in our xml. Each node will represent an image with attributes. We can add anything we like here, I&#8217;ll stick to three attributes to each image node. The &#8217;src&#8217; of the image (used to load it in), the title and the url we will link to from the scroller. I&#8217;ll go ahead and wrap them all within an images node (in case I want to include anything else in the xml later, such as customization options &#8211; hint).</p>
<p>Each image node will need a source image, a title and a url. The source (src) will be the image that gets loaded into the scroller, the title will be what we call it and the url will be the url that we load from the scroller when users click on the image (it can be a larger image or even a website). I&#8217;ve gotten some images from the <a href="http://Flashden.net/page/asset_library">envato asset library</a> and resized them to be used as the thumbnails as well. I shrank the thumbnails to fit into a 140px by 105px area, this is not required but will help to optimize the experience since we won&#8217;t be loading in huge images. You&#8217;ll see soon that any size image will work because we&#8217;ll code it to resize any image that loads to fit into the scroller area!</p>
<pre name="code" class="xml">&lt;images&gt;
&lt;image src=&quot;images/tn/scottwills_underwater4.jpg&quot; title=&quot;Jelly 4&quot; url=&quot;images/scottwills_underwater4.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/scottwills_cat.jpg&quot; title=&quot;Cat&quot; url=&quot;images/scottwills_cat.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/scottwills_modern_sculpture.jpg&quot; title=&quot;Statue&quot; url=&quot;images/scottwills_modern_sculpture.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/madness_arch3.jpg&quot; title=&quot;Arch 3&quot; url=&quot;images/madness_arch3.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/scottwills_penguin.jpg&quot; title=&quot;Penguin&quot; url=&quot;images/scottwills_penguin.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/scottwills_horse.jpg&quot; title=&quot;Jelly&quot; url=&quot;images/scottwills_horse.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/scottwills_modernsculpture2.jpg&quot; title=&quot;Statue 2&quot; url=&quot;images/scottwills_modernsculpture2.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/madness_arch1.jpg&quot; title=&quot;Arch 1&quot; url=&quot;images/madness_arch1.jpg&quot; /&gt;
&lt;image src=&quot;images/tn/madness_arch2.jpg&quot; title=&quot;Arch 2&quot; url=&quot;images/madness_arch2.jpg&quot; /&gt;
&lt;/images&gt;</pre>
<h2>Step 2: Set Up Flash</h2>
<p>OK, now that we have our xml file finished, let&#8217;s get started in Flash. Open Flash and create a new file (ActionScript 3.0). Adjust the stage size to something around 600 wide and 150 tall, set the background to any color you like (I chose a dark color to help the images stand out a bit more &#8211; #000033 if you wanna follow along) and step up the frame rate to 30 frames per second to give us smoother animation. Then let&#8217;s go ahead and create a new layer calling it &quot;ActionScript&quot;. On the first frame in the timeline click to the actions panel and we&#8217;re ready to continue!</p>
<h2>Step 3: Load XML</h2>
<p>We need to load the information from the xml file (created in step 1) into our Flash file. It&#8217;s a pretty simple step, but a foundation which can spring to many other creative applications. In just a few lines of code we initialize a URLLoader, an XML object to hold our data and a string to specify the path to the xml. Then we load the xml through the urlLoader object. That done, we need an Event listener to fire off when the file is fully loaded, we wouldn&#8217;t want to start messing with the xml data before it finishes loading. As specified in the docs, the complete event passes the loaded content as a the event target data property, so we access the actual xml as e.target.data and assign it to our xml object.</p>
<p>Let&#8217;s go ahead and double check that we&#8217;ve set that all up correctly and trace the image nodes of our xml to the output panel.</p>
<pre name="code" class="javascript">
//load xml
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
var xmlPath:String = "image-scroller.xml";
xmlLoader.load(new URLRequest(xmlPath));
trace("loading xml from: " + xmlPath);
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);

function LoadXML(e:Event):void {
	trace("xml loading complete");
	xmlData = new XML(e.target.data);
	trace(xmlData.image); //we'll see each image xml element listed in the output panel with this xmlList
}

/*
output window
///////////////
loading xml from: image-scroller.xml
xml loading complete
&lt;image src=&quot;images/tn/scottwills_underwater4.jpg&quot; title=&quot;Jelly 4&quot; url=&quot;images/scottwills_underwater4.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/scottwills_cat.jpg&quot; title=&quot;Cat&quot; url=&quot;images/scottwills_cat.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/scottwills_modern_sculpture.jpg&quot; title=&quot;Statue&quot; url=&quot;images/scottwills_modern_sculpture.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/madness_arch3.jpg&quot; title=&quot;Arch 3&quot; url=&quot;images/madness_arch3.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/scottwills_penguin.jpg&quot; title=&quot;Penguin&quot; url=&quot;images/scottwills_penguin.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/scottwills_horse.jpg&quot; title=&quot;Jelly&quot; url=&quot;images/scottwills_horse.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/scottwills_modernsculpture2.jpg&quot; title=&quot;Statue 2&quot; url=&quot;images/scottwills_modernsculpture2.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/madness_arch1.jpg&quot; title=&quot;Arch 1&quot; url=&quot;images/madness_arch1.jpg&quot;/&gt;
&lt;image src=&quot;images/tn/madness_arch2.jpg&quot; title=&quot;Arch 2&quot; url=&quot;images/madness_arch2.jpg&quot;/&gt;
*/
</pre>
<h2>Step 4: Parse XML</h2>
<p>Loading the xml is great, but we also have to read it and let our code know what to do with the data. So rather than just tracing out the xmlList we&#8217;ll send it to another function that will take care of creating our scroller. The buildScroller function will accept an XMLList, so we&#8217;ll loop through it, creating movie clip objects for each image in the scroller and assigning them properties according to the xml node attributes title, url and src. Later we&#8217;ll build out this function to include much more so it will actually do what it is named for and build the scroller!</p>
<p>For now let&#8217;s just trace this info to make sure everything is working according to plan. We can even wrap the content buildScroller function with trace statements so we always know where we are. </p>
<pre name="code" class="javascript">//load xml
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
var xmlPath:String = "image-scroller.xml";
xmlLoader.load(new URLRequest(xmlPath));
trace("loading xml from: " + xmlPath);
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);

function LoadXML(e:Event):void {
	trace("xml loading complete");
	xmlData = new XML(e.target.data);
	buildScroller(xmlData.image); //rather than trace the xmlList, we send it to our buildScroller function

}

//build scroller from xml
function buildScroller(imageList:XMLList):void{
	trace("build Scroller");

	for (var item:uint = 0; item &lt; imageList.length(); item++ )  {
		var thisOne:MovieClip = new MovieClip();

		thisOne.itemNum = item;
		thisOne.title = imageList[item].attribute("title");
		thisOne.link = imageList[item].attribute("url");
		thisOne.src = imageList[item].attribute("src");

		trace(thisOne.itemNum, thisOne.title, thisOne.link, thisOne.src);
	}

	trace("termination of build scroller");
}

/*
output
///////
loading xml from: image-scroller.xml
xml loading complete
build Scroller
0 Jelly 4 images/scottwills_underwater4.jpg images/tn/scottwills_underwater4.jpg
1 Cat images/scottwills_cat.jpg images/tn/scottwills_cat.jpg
2 Statue images/scottwills_modern_sculpture.jpg images/tn/scottwills_modern_sculpture.jpg
3 Arch 3 images/madness_arch3.jpg images/tn/madness_arch3.jpg
4 Penguin images/scottwills_penguin.jpg images/tn/scottwills_penguin.jpg
5 Jelly images/scottwills_horse.jpg images/tn/scottwills_horse.jpg
6 Statue 2 images/scottwills_modernsculpture2.jpg images/tn/scottwills_modernsculpture2.jpg
7 Arch 1 images/madness_arch1.jpg images/tn/madness_arch1.jpg
8 Arch 2 images/madness_arch2.jpg images/tn/madness_arch2.jpg
termination of build scroller

*/</pre>
<h2>Step 5: Build Scroller MovieClip to Contain Each Image</h2>
<p>Now that the build scroller function is created and that it creates objects for each node in the xml, let&#8217;s add them to the stage!</p>
<p>We&#8217;ll begin by creating a scroller MovieClip. This will be the container for all the objects we want to scroll, so each image node will have a movieclip within this scroller object. Let&#8217;s go ahead and add it to the stage, then set the y value to 30. We won&#8217;t yet see anything on the stage when we test, but we&#8217;re about to add items to the scroller for each image in the xmlList.</p>
<pre name="code"  class="javascript">
var scroller:MovieClip = new MovieClip();
this.addChild(scroller);
scroller.y = 30;
</pre>
<h2>Step 6: Adding Items to Scroller</h2>
<p>We already have the movie clips created with properties, but we need to create something we can see, so let&#8217;s create a box area to actually see these scroller items. Create a blackBox sprite and give it a shape with the graphics api. I&#8217;ve decided that I want my standard scroller item to be 140&#215;105px so I&#8217;ll create the blackBox to fit that area and I&#8217;ll give it a 1px border on all sides. Move it up and to the left one pixel and give it 142&#215;107 dimensions.</p>
<p>We add the blackbox sprite to the thisOne movieClip and also update the x value of the item. Since each will be 140 wide, I&#8217;ll add some padding (20) and lay them out horizontally. I&#8217;ll update the trace statement to output what is going on here.</p>
<pre name="code"  class="javascript">
var scroller:MovieClip = new MovieClip();
this.addChild(scroller);
scroller.y = 30;
//build scroller from xml
function buildScroller(imageList:XMLList):void{
	trace("build Scroller");
	for (var item:uint = 0; item &lt; imageList.length(); item++ )  {
		var thisOne:MovieClip = new MovieClip();

		//outline
		var blackBox:Sprite = new Sprite();
		blackBox.graphics.beginFill(0xFFFFFF);
		blackBox.graphics.drawRect( -1, -1, 142, 107);
		thisOne.addChild(blackBox);

		thisOne.x = (140 + 20) * item;
		thisOne.itemNum = item;
		thisOne.title = imageList[item].attribute("title");
		thisOne.link = imageList[item].attribute("url");
		thisOne.src = imageList[item].attribute("src");

		trace(thisOne.itemNum, thisOne.title, " added to scroller");

		//add item
		scroller.addChild(thisOne);
	}
	trace("termination of build scroller");
}
/*
output
///////
loading xml from: image-scroller.xml
xml loading complete
build Scroller
0 Jelly 4  added to scroller
1 Cat  added to scroller
2 Statue  added to scroller
3 Arch 3  added to scroller
4 Penguin  added to scroller
5 Jelly  added to scroller
6 Statue 2  added to scroller
7 Arch 1  added to scroller
8 Arch 2  added to scroller
termination of build scroller
*/
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step6.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 7: Adding Click Listener to Items</h2>
<p>Alright, this isn&#8217;t much yet because it just looks like a bunch of boxes that don&#8217;t do anything. Let&#8217;s add a listener to these boxes though, so that we can tell that they are each unique items in the scroller. Thinking of the final result, we&#8217;ll add a click listener because we want users to be able to click the item in the scroller and go to the link we put in the xml. Let&#8217;s make the clip buttonMode true, so that it&#8217;s perceived as something that is click-able. Then add an event Listener for the MouseEvent.CLICK. For now we&#8217;ll just have it listen for this click event and fire a function to trace the url we&#8217;re aiming at.</p>
<p>Through the output we can see that each box has properties sent to it from the xml.</p>
<pre name="code"  class="javascript">
//build scroller from xml
function buildScroller(imageList:XMLList):void{
	trace("build Scroller");
	for (var item:uint = 0; item &lt; imageList.length(); item++ )  {
		var thisOne:MovieClip = new MovieClip();

		//outline
		var blackBox:Sprite = new Sprite();
		blackBox.graphics.beginFill(0xFFFFFF);
		blackBox.graphics.drawRect( -1, -1, 142, 107);
		thisOne.addChild(blackBox);

		thisOne.x = (140 + 20) * item;
		thisOne.itemNum = item;
		thisOne.title = imageList[item].attribute("title");
		thisOne.link = imageList[item].attribute("url");
		thisOne.src = imageList[item].attribute("src");

		//create listeners for this item
		thisOne.buttonMode = true;
		thisOne.addEventListener(MouseEvent.CLICK, clickScrollerItem);

		//add item
		scroller.addChild(thisOne);
	}

	trace("termination of build scroller");
}

function clickScrollerItem(e:MouseEvent):void {
	trace("clicked item &quot; + e.currentTarget.itemNum + &quot; - visit url: " + e.currentTarget.link);
}

/*
output
//////
loading xml from: image-scroller.xml
xml loading complete
build Scroller
termination of build scroller
clicked item 2 - visit url: images/scottwills_modern_sculpture.jpg
clicked item 0 - visit url: images/scottwills_underwater4.jpg
clicked item 1 - visit url: images/scottwills_cat.jpg
clicked item 3 - visit url: images/madness_arch3.jpg
clicked item 1 - visit url: images/scottwills_cat.jpg
*/</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step7.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 8: Adding More Listeners to Scroller Items</h2>
<p>Let&#8217;s finish off the event listeners! We&#8217;ll want to listen to each of these items to know when a user clicks, mouses over and mouses out.</p>
<pre name="code"  class="javascript">
//build scroller from xml
function buildScroller(imageList:XMLList):void{
	trace("build Scroller");
	for (var item:uint = 0; item &lt; imageList.length(); item++ )  {
		var thisOne:MovieClip = new MovieClip();

		//outline
		var blackBox:Sprite = new Sprite();
		blackBox.graphics.beginFill(0xFFFFFF);
		blackBox.graphics.drawRect( -1, -1, 142, 107);
		thisOne.addChild(blackBox);

		thisOne.x = (140 + 20) * item;
		thisOne.itemNum = item;
		thisOne.title = imageList[item].attribute("title");
		thisOne.link = imageList[item].attribute("url");
		thisOne.src = imageList[item].attribute("src");

		//create listeners for this thumb
		thisOne.buttonMode = true;
		thisOne.addEventListener(MouseEvent.CLICK, clickScrollerItem);
		thisOne.addEventListener(MouseEvent.MOUSE_OVER, overScrollerItem);
		thisOne.addEventListener(MouseEvent.MOUSE_OUT, outScrollerItem);

		//add item
		scroller.addChild(thisOne);
	}

	trace("termination of build scroller");
}

function clickScrollerItem(e:MouseEvent):void {
	trace(&quot;clicked item &quot; + e.currentTarget.itemNum + &quot; - visit url: &quot; + e.currentTarget.link);
}
function overScrollerItem(e:MouseEvent):void {
	trace("over " + e.currentTarget.title);
}
function outScrollerItem(e:MouseEvent):void {
	trace(&quot;out &quot; + e.currentTarget.title);
}
/* output
//////////////
loading xml from: image-scroller.xml
xml loading complete
build Scroller
termination of build scroller
over Jelly 4
out Jelly 4
over Cat
out Cat
over Statue
out Statue
over Arch 3
out Arch 3
over Arch 3
clicked item 3 - visit url: images/madness_arch3.jpg
out Arch 3
over Statue
clicked item 2 - visit url: images/scottwills_modern_sculpture.jpg
out Statue
*/
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step8.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 9: Loading and Adding the Images</h2>
<p>Now the part I&#8217;m sure you&#8217;ve been getting anxious about, let&#8217;s get the images loaded into the scroller items so we can see what they are! We&#8217;ll do this in the buildScroller function. Right after the blackbox is created and the properties are assigned for the current item let&#8217;s also create another sprite to contain the actual image.</p>
<p>We&#8217;ll use a loader object and a URLRequest object to handle the loading of the image, which is newly standardized with ActionScript 3. We&#8217;ll pass the src of the image to the urlrequest object, then load the urlrequest with our loader object and finally we&#8217;ll add the loader to the thisThumb sprite adding that in turn to the thisOne movieClip. Whew.</p>
<p>It&#8217;s pretty self explanatory &#8211; and in just a couple of lines of code we&#8217;ve loaded the src images from our xml into Flash!</p>
<pre name="code" class="javascript">
function buildScroller(imageList:XMLList):void{
	trace("build Scroller");
	for (var item:uint = 0; item &lt; imageList.length(); item++ )  {
		var thisOne:MovieClip = new MovieClip();

		//outline
		var blackBox:Sprite = new Sprite();
		blackBox.graphics.beginFill(0xFFFFFF);
		blackBox.graphics.drawRect( -1, -1, 142, 107);
		thisOne.addChild(blackBox);

		thisOne.x = (140 + 20) * item;
		thisOne.itemNum = item;
		thisOne.title = imageList[item].attribute("title");
		thisOne.link = imageList[item].attribute("url");
		thisOne.src = imageList[item].attribute("src");

		//image container
		var thisThumb:Sprite = new Sprite();
		//add image
		var ldr:Loader = new Loader();
		var urlReq:URLRequest = new URLRequest(thisOne.src);
		trace("loading thumbnail "+item+" into Scroller: " + thisOne.src);
		ldr.load(urlReq);
		thisThumb.addChild(ldr);
		thisOne.addChild(thisThumb);

		//create listeners for this thumb
		thisOne.buttonMode = true;
		thisOne.addEventListener(MouseEvent.MOUSE_OVER, overScrollerItem);
		thisOne.addEventListener(MouseEvent.MOUSE_OUT, outScrollerItem);
		thisOne.addEventListener(MouseEvent.CLICK, clickScrollerItem);

		//add item
		scroller.addChild(thisOne);
	}

	trace("termination of build scroller");
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step9.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 10: Adding Event Listeners to the Image Loading Process</h2>
<p>When we load the images, we need to create some event listeners to tell us when the loading is complete. Best practice deal with any errors (in case there is a typo in the path to the image or we don&#8217;t have access or something). So just before we load the images let&#8217;s add an event listener for the loader&#8217;s contentLoaderInfo object for a complete event and also an i/o error. Then we&#8217;ll need to create the event handler functions.</p>
<p>For the completeHandler let&#8217;s just trace the image title for now, we&#8217;ll have to walk up the hierarchy of the event target&#8217;s parent&#8217;s parent&#8217;s title to find it, because of the way we nested our sprite within our scroller item objects (the thisOne Sprite).</p>
<pre name="code"  class="javascript">
trace("loading thumbnail "+item+" into Scroller: " + url);
//assign event listeners for Loader
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
ldr.load(urlReq);
...
function completeHandler(e:Event):void {
	trace("thumbnail complete "+e.target.loader.parent.parent.title);
}
function errorHandler(e:IOErrorEvent):void {
	trace("thumbnail error="+e);
}
</pre>
<h2>Step 11: Tweening the Images</h2>
<p>I&#8217;m using <a href="http://code.google.com/p/tweener/">Tweener</a> for this tutorial, but there are various tweening engines. If you&#8217;re not familiar with it<br />
<blockquote>Tweener (caurina.transitions.Tweener) is a Class used to create  tweens and other transitions via ActionScript code for projects  built on the Flash platform&#8230; In layman&#8217;s terms, Tweener helps you move things around on the screen using only code, instead of the timeline.</p></blockquote>
<p> So first go download it from the google code repository (be sure to get the as3 version) unzip it and put the caurina folder into the same directory as your .fla file, then import the code into your project by placing this in the first line of code: </p>
<pre name="code" class="javascript">import caurina.transitions.*;</pre>
<p>Then let&#8217;s have the images fade in once they&#8217;re loaded, instead of just popping like they are. First we&#8217;ll set the initial alpha value of the scroller item to 0, so it can fade in properly. Then jump back to our complete event listener handler function and add the Tweener code.</p>
<pre name="code"  class="javascript">
thisOne.alpha = 0;
...
function completeHandler(e:Event):void {
	//trace("thumbnail complete "+e.target.loader.parent.parent.title);
	Tweener.addTween(e.target.loader.parent.parent, { alpha:1, time: .5 } );
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step11.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 12: Resizing the Images</h2>
<p>Now, since I resized all my images and created thumbnails beforehand, this step is not <em>as</em> important, but is still great to include so that in case the dimensions change or I add another image later, the scroller will be able to handle it and resize it. The resize function will scale an image to fit within an area as I have explained before on my  <a href="http://blog.circlecube.com/2009/01/tutorial/how-to-as3-resize-a-movieclip-and-constrain-proportions-ActionScript-tutorial/">blog</a>. Basically though, in the completeHandler we&#8217;ll resize the image to fit an area, even if the image is correctly sized, the resizeMe function will still center the image for us.</p>
<pre name="code"  class="javascript">
function completeHandler(e:Event):void {
	//trace("thumbnail complete "+e.target.loader.parent.parent.name);
	//size image into scroller
	resizeMe(e.target.loader.parent, 140, 105, true, true, false);
	Tweener.addTween(e.target.loader.parent.parent, { alpha:1, time: .5 } );
}

//The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once, or resizeMe(image, 200);)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
// optional: centerHor = centers the displayObject in the maxW area. default true.
// optional: centerVert = centers the displayObject in the maxH area. default true.
function resizeMe(mc:DisplayObject, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true, centerHor:Boolean=true, centerVert:Boolean=true):void{
    maxH = maxH == 0 ? maxW : maxH;
    mc.width = maxW;
    mc.height = maxH;
    if (constrainProportions) {
        mc.scaleX &lt; mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
    }
	if (centerHor) {
		mc.x = (maxW - mc.width) / 2;
	}
	if (centerVert){
		mc.y = (maxH - mc.height) / 2;
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step12.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 13: Adding Movement</h2>
<p>We&#8217;ll start by just adding the basics. We want users to be able to intuitively control this scroller, so we&#8217;ll use their mouse position as direction only initially. If the mouse is positioned in the left half of the stage we want to move the scroller to the right, so the user moves in the direction they want the scroller to reveal itself. I prefer this to the direct relationship of moving the scroller the same way the mouse goes, but that&#8217;s a discussion for another day.</p>
<p>To implement this is pretty simple, we just add an event listener at the end of the buildScroller function, for every time we enter the frame to position the scroller. Then in the handler function we&#8217;ll create an if/else statement and set the new speed variable depending on mouse position. If the mouse x position is on the left half of the stage, we want the scroller to move one way and if it is on the right half of the stage we want it to move the other direction. Then we apply this speed to the x position of the scroller container. This is now starting to look like something useful because it is now interactive and responsive! </p>
<p>Essentially all we are doing is moving the scroller container clip to one direction of the other, but we&#8217;re doing it every frame, so it animates the position over time. Remember this scroller clip contains all the items we created, so it&#8217;s like putting things into a box and moving the box. The items don&#8217;t have to be moved, just the container! We move it either 5 pixels to the left or 5 pixels to the left every single frame (this 5 could be anything, I just chose 5 &#8217;cause it looked right). This leaves a lot to be desired, but it&#8217;s the first step. We have our scroller moving and have given the end user the power to control this movement!</p>
<p>Notice that we&#8217;re using the stage properties to find the stage size even though we set the stage size earlier and know exactly what size it is. This is because it will help the code to be self containing and portable. If we were to use the actual values we would have to remember to update them if we ever changed the scroller size or wanted to use this in a different application. We&#8217;ll create more variables soon that will allow us to fully customize the scroll interaction.</p>
<pre name="code"  class="javascript">
scroller.addEventListener(Event.ENTER_FRAME, moveScrollerThumbs);
trace(&quot;termination of build scroller&quot;);
...
var speed:Number;
function moveScrollerThumbs(e:Event):void {
	if (mouseX &lt; stage.stageWidth/2) { //left half of stage
		speed = 5;
	}
	else { //right half of stage
		speed = -5;
	}
	scroller.x += speed;
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step13.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 14: Better Movement &#8211; Mouse Limits</h2>
<p>You can see above that we still have a way to go with our movement controls of the scroller. There are boundaries to add to the mouse positions that cause the scrolling (we&#8217;d like it to only scroll when you are on the stage and over the scroller), limits we&#8217;d like to apply to the scroller (so that it doesn&#8217;t scroll off the page) and we want to make the scroller speed dynamic.</p>
<p>Let&#8217;s start first by adding a statement to check if we are over the scroller. To do this we&#8217;ll check the mouseY position, the scroller.y and scroller.height properties. Let&#8217;s also add a bit more to the mouseX statements, let&#8217;s ensure that it&#8217;s a bit more precise and only include the x values from 0 to the center of the stage (stage.stageWidth/2) and from the center to the edge. </p>
<pre name="code"  class="javascript">
function moveScrollerThumbs(e:Event):void {
	if ( mouseY &gt; scroller.y &#038;&#038; mouseY &lt; scroller.y + scroller.height) { //vertically over scroller
		if (mouseX &lt; stage.stageWidth/2 &#038;&#038; mouseX &gt; 0) { //left half of stage explicitly
			speed = 5;
		}
		else if (mouseX &gt; stage.stageWidth/2 &#038;&#038; mouseX &lt; stage.stageWidth) { //right half of stage explicitly
			speed = -5;
		}
		scroller.x += speed;
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step14.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 15: Better Movement &#8211; Scroller Limits</h2>
<p>Now we&#8217;ll want to apply boundaries  to the scroller itself so that it doesn&#8217;t scroll off the page and leave us with a blank stage and a user who doesn&#8217;t know or remember which way the images went.</p>
<p>We need to watch the scroller x position and if it goes too far either way reset it to our limit. Remember that the scroller x position is found at its left edge, so when it is at a 0 x position it is flush with the left edge of the stage. So first off if the x position of the scroller is greater than 0 after the speed is calculated and applied, we want to set it back to our limit, 0. This will keep the scroller from moving too far into the stage. We can even add some padding to the stage and since we have the padding between each scroller item of 20, let&#8217;s make it consistent. Rather than using 0 here, let&#8217;s make it the same 20 value. </p>
<p>We want the scroller to stop moving left once it&#8217;s last item is fully on stage. This left limit can be found by finding the width of the scroller and the stage width. If the scroller is moved so far to the left that it&#8217;s x position is less than it&#8217;s own width (negative) but factor back in the stage width (plus stageWidth) we need to hold it right there. To add the padding on this end we subtract 20.</p>
<pre name="code"  class="javascript">
function moveScrollerThumbs(e:Event):void {
	if ( mouseY &gt; scroller.y &#038;&#038; mouseY &lt; scroller.y + scroller.height) {//vertically over scroller
		if (mouseX &lt; stage.stageWidth/2 &#038;&#038; mouseX &gt; 0) {//left of stage explicitly
			speed = 5;
		}
		else if (mouseX &gt; stage.stageWidth/2 &#038;&#038; mouseX &lt; stage.stageWidth) {//right of stage explicitly
			speed = -5;
		}
		scroller.x += speed;

		//scroller limits
		if (scroller.x &lt; -scroller.width + stage.stageWidth - 20) { //if scroller too far left
			scroller.x = -scroller.width + stage.stageWidth - 20;
		}
		else if (scroller.x &gt; 20) { //if scroller to far right
			scroller.x = 20;
		}
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step15.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 16: Dynamic Movement</h2>
<p>To make the movement more fluid and dynamic we only need to update two lines of code. You guessed it, the two lines that set the speed need to be adjusted to determine the speed by the distance mouseX is from the center of the stage rather than a flat value of 5. We find the distance the mouse is horizontally from the center axis of the stage (stage.stageWidth/2), and we want the scroller to move to the right if we&#8217;re on the left side and vice versa. In both instances we find the negative difference between the two. Then we should scale it down by dividing it by, let&#8217;s try 8, because if we don&#8217;t, the scroller is way too fast (go ahead, try it).</p>
<pre name="code"  class="javascript">
function moveScrollerThumbs(e:Event):void {
	if ( mouseY &gt; scroller.y &#038;&#038; mouseY &lt; scroller.y + scroller.height) {//vertically over scroller
		if (mouseX &lt; stage.stageWidth/2 &#038;&#038; mouseX &gt; 0) {//left of stage explicitly
			speed = -(mouseX - stage.stageWidth/2) / 8;
		}
		else if (mouseX &gt; stage.stageWidth/2 &#038;&#038; mouseX &lt; stage.stageWidth) {//right of stage explicitly
			speed = -(mouseX - stage.stageWidth/2) / 8;
		}
		scroller.x += speed;

		//scroller limits
		if (scroller.x &lt; -scroller.width + stage.stageWidth - 20) { //if scrolled too far left
			scroller.x = -scroller.width + stage.stageWidth - 20;
		}
		else if (scroller.x &gt; 20) { //if scrolled to far right
			scroller.x = 20;
		}
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step16.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 17: User Friendly Movement</h2>
<p>Now test this and think about your end user. You&#8217;ll be looking at this image scroller and maybe wanting to look a bit closer or focus in on an image that catches your eye. You want this scroller to stop moving, (if I move to the center of the stage it still drifts to one side of the other) and I focus more on fighting the scroller than I do on the image I want to look at.</p>
<p>This is an example of a non-transparent user control. We want the user to be able to intuitively use this scroller to the point that they don&#8217;t even think about it. If the user has to think about it, or even worse, fight your app to get it to do something, you lose and they will look elsewhere for their content. So let&#8217;s avoid the struggle and give the scroller a dead area at the center of the stage. Then they can rest at ease by moving to the center of the scroller to inspect something or stop the motion sickness. It&#8217;s a really easy thing to do and has a big payoff, making the scroller easier to use. Rather than using the center of the stage for all our calculations we&#8217;ll give it some padding.</p>
<pre name="code"  class="javascript">
function moveScrollerThumbs(e:Event):void {
	if ( mouseY &gt; scroller.y &#038;&#038; mouseY &lt; scroller.y + scroller.height) {//vertically over scroller
		if (mouseX &lt; stage.stageWidth/2 - 40 &#038;&#038; mouseX &gt; 0) {//left of stage explicitly
			speed = -(mouseX - (stage.stageWidth/2 - 40)) / 8;
		}
		else if (mouseX &gt; stage.stageWidth/2 + 40 &#038;&#038; mouseX &lt; stage.stageWidth) {//right of stage explicitly
			speed = -(mouseX - (stage.stageWidth/2 + 40)) / 8;
		}
		else {
			speed = 0; //if in the center area, clear the speed to 0 so we don't have any roll over effect from the last frame.
		}
		scroller.x += speed;

		//scroller limits
		if (scroller.x &lt; -scroller.width + stage.stageWidth - 20) { //if scrolled too far left
			scroller.x = -scroller.width + stage.stageWidth - 20;
		}
		else if (scroller.x &gt; 20) { //if scrolled to far right
			scroller.x = 20;
		}
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step17.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 18: Abstracting Movement More</h2>
<p>Let&#8217;s abstract this out a bit. We have multiple places where we are adding padding to values or measurements. It&#8217;d be best practice to create a variable to hold our padding value and apply the same value easily by applying the variable every time we want padding. This would help us update if a client later says &quot;I like it, but can we spread it out some?&quot; or the dreaded&#8230; &quot;Something&#8217;s off about this&#8230;&quot;, then we&#8217;d just update the variable and it would be ready to go. I always try to create controls for myself, the programmer, to make it easy to customize a project.</p>
<p>I&#8217;ve created a variable named &quot;padding&quot; here and am applying it everywhere that makes sense. Notice that in a couple places I multiply it by 2, use your own judgment here &#8211; if you want more padding give it more, of course we could take it further and have a &quot;padding_small&quot; variable and another &quot;padding_large&quot; variable, but one will do justice for the purpose of this tutorial. You get the idea. This doesn&#8217;t really change the end file, but it can help to make your life much easier and your code simpler, more understandable or readable.</p>
<pre name="code"  class="javascript">
import caurina.transitions.*;

//load xml
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);

var xmlPath:String = "image-scroller.xml";
xmlLoader.load(new URLRequest(xmlPath));
trace("loading xml from: " + xmlPath);

function LoadXML(e:Event):void {
	trace("xml loading complete");
	xmlData = new XML(e.target.data);
	//trace(xmlData.image);
	buildScroller(xmlData.image);
}

var scroller:MovieClip = new MovieClip();
var speed:Number;
var padding:Number = 20;

this.addChild(scroller);
scroller.y = scroller.x = padding;
//build scroller from xml
function buildScroller(imageList:XMLList):void{
	trace("build Scroller");
	for (var item:uint = 0; item &lt; imageList.length(); item++ )  {
		var thisOne:MovieClip = new MovieClip();

		//outline
		var blackBox:Sprite = new Sprite();
		blackBox.graphics.beginFill(0xFFFFFF);
		blackBox.graphics.drawRect( -1, -1, 142, 107);
		thisOne.addChild(blackBox);

		thisOne.x = (140 + padding) * item;
		thisOne.itemNum = item;
		thisOne.title = imageList[item].attribute("title");
		thisOne.link = imageList[item].attribute("url");
		thisOne.src = imageList[item].attribute("src");

		//image container
		var thisThumb:Sprite = new Sprite();
		//add image
		var ldr:Loader = new Loader();
		var urlReq:URLRequest = new URLRequest(thisOne.src);
		trace("loading thumbnail "+item+" into Scroller: " + thisOne.src);
		ldr.load(urlReq);
		//assign event listeners for Loader
		ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
		ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
		thisThumb.addChild(ldr);
		thisOne.addChild(thisThumb);

		//create listeners for this thumb
		thisOne.buttonMode = true;
		thisOne.addEventListener(MouseEvent.MOUSE_OVER, overScrollerItem);
		thisOne.addEventListener(MouseEvent.MOUSE_OUT, outScrollerItem);
		thisOne.addEventListener(MouseEvent.CLICK, clickScrollerItem);

		//add item
		scroller.addChild(thisOne);
	}

	scroller.addEventListener(Event.ENTER_FRAME, moveScrollerThumbs);
	trace("termination of build scroller");
}

function overScrollerItem(e:MouseEvent):void {
	trace("over" + e.currentTarget.name);
}
function outScrollerItem(e:MouseEvent):void {
	trace("out" + e.currentTarget.name);
}
function clickScrollerItem(e:MouseEvent):void {
	trace("clicked item " + e.currentTarget.itemNum + " - visit url: " + e.currentTarget.link);
}
function completeHandler(e:Event):void {
	//trace("thumbnail complete "+e.target.loader.parent.parent.name);
	//size image into scroller
	resizeMe(e.target.loader.parent, 140, 105, true, true, false);
	Tweener.addTween(e.target.loader.parent.parent, { alpha:1, time: .5 } );
}
function errorHandler(e:IOErrorEvent):void {
	trace("thumbnail error="+e);
}

//The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
function resizeMe(mc:DisplayObject, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true, centerHor:Boolean=true, centerVert:Boolean=true):void{
    maxH = maxH == 0 ? maxW : maxH;
    mc.width = maxW;
    mc.height = maxH;
    if (constrainProportions) {
        mc.scaleX &lt; mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
    }
	if (centerHor) {
		mc.x = (maxW - mc.width) / 2;
	}
	if (centerVert){
		mc.y = (maxH - mc.height) / 2;
	}
}

function moveScrollerThumbs(e:Event):void {
	if ( mouseY &gt; scroller.y &#038;&#038; mouseY &lt; scroller.y + scroller.height) {//vertically over scroller
		if (mouseX &lt; stage.stageWidth/2 - padding*2 &#038;&#038; mouseX &gt; 0) {//left of stage explicitly
			speed = -(mouseX - (stage.stageWidth/2 - padding*2)) / 8;
		}
		else if (mouseX &gt; stage.stageWidth/2 + padding*2 &#038;&#038; mouseX &lt; stage.stageWidth) {//right of stage explicitly
			speed = -(mouseX - (stage.stageWidth/2 + padding*2)) / 8;
		}
		else {
			speed = 0;
		}
		scroller.x += speed;

		//scroller limits
		if (scroller.x &lt; -scroller.width + stage.stageWidth - padding) { //if scrolled too far left
			scroller.x = -scroller.width + stage.stageWidth - padding;
		}
		else if (scroller.x &gt; padding) { //if scrolled to far right
			scroller.x = padding;
		}
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step18.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 19: Adding Scale Tweens</h2>
<p>With this idea of using variables to customize our file, let&#8217;s add some bling with the Tweener library we already added. It&#8217;s great to call out the item in the scroller the user rolls over, so let&#8217;s have it scale a bit larger to help it stand out. This is where the beauty of Tweening comes in. Just one line of code, some variables and we can tell it to tween the scaleX and scaleY of the scroll item. If we&#8217;re scaling the item we&#8217;ll want to also translate its coordinates a bit so the item is still centered, this looks like tricky math, but it&#8217;s actually pretty simple.</p>
<p>First, we add a variable to each object to store it&#8217;s starting x position, we can just call it myx and put it on the same line where we calculate the x (we do this so we can reliably move the item back to it&#8217;s rightful place when we need to). We need to move it so the item is still centered, so we find its current width and factor it by half the scale we are applying. We do this for x and y. Then we need to tween it back to its starting size and coordinates on the mouse out event handler.</p>
<pre name="code"  class="javascript">
thisOne.x = thisOne.myx = (140 + padding) * item;
...
var thumbSmall:Number = 1;
var thumbLarge:Number = 1.1;
function overScrollerItem(e:MouseEvent):void {
	//trace("over" + e.currentTarget.name);
	Tweener.addTween(e.currentTarget, { scaleX:thumbLarge, scaleY:thumbLarge, x:e.currentTarget.myx - e.currentTarget.width * Math.abs(thumbSmall - thumbLarge)/2, y: -e.currentTarget.width * Math.abs(thumbSmall - thumbLarge)/2, time:1 } );
}
function outScrollerItem(e:MouseEvent):void {
	//trace("out" + e.currentTarget.name);
	Tweener.addTween(e.currentTarget, { scaleX:thumbSmall, scaleY:thumbSmall, x:e.currentTarget.myx, y:0, time:1 } );
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step19.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 20: Adding Border Tweens</h2>
<p>Let&#8217;s make them stand out even more by fading the white &#8216;blackBox&#8217; around the thumbnails (just realizing that I named the white box black =) ). This one is easier than the previous step. Just add a couple of variables for the fade in and out values (alpha) and add the Tweens to both the over and out event listener handler function. We&#8217;ll also need to ensure that we can address the blackBox sprite so when we initialize it let&#8217;s explicitly name it. While we&#8217;re at it we can set the initial alpha of the box to equal the thumbFadeOut variable.</p>
<pre name="code"  class="javascript">
//outline
var thumbFadeOut:Number = .2;
var thumbFadeIn:Number = 1;
var thumbSmall:Number = 1;
var thumbLarge:Number = 1.1;
...
var blackBox:Sprite = new Sprite();
blackBox.graphics.beginFill(0xFFFFFF);
blackBox.graphics.drawRect( -1, -1, 142, 107);
blackBox.alpha = thumbFadeOut;
thisOne.addChild(blackBox);
thisOne.blackBox = blackBox;
...
function overScrollerItem(e:MouseEvent):void {
	//trace("over" + e.currentTarget.name);
	Tweener.addTween(e.currentTarget, { scaleX:thumbLarge, scaleY:thumbLarge, x:e.currentTarget.myx - e.currentTarget.width * Math.abs(thumbSmall - thumbLarge)/2, y: -e.currentTarget.width * Math.abs(thumbSmall - thumbLarge)/2, time:1 } );
	Tweener.addTween(e.currentTarget.blackBox, { alpha:thumbFadeIn, time: 1 } );
}
function outScrollerItem(e:MouseEvent):void {
	//trace("out" + e.currentTarget.name);
	Tweener.addTween(e.currentTarget, { scaleX:thumbSmall, scaleY:thumbSmall, x:e.currentTarget.myx, y:0, time:1 } );
	Tweener.addTween(e.currentTarget.blackBox, { alpha:thumbFadeOut, time: 1 } );
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/image-scroller-step20.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/milestone.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 21: Adding Link on Click</h2>
<p>Speaking of all the event listeners, we still haven&#8217;t finished coding the click event. We want to have the click basically be a link click and link the user to the url specified in the xml. For this, we just pass the link value from the event&#8217;s target that we are currently tracing, to a URLRequest object and try to navigate to it with our friend navigateToURL. There we have it.</p>
<pre name="code"  class="javascript">
function clickScrollerItem(e:MouseEvent):void {
	//trace("clicked item " + e.currentTarget.itemNum + " - visit url: " + e.currentTarget.link);
	var urlRequest:URLRequest = new URLRequest(e.currentTarget.link);
	try {
		navigateToURL(urlRequest);
	}
	catch (e:Error) {
		// handle error here
		trace(e);
	}
}
</pre>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/073_CaurinaImageScroller/index.html" target="_blank"><br />
<img src="http://Flashtuts.s3.amazonaws.com/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Conclusion</h2>
<p>I hope you enjoyed this tutorial and that you learned something. You should now have a pretty good grasp on AS3 and xml, loading and resizing images, easy animating with tweening, mouse event listeners, scrolling and user friendly interactive design!</p>
<p>Was it easy to follow? I usually do tutorials in open source examples so I don&#8217;t know if I droned on too much here.. Feel free to let me know in the comments. This tutorial is meant to be a spring board for ideas; there are tons of other things we could to with this file and get many other effects going, but this should get you started!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/create-a-responsive-xml-image-scroller-in-actionscript-3-0/feed/</wfw:commentRss>
		<slash:comments>50</slash:comments>
		</item>
		<item>
		<title>Plotting Points Using Yahoo! Maps and RSS</title>
		<link>http://active.tutsplus.com/tutorials/xml/plotting-points-using-yahoomaps-and-rss/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/plotting-points-using-yahoomaps-and-rss/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 12:00:09 +0000</pubDate>
		<dc:creator>Jeremy Green</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=1358</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/main-page-preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, I&#8217;ll show you how to get started with the Yahoo! Maps API in Flash. We&#8217;ll load a couple of RSS feeds and plot some natural disaster warnings using their longitudes and latitudes.</p>
<p><span id="more-1358"></span></p>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/yahoo_map_source_files.zip" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/source.jpg" alt="" style="border:none"></a><br />
<a href="http://mutatedcreativity.com/dev/yahoo" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: Get an App ID</h2>
<p>Go to <a href="http://developer.yahoo.com/flash/maps/" target="_blank">http://developer.yahoo.com/flash/maps/</a> and sign up for an App ID.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/1.jpg" alt="" /></div>
<h2>Step 2: Download the Component</h2>
<p>On the Yahoo Map AS3 Component page, download the newest version of the component.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/2.jpg" alt="" /></div>
<h2>Step 3: Install the Component</h2>
<p>When the file is done downloading, extract the zip file.  Navigate to the Flash folder and install the MXP file.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/3.jpg" alt="" /></div>
<h2>Step 4: Move to Flash</h2>
<p>Start Flash and open a new ActionScript 3.0 file, then save it in a new folder as &quot;yahoo_map.fla&quot;.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/4.jpg" alt="" /></div>
<h2>Step 5: Set Up the Document</h2>
<p>Change the stage size to 640&#215;480. Navigate to the components tab and drag a copy of the YahooMaps component to the stage. Once it&#8217;s on the stage, delete it.  That will put a copy in the library so we can access it from there.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/5.jpg" alt="" /></div>
<h2>Step 6: The Text Area</h2>
<p>Drag a copy of the TextArea from the components tab. In the properties panel, change the size of the TextArea to a width of 640px and a height of 100px.  Give it an X position of 0 and a Y position of 330. Finally, give it an instance name of &quot;textArea&quot;.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/6.jpg" alt="" /></div>
<h2>Step 7: The Radio Buttons</h2>
<p>Next, drag a copy of the the RadioButton from the components tab. Copy and paste it three times, so that there are four instances of the RadioButton component on the stage. Align them to the top and evenly space them out, so that they&#8217;re in a straight line right next to one another. Next, drag them below the TextArea component.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/7.jpg" alt="" /></div>
<h2>Step 8: The Radio Button Parameters</h2>
<p>Select the first radio button. Give it an instance name of &quot;radioAll&quot;. With the button still selected, switch over to the parameters panel. Give it a group name of &quot;Disasters&quot;. Change the label property to &quot;All&quot; and the selected property to &quot;true&quot;.</p>
<p>Select the next radio button. Give it an instance name of &quot;radioEarth&quot;, the same group name of &quot;Disasters&quot;, a label of &quot;Earthquakes&quot; and leave the selected property as &quot;false&quot;.</p>
<p>Select the third radio button. Its instance name is &quot;radioTsu&quot;, the group name is &quot;Disasters&quot;, the label is &quot;Tsunamis&quot;, and the selected property is &quot;false&quot;.</p>
<p>Finally, select the fourth radio button. It has an instance name of &quot;radioVolcano&quot;, its group name is &quot;Disasters&quot;, it has a label of &quot;Volcanoes&quot;, and selected is &quot;false&quot;. Since we want to be able to toggle between the buttons, we gave them the same group name. Space them accordingly, so that they&#8217;re evenly spaced.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/8.jpg" alt="" /></div>
<h2>Step 9: The Empty MovieClip</h2>
<p>Create a separate layer.  Place the layer below the layer with TextArea and RadioButton components. In the library panel, at the bottom, select the new symbol icon. Create a new empty movieclip. Drag an instance onto the stage in the newly created layer, then give it an instance name of &quot;empty&quot;. This movie clip will hold our map when it&#8217;s loaded. Give the empty movie clip an X and Y position of 0. That way it&#8217;s lined up with the top left corner of the stage.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/9.jpg" alt="" /></div>
<h2>Step 10: Setting Up the Document Class</h2>
<p>Go to file &gt; new and select a new ActionScript File. Save the file in the same directory as your &quot;yahoo_map&quot; FLA file with the name &quot;yahoo_map.as&quot;. In your yahoo_map FLA document, in the properties panel, type &quot;yahoo_map&quot; in the Document class field. This will make your actionscript file the Document class for your yahoo_map FLA.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/10.jpg" alt="" /></div>
<h2>Step 11: The Document Class Skeleton</h2>
<p>This is the basic setup for our document class:</p>
<pre name="code" class="javascript">
package {

	import flash.display.Sprite;

	public class yahoo_map extends Sprite
	{

		public function yahoo_map()
		{

		}
	}
}
</pre>
<h2>Step 12: The Yahoo Maps Import Statements</h2>
<p>These are the statements that will drive the YahooMap API</p>
<pre name="code" class="javascript">
package {

	import com.yahoo.maps.api.YahooMap;
	import com.yahoo.maps.api.YahooMapEvent;
	import com.yahoo.maps.api.core.location.LatLon;
	import com.yahoo.maps.api.markers.Marker;

	import flash.display.Sprite;

	public class yahoo_map extends Sprite
	{

		public function yahoo_map()
		{

		}
	}
}
</pre>
<h2>Step 13: The Rest of the Import Statements</h2>
<p>Simply add these below the YahooMaps import statement.  Make sure that they are above the class declaration.</p>
<pre name="code" class="javascript">
package {

	import com.yahoo.maps.api.YahooMap;
	import com.yahoo.maps.api.YahooMapEvent;
	import com.yahoo.maps.api.core.location.LatLon;
	import com.yahoo.maps.api.markers.Marker;

    import fl.controls.RadioButtonGroup;
	import fl.controls.RadioButton;

    import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.DropShadowFilter;
	import flash.geom.ColorTransform;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.text.AntiAliasType;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	public class yahoo_map extends Sprite
	{

		public function yahoo_map()
		{

		}
	}
}
</pre>
<h2>Step 14: Declaring the Variables</h2>
<p>Here we&#8217;re going to delcare the global variables. We&#8217;ll need the app id that you got from the YahooMaps page and we&#8217;re going to need to use some php later to make the feeds load into Flash. That is why we have the CURL constant. Make sure that these are placed below the class declaration but above the main public function.</p>
<pre name="code" class="javascript">
public class yahoo_map extends Sprite
	{
		private static const APPID:String = "YOUR APP ID";
        private static const CURL:String = "curl.php";
		private var map:YahooMap;
		private var ds:DropShadowFilter;
		private var geo:Namespace;
		private var tsuArray:Array;
		private var tsuCounter:int = 0;
		private var color:ColorTransform;
		private var group:RadioButtonGroup;

		public function yahoo_map()
</pre>
<h2>Step 15: Setting up our Init Function</h2>
<p>Here we&#8217;ll instantiate all of our variables. After searching Google, I found four RSS feeds for tsunami warnings from weather.gov. I loaded those into the tsuArray variable, so that I can load them one at a time. The geo namespace is going to help with getting to the latitude and longitude of all the RSS feeds. Also, there is a new RadioButtonGroup that will handle the toggling of the RadioButton components on the stage. Finally, I call the handleMap function. That will start the map loading process.</p>
<pre name="code" class="javascript">
public function yahoo_map()
		{
			init();
		}

        private function init():void
		{
			tsuArray = new Array("http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_pacific.xml", "http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_hawaii.xml", "http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_indian.xml", "http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_caribe.xml");
			geo = new Namespace("http://www.georss.org/georss");
			ds = new DropShadowFilter(2,90,0x00000,0.75,2,2,1,3);
            color = new ColorTransform();
			group = new RadioButtonGroup("Disasters");
			handleMap();
		}
 </pre>
<h2>Step 16: Setting up our Map</h2>
<p>This is where we start working with the map basics and where we&#8217;ll use our app id. Also, when we call the map.init() method, we dictate the size we want the map to be. The map will be the width of the stage and have a height that touches the top of the TextArea component. We also listen for the MAP_INITALIZE event.</p>
<pre name="code" class="javascript">
private function handleMap():void
		{
			map = new YahooMap();
			map.addEventListener(YahooMapEvent.MAP_INITIALIZE, onInit);
			map.init(APPID, stage.stageWidth, 330);
		}
 </pre>
<h2>Step 17: The Map is Ready</h2>
<p>When the map is initialized, it will fire the onInit function.  Here is where we&#8217;ll add the map to the empty movie clip that was placed on the stage. That way the map will load underneath the TextArea and RadioButton components &#8212; just in case. We then add the zoom, pan, and type widgets. These control the type of map, add the ability to pan the map and add the zoom controls. We&#8217;ll center the map to 0,0.</p>
<p>The map is looking for a new LatLon variable to which you plug in two numbers. I used 0,0 to set the map at where the Equator and Prime Meridian meet. After, maps zoom level is set. This is set to the highest altitude possible. That way we can see all the natural disaster warnings across the globe. Next we call the function to start loading our RSS feeds.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/11.jpg" alt="" /></div>
<pre name="code" class="javascript">
private function onInit(event:YahooMapEvent):void
		{
			empty.addChild(map);
			map.addZoomWidget();
			map.addPanControl();
			map.addTypeWidget();
			map.zoomLevel = 17;
			map.centerLatLon = new LatLon(0,0);
			volcanoes();
		}
 </pre>
<h2>Step 18: cURLing the Feeds</h2>
<p>We have to step out of Flash for a second and do a little PHP. When I started doing this project, I realized that the feeds wouldn&#8217;t load on my website. A quick and easy way that I by-passed it was be using cURL. I found a useful sample code from Google. I&#8217;m not too sure where exactly it came from, but I&#8217;ve been using the same script for some time now. Open a new PHP file, paste in the following code and save it as &quot;curl.php&quot;</p>
<pre name="code" class="php">
&lt;?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $_POST['earl']);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);

curl_close($ch);
?&gt;
</pre>
<h2>Step 19: Back to Flash</h2>
<p>Now that we&#8217;ve called the function to start loading our volcano feed, we can take a look at what&#8217;s going on inside the function. Simply put, we are loading our curl.php page which is loading the RSS feed. We then add a listener for when the page is done loading.</p>
<pre name="code" class="javascript">
private function volcanoes():void
		{
			var url:URLLoader = new URLLoader();
			url.addEventListener(Event.COMPLETE, onVolcano);
			var vars:URLVariables = new URLVariables();
			var req:URLRequest = new URLRequest(CURL);
			req.method = URLRequestMethod.POST;
			vars.earl = "http://volcanoes.usgs.gov/rss/vhpcaprss.xml"
			req.data = vars;
			url.load(req);
		}
 </pre>
<h2>Step 20: The First Feed is Loaded</h2>
<p>In the first feed, there are a few interesting features. The most important one is the geo:point. This is the latitude and longitude of the warning. Also, in this feed, there is a color code to show the alert level of the activity. With the feed loaded, there are two xml lists that are going to be loaded. One is for the latitude and longitude. The other is for the color code.</p>
<p>The lists are looped through and the new markers are created on the map. Custom movie clips are added to the markers, these are made using functions I will describe soon. The color of the nested movie clips is controlled by using the &quot;colorTransform&quot; property. After the feed is loaded and the markers are placed, the next RSS feed is set to load. I also pass the description text to the newly created movie clip, so that I can get to it later using the name that was given to the movie clip.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/12.jpg" alt="" /></div>
<pre name="code" class="javascript">
private function onVolcano(event:Event):void
		{
			var vol:Namespace = new Namespace("http://volcano.wr.usgs.gov/rss/volcanons/1.0");
			var xml:XML = new XML(event.target.data);
			var pointList:XMLList = xml..geo::point.text();
			var colorList:XMLList = xml..vol::colorcode.text();
			var string:String;
			for(var i:uint; i</pre>
<h2>Step 21: Loading the Second Feed</h2>
<p>Now it&#8217;s time to load the earthquakes RSS feed. The functions work pretty much the same way as before.</p>
<pre name="code" class="javascript">
private function earthQuakes():void
		{
			var url:URLLoader = new URLLoader();
			var vars:URLVariables = new URLVariables();
			var req:URLRequest = new URLRequest(CURL);
			req.method = URLRequestMethod.POST;
			vars.earl = "http://earthquake.usgs.gov/eqcenter/catalogs/1day-M2.5.xml"
			req.data = vars;
			url.addEventListener(Event.COMPLETE, onEarthQuake);
			url.load(req);
		}
</pre>
<p>The differences are that there is no color code for this feed. Instead I just change the color manually to brown. Also, the description of the alert has some html inside it. I used a regular expression that I came across from Google a while back to strip all the HTML out of it.  Without doing that, the TextArea component will load an image, which I didn&#8217;t want.</p>
<p>One more thing to note is that this is a different type of RSS feed.  For some reason (in my experience) Atom feeds don&#8217;t like to parse properly. The way around this was to climb down the child tree to the first item. Also, the item node doesn&#8217;t always have the same number of children. I added a simple <em>if</em> statement to account for it. Finally, we call the function to load the last of the RSS feeds.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/13.jpg" alt="" /></div>
<pre name="code" class="javascript">
        private function onEarthQuake(event:Event):void
		{
			var xml:XML = new XML(event.target.data);
			var list:XMLList = xml..geo::point.text();
			var string:String
			for(var i:uint; i&lt;\/?\w+((\s+(\w|\w[\w-]*\w)(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?&gt;/gi;
				string = string.replace(pattern, "");
				earth.desc = string;
			}
			tsunamis();
		}
</pre>
<h2>Step 22: The Final Set of Feeds</h2>
<p>This is where we start to load the tsunami feeds. We created a tsuCounter so that we can increase the number each time a feed is loaded. When the counter reaches the end of the tsuArray, we&#8217;ll add the change listeners to the RadioButtonGroup that was created. Since I want to be able to access every marker created in every array, I added tsuCounter to the beginning of the name of the movie clip.  That way I&#8217;ll be able to access the description from 0Tsunami1 and 1Tsunami1.</p>
<p>Finally, when all the feeds have been loaded, we add the event listener to the RadioButtonGroup</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/068_YahooMaps/14.jpg" alt="" /></div>
<pre name="code" class="javascript">
private function tsunamis():void
		{
			var url:URLLoader = new URLLoader();
			var vars:URLVariables = new URLVariables();
			var req:URLRequest = new URLRequest(CURL);
			req.method = URLRequestMethod.POST;
			vars.earl = tsuArray[tsuCounter]
			req.data = vars;
			url.addEventListener(Event.COMPLETE, onTsu);
			url.load(req);
		}
        private function onTsu(event:Event):void
		{
			tsuCounter++;
			if(tsuCounter == tsuArray.length)
			{
				group.addEventListener(Event.CHANGE, onChange);
			} else
			{
				tsunamis();
			}
			var xml:XML = new XML(event.target.data);
			var list:XMLList = xml..geo::point.text();
			var string:String;
			for(var i:uint; i</pre>
<h2>Step 23: Other Functions</h2>
<p>These are the functions that are adding the markers, controlling the look of the markers, setting the longitude and latitude of the markers and creating the movie clips in the markers. The drawMarker function creates a new marker, adds a drop shadow, then adds the movie clip to it, passes the same name as the movieclip to it, gets the latitude and longitude from the loaded RSS feed and finally adds the event listeners. The marker is added the the markerManager of the map. The drawCircle function just draws a circle 10 pixels wide. The getLatlon function takes the string that is passed to it, breaks it apart and returns the LatLon. The last function, theColor, handles the different colors passed to it through the volcano feed.</p>
<pre name="code" class="javascript">
private function drawMarker(mc:MovieClip, string:String, name:String):void
		{
			var marker:Marker = new Marker();
				marker.filters = [ds];
				marker.addChild(mc);
				marker.latlon = getLatlon(string);
				marker.name = name;
				map.markerManager.addMarker(marker);
				marker.addEventListener(MouseEvent.ROLL_OVER, onOver);
				marker.addEventListener(MouseEvent.CLICK, onClick);
		}
        private function drawCircle():MovieClip
		{
			var mc:MovieClip = new MovieClip();
			mc.graphics.beginFill(0xFF0000, 1);
			mc.graphics.drawCircle(5,5,5);
			mc.graphics.endFill();
			return mc;
		}
        private function getLatlon(string:String):LatLon
		{
			var array:Array = string.split(/[\s]/);
			var latlon:LatLon = new LatLon(array[0], array[1]);
			return latlon;
		}
        private function theColor(string:String):ColorTransform
		{
			var int:uint;
			switch (string)
			{
				case "ORANGE" :
				int = 0xFD8000;
				break;
				case "GREEN" :
				int = 0x225E33;
				break;
				default :
				int = 0xFF0000;
			}
			var ct:ColorTransform = new ColorTransform();
			ct.color = int;
			return ct;
		}
</pre>
<h2>Step 24: Event Handling</h2>
<p>When the user rolls over the marker, the description of the alert is displayed in the TextArea component. This is handled through the onOver function. The target is cast as a marker using the name that was passed it. Then we receive the description text that was passed to the movieclip nested inside the marker and send it to the TextArea component. The onClick event pans the map to whichever marker was clicked. This is done by using the map.panToLatLon() method.</p>
<pre name="code" class="javascript">
private function onOver(event:MouseEvent):void
		{
			var marker:Marker = Marker(map.markerContainer.getChildByName(event.target.name))
			var mc:MovieClip = MovieClip(marker.getChildByName(event.target.name));
			textArea.htmlText = mc.desc;
		}
		private function onClick(event:MouseEvent):void
		{
			var marker:Marker = Marker(map.markerContainer.getChildByName(event.target.name))
			map.panToLatLon(marker.latlon);
		}
</pre>
<p>The final event is the onChange event. This event turns off all the movie clips except the selected buttons. It also pans the map to the most recent alert that was received in the RSS feed.</p>
<pre name="code" class="javascript">
        private function onChange(event:Event):void
		{
			var g:RadioButtonGroup = RadioButtonGroup(event.target);
			var i:uint;
			var marker:Marker;
			var panTo:Marker;
			switch(g.selection.name)
			{
				case "radioVolcano" :
				for(i = 0; i</pre>
<h2>The Final Code</h2>
<p>Here is what the final code looks like.
</p>
<pre name="code" class="javascript">
package {

	import com.yahoo.maps.api.YahooMap;
	import com.yahoo.maps.api.YahooMapEvent;
	import com.yahoo.maps.api.core.location.LatLon;
	import com.yahoo.maps.api.markers.Marker;

	import fl.controls.RadioButtonGroup;
	import fl.controls.RadioButton;

	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.DropShadowFilter;
	import flash.geom.ColorTransform;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.text.AntiAliasType;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	public class yahoo_map extends Sprite
	{
		private static const APPID:String = "YOUR APP ID";
		private static const CURL:String = "curl.php";
		private var map:YahooMap;
		private var ds:DropShadowFilter;
		private var geo:Namespace;
		private var tsuArray:Array;
		private var tsuCounter:int = 0;
		private var color:ColorTransform;
		private var group:RadioButtonGroup;

		public function yahoo_map()
		{
			init();
		}
		private function init():void
		{
			color = new ColorTransform();
			tsuArray = new Array("http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_pacific.xml", "http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_hawaii.xml", "http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_indian.xml", "http://www.prh.noaa.gov/ptwc/feeds/ptwc_rss_caribe.xml");
			geo = new Namespace("http://www.georss.org/georss");
			ds = new DropShadowFilter(2,90,0x00000,0.75,2,2,1,3);
			group = new RadioButtonGroup("Disasters");
			handleMap();
		}
		private function handleMap():void
		{
			map = new YahooMap();
			map.addEventListener(YahooMapEvent.MAP_INITIALIZE, onInit);
			map.init(APPID, stage.stageWidth, 330);
		}
		private function onInit(event:YahooMapEvent):void
		{
			empty.addChild(map);
			map.addZoomWidget();
			map.addPanControl();
			map.addTypeWidget();
			map.zoomLevel = 17;
			map.centerLatLon = new LatLon(0,0);
			volcanoes();
		}
		private function volcanoes():void
		{
			var url:URLLoader = new URLLoader();
			url.addEventListener(Event.COMPLETE, onVolcano);
			var vars:URLVariables = new URLVariables();
			var req:URLRequest = new URLRequest(CURL);
			req.method = URLRequestMethod.POST;
			vars.earl = "http://volcanoes.usgs.gov/rss/vhpcaprss.xml"
			req.data = vars;
			url.load(req);
		}
		private function onVolcano(event:Event):void
		{
			var vol:Namespace = new Namespace("http://volcano.wr.usgs.gov/rss/volcanons/1.0");
			var xml:XML = new XML(event.target.data);
			var pointList:XMLList = xml..geo::point.text();
			var colorList:XMLList = xml..vol::colorcode.text();
			var string:String;
			for(var i:uint; i&lt;\/?\w+((\s+(\w|\w[\w-]*\w)(\s*=\s*(?:\".*?\"|'.*?'|[^'\"&gt;\s]+))?)+\s*|\s*)\/?>/gi;
				string = string.replace(pattern, "");
				earth.desc = string;
			}
			tsunamis();
		}
		private function tsunamis():void
		{
			var url:URLLoader = new URLLoader();
			var vars:URLVariables = new URLVariables();
			var req:URLRequest = new URLRequest(CURL);
			req.method = URLRequestMethod.POST;
			vars.earl = tsuArray[tsuCounter]
			req.data = vars;
			url.addEventListener(Event.COMPLETE, onTsu);
			url.load(req);
		}
		private function onTsu(event:Event):void
		{
			tsuCounter++;
			if(tsuCounter == tsuArray.length)
			{
				group.addEventListener(Event.CHANGE, onChange);
			} else
			{
				tsunamis();
			}
			var xml:XML = new XML(event.target.data);
			var list:XMLList = xml..geo::point.text();
			var string:String;
			for(var i:uint; i</pre>
<h2>Conclusion</h2>
<p>I&#8217;ve barely scratched the surface for what YahooMaps has under the hood. Read the documentation and go nuts!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/plotting-points-using-yahoomaps-and-rss/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Create a Shuffle Gallery in Flash Using XML and ActionScript 3.0</title>
		<link>http://active.tutsplus.com/tutorials/xml/create-a-shuffled-gallery-in-flash-using-xml-and-actionscript-3/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/create-a-shuffled-gallery-in-flash-using-xml-and-actionscript-3/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 12:00:41 +0000</pubDate>
		<dc:creator>Carlos Yanez</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=1369</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Preview/Preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>In this tutorial I&#8217;ll explain how to access and use the Display List whilst creating an XML based image gallery with ActionScript 3.0.</p>
<p><span id="more-1369"></span></p>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/source.zip" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/source.jpg" alt="" style="border:none"></a><br />
<a href="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Src/preview.html" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1: Overview</h2>
<p>Using XML we&#8217;ll dynamically load and obtain information about the images, give them a random center position, add a frame, add drag functionality, and lastly, we&#8217;ll use a tween to handle the zoom animation.</p>
<h2>Step 2: Let&#8217;s Get Started</h2>
<p>Open Flash and create a new Flash File (ActionScript 3).</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/1.jpg" alt="" /></div>
<p>Set the stage size to 600&#215;350 and add a gray radial gradient (#EEEEEE, #DDDDDD).</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/2.jpg" alt=”” /></div>
<h2>Step 3: Adding a Preloader</h2>
<p>We&#8217;re going to add a preloading animation to tell the user when the content is loading. In this case I used the <a href="http://flash.tutsplus.com/tutorials/web-design/create-an-apple-inspired-flash-preloader/">Apple inspired preloader</a> that we created before. Since we&#8217;re going to use only the animation, there&#8217;s no need to import the class or use an Export Identifier.</p>
<p>Place the preloader on the stage and center it.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/3.jpg" alt="" /></div>
<h2>Step 4: Embedding a Font</h2>
<p>We&#8217;re going to embed a font, a super easy task when adding a TextField to the Stage in the Flash IDE, but a little different using ActionScript.</p>
<p>Open the Library Panel and right-click in the items area without selecting one, a contextual menu will appear.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/4.jpg" alt="" /></div>
<p>Click on &quot;New Font&quot; to open a dialog window, give a name to your font and select the one you want to use as shown in the following image.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/5.jpg" alt="" /></div>
<p>This will create a class of the font you selected, we&#8217;ll instantiate this in Step 9.</p>
<h2>Step 5: XML</h2>
<p>Let&#8217;s create the XML file.</p>
<p>Open your prefered XML or Text editor and write:</p>
<pre name="code" class="xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;images&gt;
	&lt;image src=&quot;images/image.jpg&quot; title=&quot;This is image 1&quot;/&gt;
	&lt;image src=&quot;images/image2.jpg&quot; title=&quot;This is image 2&quot;/&gt;
	&lt;image src=&quot;images/image3.jpg&quot; title=&quot;This is image 3&quot;/&gt;
	&lt;image src=&quot;images/image4.jpg&quot; title=&quot;This is image 4&quot;/&gt;
	&lt;image src=&quot;images/image5.jpg&quot; title=&quot;This is image 5&quot;/&gt;
&lt;/images&gt;
</pre>
<p>When you&#8217;re done, save it as &quot;images.xml&quot; in your xml folder.</p>
<h2>Step 6: ActionScript</h2>
<p>The code that we&#8217;ll use will be written in a single class that will be used as the Document Class in the FLA file.</p>
<p>Create a new ActionScript File (File &gt; New)</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/6.jpg" alt="" /></div>
<p>Save it as &quot;Main.as&quot;.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/7.jpg" alt="" /></div>
<h2>Step 7: Package</h2>
<p>We&#8217;ll begin with:</p>
<pre name="code" class="javascript">
package classes
{</pre>
<p>The <em>package</em> keyword allows you to organize your code into groups that can be imported by other scripts, it&#8217;s recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: <em>galleryClasses</em>.</p>
<p>If you don&#8217;t want to group your files in a package or you have only one class, you can use it right from your source folder, but the idea is to be organized.</p>
<h2>Step 8: Required Classes</h2>
<pre name="code" class="javascript">
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.filters.BitmapFilter;
import flash.filters.DropShadowFilter;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.text.AntiAliasType;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import fl.transitions.TweenEvent;</pre>
<p>These are the classes that we&#8217;ll need to make this gallery. If you need help with a specific class please use the Flash Help (F1).</p>
<h2>Step 9: Extending the Class</h2>
<pre name="code" class="javascript">
public class Main extends MovieClip
{</pre>
<p>The <em>extends</em> keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.</p>
<p>We&#8217;re going to use MovieClip specific methods and properties so we extend using the MovieClip Class.</p>
<h2>Step 10: Variables</h2>
<pre name="code" class="javascript">
var xml:XML; // The XML Object that will parse the XML File
var images:Array = new Array(); //This array will store the images loaded
var imagesLoaded:int = 0; //A counter, counts the images loaded
var imagesTitle:Array = new Array(); //The title properties of the XML File
var tween:Tween; //Handles the animation
var zoomed:Boolean = false; //Checks if a picture is zoomed, false by default
var canClick:Boolean = true; //Checks if the user can click a picture to zoom it, true by default
var lastX:int; //Stores the x property of the last picture that was clicked
var lastY:int; //Stores the y property of the last picture that was clicked
var textformat:TextFormat = new TextFormat(); //A TextFormat Object
var screen:Sprite = new Sprite(); //A black screen to focus on the active picture

var formatFont:Avenir = new Avenir(); //This is the embedded font</pre>
<h2>Step 11: Constructor</h2>
<p>The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object or when using the Document Class.</p>
<p>In this function we&#8217;ll set the properties of the TextFormat object that we&#8217;ll use to display a title or a description of each image. Create the black screen that appears when the user clicks on a picture and call the function which loads the desired XML file.</p>
<pre name="code" class="javascript">
public function Main():void
{
	textformat.color = 0xFFFFFF;
	textformat.font = formatFont.fontName;
	textformat.size = 17; //Use the same size you used when embedding the font from the Library

	screen.graphics.beginFill(0x111111, .75);
	screen.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
	screen.graphics.endFill();

	loadXML("xml/images.xml");
}</pre>
<h2>Step 12: XML Loader Function</h2>
<p>This function loads the XML file provided by the &quot;file&quot; parameter. We also add a listener to handle when the load is complete.</p>
<pre name="code" class="javascript">
private function loadXML(file:String):void
{
	var urlLoader:URLLoader = new URLLoader();
	var urlReq:URLRequest = new URLRequest(file);

	urlLoader.load(urlReq);
	urlLoader.addEventListener(Event.COMPLETE, handleXML);
}</pre>
<h2>Step 13: Parse XML</h2>
<p>Here we convert the loaded XML file to a valid XML object using the parameter &quot;data&quot; of the URLLoader. Then we use a &quot;for&quot; statement to create a Loader for every image in the XML. Additional information is found in the commentary.</p>
<pre name="code" class="javascript">
private function handleXML(e:Event):void
{
	xml = new XML(e.target.data);

	for (var i:int = 0; i &lt; xml.children().length(); i++)
	{
		var loader:Loader = new Loader();

		loader.load(new URLRequest(String(xml.children()[i].@src)));

		images.push(loader); //Adds the Loaders to the images Array to gain access to them outside this function
		imagesTitle.push(xml.children()[i].@title); //Adds the title attribute content to the array to use it outside this function

		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); //A listener to the function that will be executed when an image is loaded
	}
}</pre>
<h2>Step 14: Images Loaded</h2>
<p>When a Loader has loaded an image from the XML, the following code is executed:</p>
<pre name="code" class="javascript">
private function loaded(e:Event):void
{
	imagesLoaded++; //Adds one to the imagesLoaded variable

	if (xml.children().length() == imagesLoaded) //When all images are loaded...
	{
		removeChild(preloader); //Removes the Preloader MovieClip
		prepareImages(); //This function is explained in the next step
	}
} </pre>
<h2>Step 15: Prepare Images</h2>
<p>This function will add the frame, the TextField to display the title or description, the black background used for that and a Shadow Filter. Let&#8217;s take it in parts.</p>
<pre name="code" class="javascript">
private function prepareImages():void
{
	for (var i:int = 0; i &lt; images.length; i++) //These actions will be applied to all the images loaded so we use a &quot;for&quot; and the &quot;images&quot; array to do that
	{
		var container:Sprite = new Sprite(); //A container that will store the image, frame, TextField, TextField background and shadow
		var frame:Sprite = new Sprite(); //The Frame Sprite
		var infoArea:Sprite = new Sprite(); //The TextField background
		var infoField:TextField = new TextField(); //The TextField</pre>
<h2>Step 16: Image Frame</h2>
<p>This creates a white frame around the image.</p>
<pre name="code" class="javascript">
frame.graphics.beginFill(0xFFFFFF);
frame.graphics.drawRect(-20, -20, images[i].width + 40, images[i].height + 80);
frame.graphics.endFill();</pre>
<p>The rectangle will be positioned under the image to be used as a frame.</p>
<h2>Step 17: Information Background</h2>
<p>This creates a black rectangle in the bottom part of the image, where the TextField will be.</p>
<pre name="code" class="javascript">
infoArea.graphics.beginFill(0x111111, 0.75);
infoArea.graphics.drawRect(0, 0, images[i].width, 60);
infoArea.graphics.endFill();
infoArea.y = images[i].height - 60;</pre>
<h2>Step 18: Image Information</h2>
<p>The following code sets the TextField properties and adds its contents.</p>
<pre name="code" class="javascript">
infoField.defaultTextFormat = textformat;
infoField.embedFonts = true; //You have to add this to use the embedded font
infoField.antiAliasType = AntiAliasType.ADVANCED; //This property will display the text more clearly
infoField.width = images[i].width - 5;
infoField.height = 20;

infoField.text = imagesTitle[i]; //The content, obtained from the XML and stored in the Array</pre>
<h2>Step 19: Resizing the Images</h2>
<p>Here we set the desired scale of the images. Since everything will be inside the Container Sprite, we only need to resize it.</p>
<pre name="code" class="javascript">
container.scaleX = 0.3;
container.scaleY = 0.3;</pre>
<h2>Step 20: Position</h2>
<p>The images will have a random position based on the center of the Stage area. We use Math for that.</p>
<pre name="code" class="javascript">
container.x = stage.stageWidth / 4 + Math.floor(Math.random() * (stage.stageWidth / 4));
container.y = stage.stageHeight / 5 + Math.floor(Math.random() * (stage.stageHeight / 5));</pre>
<h2>Step 21: Shadow Filter</h2>
<p>This will create a Shadow Filter.</p>
<pre name="code" class="javascript">
var shadowFilter:BitmapFilter = new DropShadowFilter(3, 90, 0x252525, 1, 2, 2, 1, 15); //Distance, angle, color, alpha, blur, strength, quality
var filterArray:Array = [shadowFilter];

container.filters = filterArray; //Apply the filter</pre>
<h2>Step 22: Adding to Stage</h2>
<p>Time to add the Children, the order in which we add them is the order they will take in the Display List, so be sure to add them in this way.</p>
<pre name="code" class="javascript">
infoArea.addChild(infoField); //Adds the TextField to the TextField Background

container.addChild(frame); //Adds the Frame to the Container
container.addChild(images[i]); //Adds the Image on top of the Frame in the Container

infoArea.visible = false; //We set the image information to invisible by default

container.addChild(infoArea); //Adds the information area in top of everything</pre>
<h2>Step 23: Listeners</h2>
<p>Although we could add the Listeners to every Sprite before, I&#8217;m going to add them now that they are inside the Container to show you how the Display List works.</p>
<div class="tutorial_image"><img src="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/8.jpg" alt="" /></div>
<pre name="code" class="javascript">
container.getChildAt(1).addEventListener(MouseEvent.MOUSE_UP, zoomHandler); //This is the Image loaded by the XML, this is the Loader object
container.getChildAt(0).addEventListener(MouseEvent.MOUSE_DOWN, dragImage); //This is the Frame
container.getChildAt(0).addEventListener(MouseEvent.MOUSE_UP, stopDragImage); //Frame

addChild(container); //Lastly, we add the Container to the Stage
</pre>
<h2>Step 24: Drag Functions</h2>
<p>In the previous step we added two listeners to the Frame of the images. These functions will take care of the drag.</p>
<p>We use &quot;parent&quot; beacuse we want to drag all the objects, since the &quot;target&quot; is the Frame Sprite, the parent object is the Container.</p>
<pre name="code" class="javascript">
private function dragImage(e:MouseEvent):void
{
	e.target.parent.startDrag();
}

private function stopDragImage(e:MouseEvent):void
{
	e.target.parent.stopDrag();
}</pre>
<h2>Step 25: Zoom</h2>
<p>This function is in charge of zooming in and out. Its Listener is in the actual image, so clicking in the Frame will not call this function.</p>
<p><em><b>Editor&#8217;s Note:</b> For some reason, the <b>else if ()</b> statement within this zoomHandler function was making our syntax highlighter crash. As it doesn&#8217;t want to display on the page, I&#8217;ve made the function <a href="http://flashtuts.s3.cdn.plus.org/070_ShuffleGallery/Tutorial/zoomHandler.as" target="_blank">available for download</a>. Sorry for any inconvenience, Ian.</em></p>
<h2>Step 26: Motion Finish</h2>
<p>Some actions need to be executed when the Tweens are finished, these are those actions.</p>
<pre name="code" class="javascript">
private function zoomInFinished(e:TweenEvent):void
{
	zoomed = true; //Modify the variables according to the event
	canClick = true;
	tween.obj.getChildAt(2).visible = true; //Sets the Information area to visible
}

private function zoomOutFinished(e:TweenEvent):void
{
	zoomed = false;
	removeChild(screen); //Removes the black screen

	tween.obj.getChildAt(0).addEventListener(MouseEvent.MOUSE_DOWN, dragImage); //Adds the drag listener back to the Frame Sprite
}</pre>
<h2>Step 27: Document Class</h2>
<p>Go back to the FLA and add <em>Main</em> as the Document Class in the Properties Panel. If you save your class in a package you have to add the name of the package too, something like: <em>yourpackage.Main</em></p>
<p>Test your file and see your gallery working!</p>
<h2>Conclusion</h2>
<p>As always, try different things in your code to make the gallery just as you want.</p>
<p>I hope you enjoyed this tut, thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/create-a-shuffled-gallery-in-flash-using-xml-and-actionscript-3/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Develop an OOP Drop Down Menu Using ActionScript 3.0 Documents</title>
		<link>http://active.tutsplus.com/tutorials/xml/develop-an-oop-drop-down-menu-using-actionscript-30-documents/</link>
		<comments>http://active.tutsplus.com/tutorials/xml/develop-an-oop-drop-down-menu-using-actionscript-30-documents/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 12:00:14 +0000</pubDate>
		<dc:creator>Andre Cavallari</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://flash.tutsplus.com/?p=631</guid>
		<description><![CDATA[<img src="http://flashtuts.s3.cdn.plus.org/027_DropDownMenu/preview/preview.jpg" alt="">]]></description>
			<content:encoded><![CDATA[<p>In this, my first tutorial for Flashtuts+, I&#8217;ll quickly explain how to create an object oriented drop down menu. We&#8217;ll use ActionScript 3.0 and pull all the necessary data from an xml file.</p>
<p>The resulting menu can be used in any flash file without needing recoding.</p>
<p><span id="more-631"></span></p>
<div class="tutorial_image">
<a href="http://flashtuts.s3.cdn.plus.org/027_DropDownMenu/Source.zip" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/source.jpg" alt="" style="border:none"></a><br />
<a href="http://flashtuts.s3.cdn.plus.org/027_DropDownMenu/preview.html" target="_blank"><br />
<img src="http://flashtuts.s3.cdn.plus.org/demo.jpg" alt="" style="border:none"></a>
</div>
<h2>Step 1 &#8211; Setting the Classpath</h2>
<p>First, we&#8217;ll setup a classpath. If you dont yet have one, it&#8217;s a useful place for putting ActionScript files that you use in every project. This way you dont need to copy the ActionScript files to a folder of the fla document everytime that you create a new website or application.</p>
<p>Create a folder for ActionScripts files in c:. I&#8217;ll create the folder c:/myActionScripts, but you can create a directory anywhere you want with any name you wish.</p>
<p>For flash CS3, go to Edit &gt; Preferences. In the category menu of the preferences panel, select &quot;ActionScript&quot;. On right side of the panel, click the button &quot;ActionsScript 3.0 settings&#8230;&quot;.</p>
<p>This will open another panel (Actionscript 3.0 settings panel). Click the plus button ( + ) and type &quot;c:/myActionScripts&quot;, or whatever your directory location is. Then just click OK in all the open panels, now we have a classpath.</p>
<p>For flash CS4, go to Edit &gt; Preferences. In the category menu of the preferences panel, select &quot;ActionScript&quot;. On right side of the panel, click the button &quot;ActionsScript 3.0 settings&#8230;&quot;.</p>
<p>This will open a panel called &quot;Actionscript 3.0 Advanced Settings&quot;. In the &quot;source path&quot; area, click the plus button ( + ) and type c:/myActionScripts, or whatever your directory location is. Then just click OK in all the open panels, now we have a classpath.</p>
<h2>Step 2 &#8211; Downloading Classes and Creating Folders</h2>
<p>Go to <a href="http://blog.greensock.com/tweenliteas3/">http://blog.greensock.com/tweenliteas3/</a> and download the TweenLite ActionScript 3.0 class, courtesy of Jack Doyle. This class is much better than the Tween class built in flash CS3 and flash CS4.</p>
<p>When the download is finished, just uncompress the contents of &quot;gs&quot; inside the .zip file to c:/myActionScripts/gs to make the TweenLite class available for use any time you want, without needing to copy the gs folder to an equivalent folder of your project.</p>
<p>Also, create the folder c:/myActionScripts/dropdownmenu. We&#8217;ll put the ActionScript files from this tutorial here. We&#8217;ll then be able to use our DropDownMenu Object whenever we want, without needing to copy the dropdownmenu folder to each project. This is the advantage of using a classpath.</p>
<h2>Step 3 &#8211; Creating the XML Documents</h2>
<p>I&#8217;ll be using 5 xml files, one xml for the main drop down menu and others to populate data in the second drop down menu. Save all the xml files in c:/dropdownexample/xml.</p>
<p>Save the first xml document as &quot;menu.xml&quot; in the folder &quot;xml&quot;. Fill it with data such as:</strong></p>
<pre name="code" class="javascript">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;menu&gt;
	&lt;item caption=&quot;Company contacts&quot; value=&quot;xml/contactlist1.xml&quot; /&gt;
	&lt;item caption=&quot;Home contacts&quot; value=&quot;xml/contactlist2.xml&quot; /&gt;
	&lt;item caption=&quot;Friends&quot; value=&quot;xml/contactlist3.xml&quot; /&gt;
	&lt;item caption=&quot;School contacts&quot; value=&quot;xml/contactlist4.xml&quot; /&gt;
&lt;/menu&gt;
</pre>
<p>Save a second xml document as &quot;contactlist1.xml&quot; in the xml folder, data as follows:</p>
<pre name="code" class="javascript">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;menu&gt;
	&lt;item caption=&quot;Director area&quot; value=&quot;director@company.com&quot; /&gt;
	&lt;item caption=&quot;Finance area&quot; value=&quot;finance@company.com&quot; /&gt;
	&lt;item caption=&quot;Designing area&quot; value=&quot;designing@company.com&quot; /&gt;
	&lt;item caption=&quot;Care area&quot; value=&quot;care@company.com&quot; /&gt;
	&lt;item caption=&quot;Print area&quot; value=&quot;print@company.com&quot; /&gt;
	&lt;item caption=&quot;Internet area&quot; value=&quot;internet@company.com&quot; /&gt;
	&lt;item caption=&quot;Knowlege area&quot; value=&quot;knowlege@company.com&quot; /&gt;
&lt;/menu&gt;
</pre>
<p>Save a third xml document as &quot;contactlist2.xml&quot; in the xml folder, data as follows:</p>
<pre name="code" class="javascript">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;menu&gt;
	&lt;item caption=&quot;Mom&quot; value=&quot;mom@hotmail.com&quot; /&gt;
	&lt;item caption=&quot;Daddy&quot; value=&quot;daddy@gmail.com&quot; /&gt;
	&lt;item caption=&quot;Brother&quot; value=&quot;brother@live.com&quot; /&gt;
	&lt;item caption=&quot;Syster&quot; value=&quot;syster@email.com&quot; /&gt;
&lt;/menu&gt;
</pre>
<p>Save another xml document as &quot;contactlist3.xml&quot; in the xml folder, data as follows:</p>
<pre name="code" class="javascript">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;menu&gt;
	&lt;item caption=&quot;Tim&quot; value=&quot;tim@email.com&quot; /&gt;
	&lt;item caption=&quot;Sam&quot; value=&quot;sam@hotmail.com&quot; /&gt;
	&lt;item caption=&quot;David&quot; value=&quot;david@live.com&quot; /&gt;
	&lt;item caption=&quot;Julio&quot; value=&quot;julio@gmail.com&quot; /&gt;
	&lt;item caption=&quot;Lucas&quot; value=&quot;lucas@uol.com.br&quot; /&gt;
&lt;/menu&gt;
</pre>
<p>Finally, create the last xml document as &quot;contactlist4.xml&quot;, again in the xml folder with the following data:</p>
<pre name="code" class="javascript">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;menu&gt;
	&lt;item caption=&quot;Math teacher&quot; value=&quot;math@myschool.com&quot; /&gt;
	&lt;item caption=&quot;English teacher&quot; value=&quot;english@myschool.com&quot; /&gt;
	&lt;item caption=&quot;Geography teacher&quot; value=&quot;geography@myschool.com&quot; /&gt;
	&lt;item caption=&quot;History teacher&quot; value=&quot;hisroty@myschool.com&quot; /&gt;
	&lt;item caption=&quot;Fisic teacher&quot; value=&quot;fisic@myschool.com&quot; /&gt;
&lt;/menu&gt;
</pre>
<h2>Step 4 &#8211; Coding the MenuItem Object</h2>
<p>Now we&#8217;ll start coding the MenuItem Object. This is required for our drop down menu and will build the items in the list.</p>
<p>Start creating the package, we&#8217;ll save the file in c:/myActionScripts/dropdownmenu so the package is called &quot;dropdownmenu&quot;, then we&#8217;ll import the classes that we want to use in this object.</p>
<pre name="code" class="javascript">
package dropdownmenu{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.events.*;
	import gs.TweenLite;
</pre>
<p>Now create the class MenuItem. As we&#8217;re extending the Sprite class, we&#8217;ll have all the methods and properties of that class, but we&#8217;ll still add more.</p>
<p>Note that we&#8217;ll save this ActionScript file as &quot;MenuItem.as&quot; in the dropdownmenu folder. The package therefore has the same name as the folder and the class has the same name as the .as file.</p>
<pre name="code" class="javascript">
public class MenuItem extends Sprite{</pre>
<p>Declare and set the variables here, so you can use them with any function in the class. We&#8217;ll set as them private so only this class has access to them. If you declare the variables inside a function, only that function will have access to the variable. In our case, we want the entire class to have access to the variables.</p>
<pre name="code" class="javascript">private var _value:String;
private var txt:TextField=new TextField();
private var txtFormat:TextFormat=new TextFormat();</pre>
<p>We&#8217;ll declare the following function as public, so you can access it from anywhere. This function has the same name as the class It&#8217;s the constructor function and will be called when we instantiate this object. It will be the first function to be executed and will be executed every time you create a new object of MenuItem. The constructor function is always public.</p>
<p>We&#8217;ll pass the caption, value, width and height values through the constructor:</p>
<pre name="code" class="javascript">
public function MenuItem(caption:String,value:String,_width:int=200,_height:int=20):void{</pre>
<p>Now we&#8217;ll set this class to &quot;buttonMode&quot;, so it will behave like a button and the hand cursor will show every time you pass the mouse over it.  We set the alpha to .8 (this will be the mouse out state) we&#8217;ve declared the _value variable before, outside the function, so here we make the value visible to any other function of the class and the _width we reduce by 10, so the menu item will be a little bit smaller.</p>
<pre name="code" class="javascript">this.buttonMode=true;
this.alpha=.8;
_value=value;
_width-=10</pre>
<p>Draw a black rectangle for the background (this can be any color, just change the 0&#215;000000 to whatever you want).</p>
<pre name="code" class="javascript">this.graphics.beginFill(0x000000);
this.graphics.drawRect(0,0,_width,_height);</pre>
<p>Now we&#8217;ll set the text format object. It&#8217;s created outside the function and will be accessible to any function in this class. This will be our item caption (a dynamic textfield).</p>
<pre name="code" class="javascript">txtFormat.color=0xFFFFFF;
txtFormat.size=10;
txtFormat.font=&quot;Verdana&quot;;</pre>
<p>Now we&#8217;ll set the default textfield format to the text format object. We&#8217;ll disable the mouse interactivity of the textfield, so the text wont be clickable (this works with any displayed object). We&#8217;ll set the text of txt dynamic text field as the variable &quot;caption&quot; passed through the constructor parameter. Then it&#8217;s a question of setting the position x and y of the textfield and its width and height. Then we add the text to the MenuItem Object´s display list.</p>
<pre name="code" class="javascript">txt.defaultTextFormat=txtFormat;
txt.mouseEnabled=false;
txt.text=caption;
txt.x=5;
txt.y=2;
txt.width=_width-10;
txt.height=_height-4;
addChild(txt);</pre>
<p>Now let&#8217;s add the events. When we add this object to the stage, the addedToStage function will be called. When we pass the mouse over the object, the mouseOver function will be called. When we take the mouse out of this object the mouseOut function will be called. We also close the constructor function with a &quot;}&quot; at the end.</p>
<pre name="code" class="javascript">addEventListener(Event.ADDED_TO_STAGE,addedToStage);
addEventListener(MouseEvent.MOUSE_OVER,mouseOver);
addEventListener(MouseEvent.MOUSE_OUT,mouseOut);
}</pre>
<p>Insert a new function here. When the mouse is over the object it will smoothly set the alpha to 1, so this object appears different to the others (mouse over state).</p>
<pre name="code" class="javascript">private function mouseOver(e:MouseEvent):void{
    new TweenLite(this,1,{alpha:1});
}</pre>
<p>When we take the mouse out of the object, the alpha will smoothly be set back to .8 (the mouse out state).</p>
<pre name="code" class="javascript">private function mouseOut(e:MouseEvent):void{
    new TweenLite(this,1,{alpha:.8});
}</pre>
<p>When this object is added to the stage, we set the object&#8217;s position by getting its index in the displaylist and multiplying this by its height. We have a sequence of indexes (0, 1, 2, 3) and will position one object upon the other, not over one another.</p>
<pre name="code" class="javascript">private function addedToStage(e:Event):void{
    this.y=this.parent.getChildIndex(this)*this.height;
}</pre>
<p>The function &quot;get&quot; is a property, it works like a variable but it is read only. You cant set those values outside this class, but you can read them. They return the value of variables or textfields which are inaccessible outside the class.</p>
<pre name="code" class="javascript">public function get caption():String{ return txt.text; }
public function get value():String{ return _value; }</pre>
<p>Now close the class and the package we opened at the start of the file. Save it as &quot;MenuItem.as&quot; at c:/myActionScripts/dropdownmenu, the file should be located at c:/myActionScripts/dropdownmenu/MenuItem.as</p>
<pre name="code" class="javascript">  }
}
</pre>
<h2>Step 5 &#8211; Create the Custom Event</h2>
<p>Now we&#8217;ll create a custom event for this class. When we change the menu item we&#8217;ll get the value through this event.</p>
<p>Start the package, import the Event and create the class extending the Event class. Now we have a new Event class which we&#8217;ll call &quot;DropDownMenuEvent&quot;.</p>
<pre name="code" class="javascript">package dropdownmenu{
import flash.events.Event;
public class DropDownMenuEvent extends Event{</pre>
<p>Static variables, functions or constants can be accessed without needing to instantiate the object. You don&#8217;t need to use the new statement, you can simply access it by using: DropDownMenuEvent.CHANGE</p>
<p>The const are constants. Once you have set a value to the const, its value can&#8217;t be changed. You can use lowercase to name constants, but by default almost everbody uses uppercase for constants and we won&#8217;t do any different.</p>
<pre name="code" class="javascript">public static const CHANGE:String=&quot;change&quot;;</pre>
<p>Instantiate these String objects right here to ensure access from anywhere in this class.</p>
<pre name="code" class="javascript">private var _caption:String;
private var _value:String;</pre>
<p>Now create the constructor function. The super(type) is to set this class as a superclass.</p>
<pre name="code" class="javascript">public function DropDownMenuEvent(type:String,caption:String,value:String):void{
	super(type);
	_caption=caption;
	_value=value;
}</pre>
<p>Now make the getter functions of the class, to get the values as read only. I´ve explained before how the getter function works.</p>
<pre name="code" class="javascript">public function get caption():String{ return _caption; }
public function get value():String{ return _value; }</pre>
<p>Close the package and the class using &quot;}&quot; and save as c:/myActionScripts/dropdownmenu/DropDownMenuEvent.as</p>
<pre name="code" class="javascript">}
}
</pre>
<h2>Step 6 &#8211; Create the DropDownMenu Object</h2>
<p>I saved this object for last because it´s more complex. Also, it won&#8217;t work without the 2 classes created above.</p>
<p>This part is already well explained; we&#8217;ll define the package, import all the classes that we&#8217;ll use, create the class extending the Sprite, set the variables outside the functions to use with any other function of this class, then start the constructor function. Nothing new here.</p>
<p>I also shouldn&#8217;t need to say again that the class, the constructor and the file name are the same. </p>
<p>The constructor function has all the parameters pre-defined, so we can choose whether or not to pass parameters. We could pass just the first parameter, or the first and the second, or the first, the second and the third. We could also pass the first parameter as null, so it will be the same value as the pre-defined value in the constructor.</p>
<pre name="code" class="javascript">package dropdownmenu{
	import flash.display.Sprite;
	import flash.display.Shape;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.xml.*;
	import flash.events.*;
	import flash.display.Graphics;
	import flash.display.GradientType;
	import flash.geom.Matrix;
	import flash.display.SimpleButton;
	import gs.TweenLite;
	public class DropDownMenu extends Sprite{
		private var container:Sprite=new Sprite();
		private var req:URLRequest=new URLRequest();
		private var loader:URLLoader=new URLLoader();
		private var txt:TextField=new TextField();
		private var txtFormat:TextFormat=new TextFormat();
		private var button:SimpleButton=new SimpleButton();
		private var _value:String;
       public function DropDownMenu(url:String=null,_width:int=200,_height:int=30):void{</pre>
<p>The container is a sprite, created above outside any function for the entire class have access. We&#8217;ll put all the menu items inside the container; set the y property to the _height param. The container will be invisible to begin with(alpha=0), so it can&#8217;t be clicked. Even if it were visible, the alpha is still 0, so it won&#8217;t show yet.</p>
<pre name="code" class="javascript">container.y=_height;
container.alpha=0;
container.visible=false;
addChild(container);</pre>
<p>Create a background and add to the object. The drawObject is a function that returns a Shape, we&#8217;ll see this a little later.</p>
<pre name="code" class="javascript">var bg:Shape=drawObject(_width,_height);
addChild(bg);</pre>
<p>Again, we set the textFormat object properties and set the defaultTextFormat property of the txt object as the textFormat object. We disable interactivity with the mouse, set a default text while the xml is not loaded yet and add the txt textField to this object display list. All of these actions have been seen before, so they don&#8217;t need too much explanation.</p>
<pre name="code" class="javascript">txtFormat.bold=true;
txtFormat.size=15;
txtFormat.font=&quot;Verdana&quot;;
txt.defaultTextFormat=txtFormat;
txt.x=5;
txt.y=3;
txt.width=_width-10;
txt.height=_height-6;
txt.mouseEnabled=false;
txt.text=&quot;XML not loaded&quot;;
addChild(txt);</pre>
<p>The button, created outside the function, can be acessed from anywhere in this class. We set a new Shape for the hitTestState, then add an event. When clicked it will call for function &quot;open&quot;. We then add the button to this object´s display list.</p>
<pre name="code" class="javascript">button.hitTestState=drawObject(_width,_height);
button.addEventListener(MouseEvent.CLICK,open);
addChild(button);</pre>
<p>Now add the event listeners. One for the loader when the loader has fully completed loading the xml document. This will call the function loaderComplete, or if the loader doesn&#8217;t find the xml document it will call the function loaderIOError</p>
<p>This class when added to the stage will call the function addedToStage. When removed from stage it will call the function removedFromStage.</p>
<pre name="code" class="javascript">loader.addEventListener(Event.COMPLETE,loaderComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR,loaderIOError);
addEventListener(Event.ADDED_TO_STAGE,addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE,removedFromStage);</pre>
<p>Here we check if any value other than null was passed to url param of the constructor. If so, we&#8217;ll set the url ( private var url:URLRequest=new URLRequest() )and call the function load. Close the constructor function with a &quot; } &quot;</p>
<pre name="code" class="javascript">if(url) load(url);
}</pre>
<p>As the load function is public, it allows you to load xml anywhere outside or inside this class. First this function will remove all the menu items inside the container. If any exist, then it will start loading the xml document.</p>
<pre name="code" class="javascript">public function load(url:String):void{
  txt.text=&quot;Loading&quot;;
  _value=null;
  var total:int=container.numChildren;
  for(var i:int=0;i&lt;total;i++){ container.removeChildAt(0); }
  req.url=url;
  loader.load(req);
}</pre>
<p>This function will be called when the button is pressed. It will check if the alpha of the container is equal to zero. If so, it will set the visibility of the container to true, alpha to 0 and will smoothly set the alpha of the container to 1. If the alpha of the container is already more than 0, it will call for the close function.</p>
<pre name="code" class="javascript">private function open(e:MouseEvent):void{
	if(container.alpha==0){
		container.visible=true;
		container.alpha=0;
		new TweenLite(container,.5,{alpha:1});
	}
	else{ close(); }
}</pre>
<p>The close function will be called when you click anywhere, because we&#8217;ll add an event to the stage for when the mouse is down. This function will check if a container´s alpha is more than 0. If that&#8217;s the case it will smoothly set the container´s alpha to 0. When finished it will call the function hideContainer() that sets the container´s visibility to false (invisible and unclickable).</p>
<p>We&#8217;ll add an event to the stage, the MouseEvent.MOUSE_DOWN, so the function stageMouseDown.</p>
<pre name="code" class="javascript">private function close():void{
	if(container.alpha&gt;0) new TweenLite(container,.5,{alpha:0,onComplete:hideContainer});
}
private function hideContainer():void{ container.visible=false; }
private function stageMouseDown(e:MouseEvent):void{ this.close(); }
private function stageMouseLeave(e:Event):void{ this.close(); }</pre>
<p>loaderIOError will be called if the load function of the loader doesn&#8217;t find the xml document and will set the caption to &quot;XML not found&quot;.</p>
<p>The addedToStage will be called when this object is added to the stage display list. It will add an event for when you click anywhere on the stage to call the stageMouseDow function.</p>
<p>The removedFromStage will be called when this object is removed from the stage. It removes the event from stage so that clicks on stage will no longer call for the stageMouseDown function.</p>
<p>When the mouse leaves the stage, we&#8217;ll also close the drop down menu.</p>
<pre name="code" class="javascript">private function loaderIOError(e:IOErrorEvent):void{ txt.text=&quot;XML not found&quot;; }
private function addedToStage(e:Event):void{
	stage.addEventListener(MouseEvent.MOUSE_DOWN,stageMouseDown);
   stage.addEventListener(Event.MOUSE_LEAVE,stageMouseLeave);
}
private function removedFromStage(e:Event):void{
	stage.removeEventListener(MouseEvent.MOUSE_DOWN,stageMouseDown);
	stage.removeEventListener(Event.MOUSE_LEAVE,stageMouseLeave);
}</pre>
<p>The function loaderComplete is called when the xml is fully loaded, it will work like this:</p>
<ul>
<li>Set the default text of txt object to &quot;Select&quot; and the value to null, so we don&#8217;t have a value and the default caption is just &quot;Select&quot;</li>
<li>Create a new XML instance</li>
<li>Check the total number of nodes that have an &lt;item&gt; tag in the xml document and insert into the &quot;total&quot; variable.</li>
<li>Loop  the values of the xml document, getting their caption and value properties. The properties in xml are gotten by @property and the node value just .node without @.</li>
<li>Create a new MenuItem object with a menuItem instance, passing the caption and the value to the MenuItem constructor.</li>
<li>Add an event to the menuItem, when clicked it will call the function menuItemClick.</li>
<li>Add the menuItem just created to the container display list. </li>
<li>Set the position x of the container to the center of the DropDownMenu Object using some calculation.</li>
</ul>
<pre name="code" class="javascript">private function loaderComplete(e:Event):void{
	txt.text=&quot;Select&quot;;
	_value=null;
	var xml:XML=XML(e.target.data);
	var total:int=xml.item.length();
	var _w:int=this.width;
	var _h:int=this.height;
	for(var i=0;i&lt;total;i++){
		var caption:String=xml.item[i].@caption;
		var swf:String=xml.item[i].@value;
		var menuItem:MenuItem=new MenuItem(caption,swf,_w,_h);
		menuItem.addEventListener(MouseEvent.CLICK,menuItemClick);
		container.addChild(menuItem);
	}
	container.x=(this.width-container.width)*.5;
}</pre>
<p>The function menuItemClick will be called when you click any menu item object, the currentTarget parameter will get the object that was clicked.<br />
  We compare the actual value of DropDownMenu Object to the value of the clicked menu item and compare the current text of the txt textfield to the caption of the menu item. If there is any difference in the value, the function will dispatch a new DropDownMenuEvent passing the new caption and the new value.
</p>
<pre name="code" class="javascript">private function menuItemClick(e:MouseEvent):void{
	if(e.currentTarget.value!=_value &amp;&amp; e.currentTarget.caption!=txt.text){
		dispatchEvent(new DropDownMenuEvent(DropDownMenuEvent.CHANGE,e.currentTarget.caption,e.currentTarget.value));
		_value=e.currentTarget.value;
		txt.text=e.currentTarget.caption;
	}
}</pre>
<p>This is the function we have used to create the background and the hit state of the button. In the constructor function, this function returns a new Shape Object.</p>
<pre name="code" class="javascript">private function drawObject(_width:int,_height:int):Shape{
	var newShape=new Shape();
	var colours=[0xA6A6A6,0x515151];
	var alphas=[1,1];
	var ratios=[0,255];
	var radians:Number=90*(Math.PI/180);
	var matrix:Matrix=new Matrix();
	matrix.createGradientBox(_width,_height,radians);
	newShape.graphics.beginGradientFill(GradientType.LINEAR,colours,alphas,ratios,matrix);
	newShape.graphics.drawRoundRect(0,0,_width,_height,5,5);
	return newShape;
}</pre>
<p>We create 2 read-only properties, one to get the caption and other to get the value of this object. These 2 properties will be visible outside the class, but can&#8217;t be changed outside the class, only read.</p>
<p>Use 2x &quot; }&quot; to close the package and the class.</p>
<pre name="code" class="javascript">public function get caption():String{ return txt.text; }
public function get value():String{ return _value; }
}
}</pre>
<p>Now save this file as c:/myActionScripts/dropdownmenu/DropDownMenu.as. We have 3 files in the c:/myActionScripts/dropdownmenu:</p>
<ol>
<li>DropDownMenu.as</li>
<li>MenuItem.as</li>
<li>DropDownMenuEvent.as</li>
</ol>
<p>Now we have a dropdownmenu package with 3 classes.</p>
<h2>Step 7 &#8211; The .fla and the Document Class</h2>
<p>In Flash, go to File &gt; New.</p>
<p>Select Flash File (ActionScript 3.0) and click OK.</p>
<p>Then go to Window &gt; Properties. The properties panel will open</p>
<p>In the properties panel enter &quot;Main&quot; in the Class textbox (without the &quot; surround) and save your .fla file in c:/dropdownexample/dropdown.fla (remember that we already have the c:/dropdownexample folder with the xml folder inside.</p>
<h2>Step 8 &#8211; Coding the Main Document Class</h2>
<p>Create a new ActionScript file document (File &gt; New &gt; ActionScript file).</p>
<p>We&#8217;ll save the document in the same folder as the .fla document, with the name Main.as. This class belongs to the TopLevel package, so its package is just package&#8230;</p>
<p>We import the necessary classes. Notice that we import all the dropdownmenu package, so the three files created above (DropDownMenu, DropDownMenuEvent and MenuItem) will be imported to the Main class.</p>
<pre name="code" class="javascript">package{ 	import flash.display.Sprite; 	import dropdownmenu.*; 	import flash.events.*;	 	public class Main extends Sprite{</pre>
<p>Attention here, we&#8217;re creating 2 drop down menus; the first drop down menu will select a new xml document and make the second drop down menu load the value selected.</p>
<p>The first parameter, if not null, will automatically load the xml document when creating this object. The second parameter is the width of the drop down menu. We didn&#8217;t pass the third parameter; the height of the drop down menu, but we set the default value to 30, which I think it is a good height.</p>
<p>The first drop down menu will automatically load the xml called menu.xml in the folder xml, the second will load an xml file only when we use the load function.</p>
<pre name="code" class="javascript">private var d1:DropDownMenu=new DropDownMenu(&quot;xml/menu.xml&quot;,150); private var d2:DropDownMenu=new DropDownMenu(null,150);</pre>
<p>We create the constructor. As this class is the document class, the function will be called when we compile the .swf and every time we open the .swf file too. We add the two drop down menus we´ve created, set the x position of both, then set the same y value to them.  Add event listeners to both drop down menus, when we change the value we&#8217;ll call for the listeners.
</p>
<pre name="code" class="javascript">public function Main():void{ 	addChild(d1); 	addChild(d2); 	d1.x=50; 	d2.x=210; 	d1.y=d2.y=40;			 	d1.addEventListener(DropDownMenuEvent.CHANGE,d1Change); 	d2.addEventListener(DropDownMenuEvent.CHANGE,d2Change); }</pre>
<p>This is the listener of drop down menu 1. When the d1 value changes, it will load its value in d2 drop down menu.</p>
<pre name="code" class="javascript">private function d1Change(e:DropDownMenuEvent):void{ 	d2.load(e.value); }</pre>
<p>This is just to test the second drop down menu, but you can get the drop down menu´s values by getting instance.value and get the drop down menu´s captions by getting instance.caption.</p>
<pre name="code" class="javascript">private function d2Change(e:DropDownMenuEvent):void{ 	trace(e.caption+&quot; = &quot;+e.value);
   //or trace(d2.caption+&quot; = &quot;+e.value); }</pre>
<p>Close the package and the class with 2x &quot; } &quot;</p>
<pre name="code" class="javascript">}
}</pre>
<p>Now we have the Main class to test our work, just save in c:/dropdowexample/Main.as and compile the dropdown.fla document. Test it in flash so the trace will work.</p>
<p>The captions and the values can, of course, be anything you like.</p>
<h2>Conclusion</h2>
<p>The classes are a little bit big, but they&#8217;re correctly coded, don&#8217;t have bugs and you can use them whenever you want by just importing the dropdownmenu package and creating DropDownMenu objects. Classes and the Document class are the biggest difference between ActionScript 2.0 and 3.0. Anybody that learns how to work with ActionScript files and learns how to use the classpath will find it far better than using the timeline to code.</p>
<p>Thats all for now!</p>
]]></content:encoded>
			<wfw:commentRss>http://active.tutsplus.com/tutorials/xml/develop-an-oop-drop-down-menu-using-actionscript-30-documents/feed/</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.660 seconds -->
