Archive for the ‘Tutorial’ Category

How to add a webpage fade-in effect using JQuery

Friday, August 28th, 2009

THE PROBLEM: HTML pages that have numerous and complex nested <div> tags and CSS can sometimes have a jumbled “assembling” appearance that happens as the page is loading and the various elements are being rendered by the browser. The appearance of this process can look quite unrefined and detract from professional appearance of the site.

A SOLUTION: JQuery includes a function to fade-in a hidden tag. If the content of the page is initially hidden using CSS, it then can be faded-in using JQuery once the whole page has been processed and is ready for display.

Step 1

Inside the page’s <body> tag, enclose the content in a <div> tag with a unique CSS id (see this post for the difference between CSS ids and classes).

<body>
 
<div id="content-wrapper">
 
The page content goes here!
 
</div><!-- content-wrapper -->
 
</body>

Step 2

Inside the page’s <head> tag, import the JQuery library (download it here) and create a fade-in effect on the <div> tag surrounding the page’s content. Key to this solution is that the effect gets placed inside JQuery’s $(document).ready() function, ensuring the fade begins after the document’s DOM has been completely parsed.

<script type="text/javascript" src="jquery.min.js"></script>
 
<script type="text/javascript">
$(document).ready(function() 
{
		// fade in content.
		$( '#content-wrapper' ).fadeIn("slow");		
});
</script>

Step 3

At this point the fade-in effect will not occur, because the content is not hidden to begin with. To correct this add some CSS styling underneath the JavaScript above to hide the page content initially.

<style type="text/css">
 
#content-wrapper
{
	display:none;	
}
 
</style>

Step 4

Now the fade-in effect will work, however, a problem exists. If someone visits the page and has JavaScript turned off in their browser, the CSS to hide the content will be applied, but the JQuery to fade it back into visibility will not run, leaving the page effectively blank. This is a serious accessibility issue. To correct this, instead of hardcoding the <div> tag that is wrapping the content, write the tag using JavaScript. That way if JavaScript is turned off, the tag will not be rendered and won’t hide its containing content. Change what was written in Step 1 to the following:

<body>
 
<script type="text/javascript">
<!--//--><![CDATA[//><!--
document.write( '<div id="content-wrapper">' );
//--><!]]>
</script>
 
The page content goes here!
 
<script type="text/javascript">
<!--//--><![CDATA[//><!--
document.write( '</div><!-- content-wrapper -->' );
//--><!]]>
</script>
 
</body>

Putting it all together you end up with this (remember to include the JQuery library in the same folder as this HTML page):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Fade-in effect example</title>
 
<script type="text/javascript" src="jquery.min.js"></script>
 
<script type="text/javascript">
$(document).ready(function() 
{
		// fade in content.
		$( '#content-wrapper' ).fadeIn("slow");		
});
</script>
 
<style type="text/css">
 
#content-wrapper
{
	display:none;	
}
 
</style>
 
</head>
 
<body>
 
<script type="text/javascript">
<!--//--><![CDATA[//><!--
document.write( '<div id="content-wrapper">' );
//--><!]]>
</script>
 
The page content goes here!
 
<script type="text/javascript">
<!--//--><![CDATA[//><!--
document.write( '</div><!-- content-wrapper -->' );
//--><!]]>
</script>
 
</body>
</html>

How to build an Object-Oriented ActionScript 3 Preloader in Flash CS4: 2 Methods

Saturday, June 20th, 2009

The magic of creating a preloader in ActionScript 3 lies in the LoaderInfo class. Every instantiated DisplayObject instance (all objects that appear on the stage, plus the stage itself) have a loaderInfo property that returns a LoaderInfo instance that contains information about the loading progress of that particular display object. Creating a preloader for the whole application is a matter of monitoring these LoaderInfo instances.

Method 1: Monitor Stage LoaderInfo instance

Under this method the loading progress is monitored via the LoaderInfo instance associated with the stage. Since all assets that will appear in the application need to be attached to the stage, the stage’s LoaderInfo instance will reflect the loading of all these assets.

Graphics

  1. Go to File → New… and select Flash File (ActionScript 3.0).
  2. Using the Rectangle tool create a rectangle (include a stroke) on the stage that is 100 pixels wide by 10 pixels high.
  3. Click on the fill of the newly created rectangle and select Modify → Convert to Symbol… Name the new instance ProgBar and set the registration point to left-middle. This will be the progress bar of the preloader.

    preloader_pbar

  4. With the new ProgBar instance selected on the stage, go to the Properties panel and name the instance progBar.
  5. Select the whole rectangle (stroke and progress bar instance). Select Modify → Convert to Symbol… Name the new instance Preloader and set the registration point to left-middle. Check the Export for ActionScript button.
  6. Click OK. If you get a warning that says the “definition for this class could not be found” click OK again.
  7. With the new Preloader instance selected, go to the Properties panel and name the newly created instance preloader. Your library should look like the following:

    preloader_library

  8. Select frame 2 of the main timeline, go to Insert → Timeline → Blank Keyframe. All content for the application will appear on frame 2 and beyond.
  9. Go to Insert → New Symbol… Name the new instance Content. If you check Export for ActionScript be sure to uncheck Export in frame 1, otherwise the preloader will not function properly.
  10. Place all content of the application on the timeline of the newly created Content instance.
  11. Return to the main timeline. Select frame 2 and drag an instance of the Content symbol from the library and place it on the stage.
  12. In the Properties panel of the stage name the document class Main. If you get a warning that says the “definition for this class could not be found” click OK.

    preloader_docclass

  13. Save the file.

Code

  1. Go to File → New… and select ActionScript File.
  2. Paste the following code and save the file as Preloader.as in the same directory as the .fla file saved earlier.
    package
    {
    	import flash.display.Sprite;
    	import flash.display.LoaderInfo;
    	import flash.events.Event;
     
    	public class Preloader extends Sprite
    	{
    		/**
    		* Alias for stage LoaderInfo instance
    		*/
    		private var _targetLoaderInfo:LoaderInfo;
     
    		/**
    		* The percent loaded
    		*/
    		private var _loadPercent:Number = 0;
     
    		/**
    		* Constructor
    		* Listen for when the preloader has been added to the stage 
    		* so that the progress of the remaining load can be monitored.
    		*/
    		public function Preloader()
    		{
    			this.addEventListener( Event.ADDED_TO_STAGE , _init );
    		}
     
    		/**
    		* Initialize variables.
    		* Set initial width of the progress bar to 0 
    		* and listen for enter frame event.
    		*/
    		private function _init(evt:Event):void
    		{
    			_targetLoaderInfo = stage.loaderInfo;
     
    			progBar.scaleX = 0;
     
    			this.removeEventListener( Event.ADDED_TO_STAGE , _init );
    			this.addEventListener(Event.ENTER_FRAME, _onCheckLoaded);
    		}
     
    		/**
    		* Check the status of the load, once complete dispatch a complete event.
    		*/
    		private function _onCheckLoaded(evt:Event):void 
    		{
    			_loadPercent = _targetLoaderInfo.bytesLoaded / _targetLoaderInfo.bytesTotal;
    			progBar.scaleX = _loadPercent;
    			if (progBar.scaleX == 1)
    			{
    				this.removeEventListener(Event.ENTER_FRAME, _onCheckLoaded);
    				this.dispatchEvent( new Event(Event.COMPLETE) );
    			}
    		}
    	}	
    }
  3. Go to File → New… and select ActionScript File a second time.
  4. Paste the following code and save the file as Main.as in the same directory as the .fla file saved earlier.
    package 
    {
    	import flash.display.MovieClip;
    	import flash.events.Event;
     
    	public class Main extends MovieClip 
    	{
    		/**
    		* Constructor
    		* Stop timeline and add event listener to preloader.
    		*/
    		public function Main() 
    		{
    			this.stop();
    			preloader.addEventListener( Event.COMPLETE , _initContent );
    		}
     
    		/**
    		* Load has finished, remove preloader and preceed to next frame.
    		*/
    		private function _initContent(evt:Event):void 
    		{
    			preloader.removeEventListener( Event.COMPLETE , _initContent );
    			this.removeChild(preloader);
    			nextFrame();
    		}
    	}
    }
  5. To test the preloader go to Control → Test Movie. Go to View → Simulate Download.
  6. Download method 1 complete source

Method 2: Monitor content SWF LoaderInfo instance

Under this method two SWFs are created, one encapsulating the preloader and the other encapsulating all content. The content SWF is loaded inside of the preloader SWF, which monitors the loading progress.

Graphics

  1. Follow steps 1 – 7 in the previous method.
  2. In the Properties panel of the stage name the document class PreloaderWrapper. If you get a warning that says the “definition for this class could not be found” click OK.
  3. Save the file.
  4. Go to File → New… and select Flash File (ActionScript 3.0).
  5. Add the content for your application to the timeline of this file.
  6. Save the file as content.fla.
  7. Go to Control → Test Movie to create the content.swf that will be loaded by the preloader SWF.

Code

  1. Go to File → New… and select ActionScript File.
  2. Paste the following code and save the file as PreloaderWrapper.as in the same directory as the .fla file saved earlier.
    package 
    {
    	import flash.display.Sprite;
    	import flash.display.Loader;
    	import flash.display.LoaderInfo;
    	import flash.display.DisplayObject;
    	import flash.events.Event;
    	import flash.events.ProgressEvent;
    	import flash.net.URLRequest;
     
    	public class PreloaderWrapper extends Sprite 
    	{
    		/**
    		* Alias for content LoaderInfo instance
    		*/
    		private var _targetLoaderInfo:LoaderInfo;
     
    		/**
    		* The percent loaded
    		*/
    		private var _loadPercent:Number = 0;
     
    		/**
    		* Constructor
    		* Creates Loader instance, adds event listeners and begins loading content SWF.
    		*/
    		public function PreloaderWrapper() 
    		{
    			var loader:Loader = new Loader();
    			_targetLoaderInfo = loader.contentLoaderInfo;
    			_targetLoaderInfo.addEventListener( ProgressEvent.PROGRESS, _loadingData );
    			_targetLoaderInfo.addEventListener( Event.COMPLETE , _finishedLoading );
    			loader.load( new URLRequest("content.swf") );
     
    		}
     
    		/**
    		* Monitor loading progress and update progress bar.
    		*/
    		private function _loadingData( evt:ProgressEvent ):void 
    		{
    			_loadPercent = _targetLoaderInfo.bytesLoaded / _targetLoaderInfo.bytesTotal;
    			preloader.progBar.scaleX = _loadPercent;	
    		}
     
    		/**
    		* Remove event listeners and preloader, and attach content SWF to stage.
    		*/
    		private function _finishedLoading( evt:Event ):void 
    		{
    			_targetLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, _loadingData );
    			_targetLoaderInfo.removeEventListener( Event.COMPLETE , _finishedLoading );
    			this.removeChild(preloader);
    			this.addChild( DisplayObject(LoaderInfo(evt.target).content) );
    		}
    	}
    }
  3. To test the preloader go to Control → Test Movie. Go to View → Simulate Download.
  4. Download method 2 complete source

UPDATE July 30, 2009: I noticed I forgot the private designation on two of the methods in the PreloaderWrapper class. They have been added.

Curious about Adobe Open Source? Get started with the Flex SDK on Mac OS X

Tuesday, January 6th, 2009

How about creating a SWF that runs in the Adobe Flash Player without building it in the Flash or Flex Builder authoring environment, using tools that are free and open source? Ever since Adobe made the move from ActionScript 2.0 to 3.0 there has been a gem of a toolkit available that allows precisely that. The Flex SDK (Software Development Kit) allows developers to create SWFs from ActionScript and MXML source code, and with the right setup is not difficult to configure and use.

Housed at Adobe Open Source, the Flex SDK is available in two incarnations through the site:

  • The Open Source Flex SDK containing everything needed to create a functional application using ActionScript and/or MXML and the Flex framework.
  • The Free Adobe Flex 3 SDK containing everything in the Open Source Flex SDK plus additional components such as advanced font encoders, tools for packaging Adobe AIR applications, and the Adobe Flash Player.
  • How to use the Flex SDK

    I have developed an Apache Ant build script that makes—after some configuration—the Flex SDK quite easy to use on Mac OS X. Here’s how to configure it:

    1. Download the latest Flex SDK from Adobe Open Source. Rename the SDK folder flex_sdk_3 and place it in /Applications/ on your hard drive.
    2. Locate Apache Ant on your system. Ant will already be installed if you have installed the Mac OS X Developer Tools (which are an optional install included with every version of OS X) or are running Leopard.

      Open Terminal and type:

      whereis ant

      It should say something like

      /usr/bin/ant

      If Ant is not installed, no path will be shown in Terminal. To install Ant I recommend using MacPorts, an excellent open source utility for managing unix tools on Mac OS X (follow these well written directions for installation). If you are not comfortable using the Terminal, there is a GUI available for MacPorts called Porticus.

    3. Copy the Flex Ant tasks to your Ant installation’s library. These will allow Ant to communicate with the major Flex SDK tools. To copy the tasks, first locate the Ant lib directory, which will be in Ant’s main installation folder. For example on Mac OS X 10.5 it appears at usr/share/ant/lib. Copy /Applications/flex_sdk_3/ant/lib/flexTasks.jar into this directory.
    4. If you are an advanced user and would like to utilize Unit Testing using FlexUnit, Download the FlexUnit Ant Tasks. Place these in the Ant installation’s library folder as well.

      (Note: The project template you will download from my site in the next step includes two SWCs for use with unit testing. For those that may be curious where these came from, here are the links to the original locations: FlexUnit SWC library and FlexUnit Optional SWC library)

    5. Download the Flex SDK example application template from my site. Unzip the archive and place the FlexSDKProjectTemplate folder on your desktop. Open the folder.
    6. Make a copy of build.properties.template and rename it build.properties.
    7. Open the build.properties file you just created and edit the REQUIRED TOOL LOCATIONS section to reflect the path to the Flex SDK, your preferred web browser, and the location of the Flash Player (which you will need to download if you have not already done so).
    8. Using Terminal navigate to the example application template. For example:
      cd Desktop/FlexSDKProjectTemplate/

      And then type the following:

      ant run

      The sample application will launch, typing ant usage will show you what other options are available, such as creating documentation, SWCs, or launching the application in a web browser.

    9. Lastly, to enable the trace() method so that it will work from your code when using the Flash debug player, create a textfile called mm.cfg and fill it with the following:

      TraceOutPutFileName=flashlog.txt
      ErrorReportingEnable=1
      TraceOutputFileEnable=1
      MaxWarnings=0

      Place this file at
      /Library/Application Support/Macromedia/mm.cfg
      . Whenever you have a trace("some text"); statement in your code, it will be written to:

      /Users/[your username]/Library/Preferences/Macromedia/Flash Player/Logs/flashlog.txt

    Please leave comments with any suggestions, problems, questions, etc. Enjoy!

    Troubleshooting

    Problem: Running ASDoc produces: Execute failed: java.io.IOException: /Applications/flex_sdk_3/bin/asdoc: cannot execute

    Solution: This mostly likely means the ASDoc script Ant uses is not set to be executable. Type the following in Terminal:

    cd /Applications/flex_sdk_3/bin/
    chmod +x asdoc

    The first line changes the directory to the one ASDoc resides in. The second line makes ASDoc executable.

    Problem: Running ASDoc produces: exec returned: 255

    Solution: This mostly likely means the ASDoc script (which is just a text file) contains Window-style line endings. These will need to be converted to linux.

    Install dos2unix using MacPorts and type the following in Terminal:

    cd /Applications/flex_sdk_3/bin/
    dos2unix asdoc

    This will turn off the executable bit in the permission tables, so you will have to re-enable that using the instructions in the first solution above.

    Problem: Running ASDoc produces: Could not create toplevel.xml: /Applications/flex_sdk_3/asdoc/templates/asDocHelper: cannot execute

    Solution: This mostly likely means that a helper script used by ASDoc is not set to be executable. Type the following in Terminal:

    cd /Applications/flex_sdk_3/asdoc/templates/
    chmod +x asDocHelper