ActionScript 3 Accordion Content Menu

ActionScript 3 Vertical & Horizontal Accordion Menu

This example extends and supersedes an earlier version of this file I wrote about a year ago. I always wanted to make a horizontal version and extend the class, making it more flexible and useful to people.

As was the previous menu, this menu is a Class based ActionScript 3 Accordion Menu, with either a rollOver/RollOff activation scheme for a onRelease activation scheme. I also added in a better extended event class which allows you to control, or respond to all menu activity via events.

Class Features

  • Vertical or Horizontal Menu Orientation
  • Visible or invisible Menu Bar
  • Supports parsing functions passed to each menu item
  • Control
  • Menu Spacing
  • MenuBar colour / RollOver/Off colour
  • Menu text format
  • Menu tween speed
  • Menu easing type
  • MenuBar width, height, visibility
  • Menu Click behaviour
  • Disable / Enable Menu
  • Open Particular Panels
  • etc, etc.
  • Menu attributes are applicable on a per menu item basis

The only thing I have left to add is support for passing in custom menuBar assets. Thats if people would like that to be added?

View Example
http://noponies.com/dev/as3_accordion/

Source Files
http://www.blog.noponies.com/wp-content/uploads/npaccordion.zip

Dependencies
TweenLite - http://www.tweenlite.com

Class ActionScript

/* AS3
* Copyright 2008 noponies.
*/


package noponies.ui{
  import flash.display.Sprite;
  import flash.display.DisplayObject;
  import flash.display.Shape;
  import flash.display.Stage;
  import flash.events.MouseEvent;
  import flash.events.Event;
  import flash.text.TextField;
  import flash.text.TextFieldAutoSize;
  import flash.text.TextFieldType;
  import flash.text.TextFormat;
  import flash.text.AntiAliasType;
  import fl.motion.easing.*;
  //non internal imports
  import gs.TweenLite;
  import noponies.ui.events.NpAccordionEvent;
  import noponies.ui.NpAccordionPaneV;
  import noponies.ui.NpAccordionPaneH;
 
    /**
    *   <strong>NpAccordion</strong>
    *   <p>This menu system was written as a means to display content in a condensed manner. Menus can be either vertical or horizontal. Supports mulitple columns.</p>
    *   <p>Simple XML based accordion menu. Menu acts as a content space minimiser, with content hidden behind menu bar items. Content
    * slides into view when the menu item is clicked on. However, you can pass it any display objects, derived how you like. </p>
    * <p>Menu supports parsing function calls passed as a string value , along with parameter support for these functions. This is useful for perhaps
    * calling a function on the parent timeline of the menu. Menu also supports a standard URL call passed to it.</p>
    * <p>Menu supports any DisplayObject. Loaded swfs can contain their own interactivity. </p>
    * <p>Menu supports using either the whole menu or just the menu bar as the mechansim for sliding the menu up and down. Generally it is better to only use
    * the bar if you want to include interactivity in the menu items.</p>
    * <p>Positioning menu:To create a column, or otherwise change menu item positions, set either the menuPosX or menuPosY values, like so, menuInstanceVarName.menuPosX = newValue</p>
    * <p>Menu supports custom events, so that individual menu instances can be targetted. Doing so relies on the <code>NpAccordionEvent</code> Class, which allows for the passing
    * of parameters to each menu item. This param is checked against the ID var of each menu, if they match, then the menu acts on the event.</p>
    * <p>Class requires TweenLite <a href="http://blog.greensock.com/tweenliteas3" target="_blank">http://blog.greensock.com/tweenliteas3</a><p>
    * <b>Author:</b> noponies - <a href="http://www.blog.noponies.com/" target="_blank">www.blog.noponies.com</a><br />
    *   <b>Class version:</b> 1<br />
    *   <b>Actionscript version:</b> 3.0 Player Version 9.0.28<br />
    *   <b>Copyright:</b>
    *   Creative Commons AttCreative Commons Attribution 3.0 New Zealand License<br />
    *   <a href="http://creativecommons.org/licenses/by/3.0/nz/" target="_blank">http://creativecommons.org/licenses/by/3.0/nz/</a><br />
    *   You can use this class how you like, except as a base for Flash Components or for Flash Template sites.<br />
    *   <br />
    *   <b>Date:</b> 17 July 2008<br />
    */


  public class NpAccordion extends Sprite {
   
    private var menuOrientation:String = "horizontal"
    private var clickMode:Boolean = true
    private var counter:int
    private var menuItems:Array
    private var menuPosY:int = 0;
    private var menuPosX:int = 0;
   
    private var menuPadding:int = 5;//space between menu items
    private var barHeight:int = 10//default
    private var barWidth:int = 10
    private var menuTxtFormat:TextFormat
    private var menuEnabled:Boolean =true//defaut, is the menu as a whole disable from mouse interactivity
    private var speed:Number = .5;//menu transition speed - in seconds
    private var useWholeMenu:Boolean = false;//default
    private var menuColour:uint = 0x000000;//menu bars colour
    private var menuAlpha:Number = 1//default
    private var useHighLighting:Boolean = true;//change colours of bar on rollOver?
    private var menuHighlightColour:int = 0xCCCCCC;//menu rollover colour
    private var easeType:Function = fl.motion.easing.Linear.easeNone //default ease type
   
    //action handling
    private var contentHasAction:Boolean = true//default
    private var contentActionScope:Object //scope that actions run within when applying actions internally
    private var handleActionsExternally:Boolean = true//default

   
    /**
     *  Get / Set whether or not to change the colour of the menu bar with a rollOver. A value of <code>true</code> enables this feature.
     *  @param Boolean
     *  @default true
     *  @return Boolean
     */

    public function get setMenuX():int {
      return menuPosX;
    }
    /**
    * @private
    */

    public function set setMenuX(newMenuPosX:int):void {
      menuPosX = newMenuPosX;
    }
    /**
     *  Get / Set whether or not to change the colour of the menu bar with a rollOver. A value of <code>true</code> enables this feature.
     *  @param Boolean
     *  @default true
     *  @return Boolean
     */

    public function get setMenuY():int {
      return menuPosY;
    }
    /**
    * @private
    */

    public function set setMenuY(newMenuPosY:int):void {
      menuPosY = newMenuPosY;
    }
    /**
     *  Get / Set the padding between each menu item.
     *  @param int
     *  @default 5
     *  @return int
     */

    public function get menuSpacing():int {
      return menuPadding;
    }
    /**
    * @private
    */

    public function set menuSpacing(newMenuPadding:int):void {
      menuPadding = newMenuPadding;
    }  
    /**
     *  Get / Set if the menus respond to interactivity. Use this property when loading a menu set and you want to disable a user clicking on menu items until all
     *  content has loaded, or some other event occurs. If you set this property, dispatch a <code>NpAccordionEvent.ENABLE_MENU</code> event to enable menu interactivity globally.
     *  @param Boolean
     *  @default true
     *  @return Boolean
     *  @see noponies.accordion.events.NpAccordionEvent#DISABLE_MENU
     *  @see noponies.accordion.events.NpAccordionEvent#ENABLE_MENU
     */

    public function get menusEnabled():Boolean {
      return menuEnabled;
    }
    /**
    * @private
    */

    public function set menusEnabled( newMenuEnabled:Boolean):void {
      menuEnabled = newMenuEnabled;
    }
    /**
     *  Get / Set whether or not to change the colour of the menu bar with a rollOver. A value of <code>true</code> enables this feature.
     *  @param Boolean
     *  @default true
     *  @return Boolean
     */

    public function get highLightMenuBar():Boolean {
      return useHighLighting;
    }
    /**
    * @private
    */

    public function set highLightMenuBar(newHigh:Boolean):void {
      useHighLighting = newHigh;
    }
    /**
     *  Get / Set the colour to use when you have enabled the <code>highLightMenu<code> property.
     *  @param uint
     *  @default 0xCCCCCC (light grey)
     *  @return uint
     */

    public function get highLightColour():uint {
      return menuHighlightColour;
    }
    /**
    * @private
    */

    public function set highLightColour(newCol:uint):void {
      menuHighlightColour = newCol;
    }
    /**
     *  Get / Set the tween speed of the menus opening and closing.
     *  @param Number representing the speed in seconds for menu opening and closing tweens.
     *  @default .5
     *  @return Number
     */

    public function get tweenSpeed():Number {
      return speed;
    }
    /**
    * @private
    */

    public function set tweenSpeed(newSpeed:Number):void {
      speed = newSpeed;
    }
    /**
     *  Get / Set the height of the menu bar in pixels.
      * <p>The impact of this setting depends on how you are displaying your menus. If you have chosen to display a <em>horizontal</em> (menu slides across x axis)
     *  menu, then this setting controls how far across the side of your content the menuBar displays.
     *  If you want it to match the height of your content, set it to <code>0</code>. If you are displaying your menu as a  <em>vertical</em> menu, then this setting controls the visible height
     *  of the menuBar. Setting the menuBarAlpha to <code>0</code> will make your menuBar invisible.
     *  @param int
     *  @default 10
     *  @return int
     *  @see #menuBarAlpha
     *  @see #menuBarWidth
     */

    public function get menuBarHeight():int {
      return barHeight;
    }
    /**
    * @private
    */

   
    public function set menuBarHeight(newBarHeight:int):void {
      barHeight = newBarHeight;
    }
    /**
     *  Get / Set the width of the menu bar in pixels.
     *  <p>The impact of this setting depends on how you are displaying your menus. If you have chosen to display a <em>horizontal</em> (menu slides across x axis)
     *  menu, then this setting controls the visible width of the menuBar. If you are displaying your menu as a  <em>vertical</em> menu, then this setting
     *  controls how far across the top of your content the menuBar displays. If you want it to match the width of your content, set it to <code>0</code>.
     *  Setting the menuBarAlpha to <code>0</code> will make your menuBar invisible.
     *  @param int
     *  @default 10
     *  @return int
     *  @see #menuBarHeight
     *  @see #menuBarAlpha
     */

    public function get menuBarWidth():int {
      return barWidth;
    }
    /**
    * @private
    */

    public function set menuBarWidth(newBarWidth:int):void {
      barWidth = newBarWidth;
    }
    /**
     *  Get / Set the colour of the menu bar.
     *  @param uint
     *  @default 0x000000 (black)
     *  @return uint
     */

    public function get menuBarColour():uint {
      return menuColour;
    }
    /**
    * @private
    */

    public function set menuBarColour(newMenuColour:uint):void {
      menuColour = newMenuColour;
    }
    /**
     *  Get / Set the alpha levels of the menu bar.
     *  <p>A technique you can employ here is to set the menu bars alpha to 0, so that your content will be visible. You may also wish to adjust the <code>menuBarHeight</code> property, as this will
     *  control how much of your content is visible.</p>
     *  @param Number
     *  @default 1
     *  @return Number
     *  @see #menuBarWidth
     *  @see #menuBarHeight
     */

    public function get menuBarAlpha():Number {
      return menuAlpha;
    }
    /**
    * @private
    */

    public function set menuBarAlpha(newMenuAlpha:Number):void {
      menuAlpha = newMenuAlpha;
    }
   
    /**
     *  Get / Set how a the menu item and menu content respond to clicks. A value of <code>false</code> enables mouseEvent.CLICK interactivity on the menu bar alone. This is the setting you would use if your content
     *  itself had interactivity. A value of <code>true</code> enables mouseEvent.CLICK interactivity on the entire menu item.
     *  @param Boolean
     *  @default false
     *  @return Boolean
     */

    public function get globalMenuClick():Boolean {
      return useWholeMenu;
    }
    /**
    * @private
    */

    public function set globalMenuClick(newUseWholeMenu:Boolean):void {
      useWholeMenu = newUseWholeMenu;
    }
    /**
     *  Get / Set how a the menu will handle any actions passed to it. A value of <code>true</code> will dispatch all actions via the <code>NpAccordionEvent.PRESS</code> event. You can access this events
     *  <code>menuAction</code> property to parse what action the menu item contained. This property is sent in String form. A value of <code>false</code> will make the menu run the actions internally.
     *  @param Boolean
     *  @default true
     *  @return Boolean
     *  @see #actionScope
     */

    public function get delegateActions():Boolean {
      return handleActionsExternally;
    }
    /**
    * @private
    */

    public function set delegateActions(newDispatchMenuActions:Boolean):void {
      handleActionsExternally = newDispatchMenuActions;
    }
    /**
     *  Change the way actions are fired off a menu item. Setting this value to <code>true</code> will make the contentItem itself, rather than the menu bar fire any actions you may have set.
     *  A value of <code>false</code> will make menu actions fire from a CLICK on the menu bar. This means that a user has to first click on the bar to open the menu item, then click on any content it may have.
     *  @param Boolean
     *  @default true
     *  @return Boolean
     *  @see #actionScope
     *  @see #delegateActions
     */

    public function get contentActions():Boolean {
      return contentHasAction;
    }
    /**
    * @private
    */

    public function set contentActions(newContentAction:Boolean):void {
      contentHasAction = newContentAction;
    }
    /**
     *  Set the scope that internally applied actions run within. By default this is set to the parent object of each menu item. Set this property of you want actions to run internally in another scope.
     *  @param Object
     *  @default menuItem.parent
     *  @return Object
     *  @see #delegateActions
     */

    public function get actionScope():Object {
      return contentActionScope;
    }
    /**
    * @private
    */

    public function set actionScope(newActionScope:Object):void {
      contentActionScope = newActionScope;
    }
    /**
     *  Set the textformat that the menu items will use for their text display. If you do not pass in a TextFormat Object the class defaults to using 10 pt, white _sans for any menu text. By default the menu
     *  textField is set to use embedded fonts. This setting affects the defaultTextFormat property of the menus textField. So, once this is set, future text assignments will inherit that text format.
     *  @param Textformat
     *  @default null
     *  @return
     */

    public function set menuTextFormat(newFormat:TextFormat):void {
      menuTxtFormat = newFormat;
    }
    /**
     *  Set the ease type that the menus use when moving. This parameter is in the form of a <code>fl.motion.easing.Elastic.easeInOut</code>. The default is a <code>fl.motion.easing.Linear.easeNone</code>, or no easing.
     *  @param Function
     *  @default fl.motion.easing.Linear.easeNone
     *  @return
     */

    public function set menuEaseType(newEaseType:Function):void {
      easeType = newEaseType;
    }
    /**
     *  Get the current menu items as an array of Class Objects representing each menu item created by this Class.
     *  @return Array
     */

    public function get currentMenuArray():Array {
      return menuItems
    }
   
    //--------------------------------------
    // CONSTRUCTOR
    //--------------------------------------
    /**
     *  Please review the various Getter / Setter Methods for controlling the look, feel and behaviour of the Accordion Menu.
     *  <p>To control the properties of individual menu items, set the menu items properties before you call the <code>addPanel()</code> method!</p>
     *  <p>Make sure you pay attention to the <code>menuBarHeight</code> and the <code>menuBarWidth</code> properties when switching between vertical or horizontally displaying menus.</p>
     *  <p>Should you need access to the current active menu items ID, or its menuBar Sprite or menuBar textField please review the various events and event parameters that allow for this access</p>
     *  @param mouseMode String. <strong>Optional (Default: click)</strong> Controls the click or rollOver action of the menu. A value of <code>click</code> makes the menu open in response to Mouse Clicks. A value of <code>rollover</code> makes the menu open and close in reponse to
     *  a user rolling over and off individual menu items.
     *  @param menuOrientation String. <strong>Optional (Default: vertical)</strong> String representing the click action of the menu item. This can be either a http URL or a function with parameters. In this format <code>Function Name, param, param</code>
     *  @see #globalMenuClick
     *  @see #menusEnabled
     *  @see #menuColour
     *  @see #menuBarAlpha
     *  @see #menuBarHeight
     *  @see #menuBarWidth
     *  @see #menuSpacing
     *  @see #tweenSpeed
     *  @see #actionScope
     *  @see #delegateActions
     *  @see #contentActions
     *  @see #menuTextFormat
     *  @see #menuEaseType
     */

    public function NpAccordion(mouseMode:String ="click", menuOrientation:String ="vertical") {
      //validate menu mode
      switch (mouseMode) {
        case "click" :
          clickMode = true
          break;
        case  "rollover" :
          clickMode = false
          break
        default:
          throw new Error("Problem :The mouseMode parameter passed is incorrect. It must be either 'click' or 'rollover'!"+ " You passed '"+mouseMode+"'");
      }
      //validate menuOrientation
      switch (menuOrientation) {
        case "horizontal" :
          this.menuOrientation = menuOrientation
          break;
        case  "vertical" :
          this.menuOrientation = menuOrientation
          break
        default:
          throw new Error("Problem :The menuOrientation parameter passed is incorrect. It must be either 'horizontal' or 'vertical'!"+ " You passed '"+menuOrientation+"'");
      }
      menuItems = []
      addEventListener(Event.REMOVED_FROM_STAGE, handleStageRemoval)
    }
    //--------------------------------------
    // ADDPANEL METHOD - ADD A MENU PANEL TO THE ACCORDION MENU
    //-------------------------------------- 
    /**
     *  The addPanel Method adds an accordion panel (via an instance of the NpAccordionPane Class) to an instance of the NpAccordion Class.
     *  <p>To control the properties of individual menu items, set the menu items properties before you call the <code>addPanel()</code> method!</p>
     *  @param loadedContent DisplayObject. The content you want to place within an NpAccordion Menu item.
     *  @param titleText String. <strong>Optional</strong> String representing the text of the menu bar.
     *  @param action String. <strong>Optional</strong> String representing the click action of the menu item. This can be either a http URL or a function with parameters. In this format <code>Function Name, param, param</code>
     *  @see #globalMenuClick
     *  @see #menusEnabled
     *  @see #menuColour
     *  @see #menuBarAlpha
     *  @see #menuBarHeight
     *  @see #menuBarWidth
     *  @see #menuSpacing
     *  @see #tweenSpeed
     *  @see #actionScope
     *  @see #delegateActions
     *  @see #contentActions
     *  @see #menuTextFormat
     *  @see #menuEaseType
     */

    public function addPanel(loadedContent:DisplayObject, titleText:String="", action:String=""):void {

      var ClassSwitch:Class
      if(menuOrientation=="vertical"){
        ClassSwitch = NpAccordionPaneV
      }else{
        ClassSwitch = NpAccordionPaneH
      }
      var menuItem:Object = new ClassSwitch(loadedContent, counter, titleText, action);

      //set menu properties before it draws itself to stage
      menuItem._clickMode = clickMode
      menuItem.x = menuPosX
      menuItem.y = menuPosY
      menuItem._barHeight = barHeight
      menuItem._barWidth = barWidth
      menuItem._menuTxtFormat = menuTxtFormat
      menuItem._menuEnabled = menuEnabled
      menuItem._speed = speed
      menuItem._useWholeMenu = useWholeMenu
      menuItem._menuColour = menuColour
      menuItem._menuAlpha = menuAlpha
      menuItem._useHighLighting = useHighLighting
      menuItem._menuHighlightColour = menuHighlightColour
      menuItem._easeType = easeType
      //action handling
      menuItem._contentHasAction = contentHasAction
      menuItem._contentActionScope = contentActionScope
      menuItem._handleActionsExternally = handleActionsExternally
     
      if(menuOrientation=="vertical"){
        menuPosY += (barHeight+menuPadding);//positioning of menu, vertically = barheight + menu padding
      }else{
        menuPosX += (barWidth+menuPadding);//positioning of menu, horizontally = barwidth + menu padding
      }
     
      addChild(DisplayObject(menuItem))
      //push menu instances into array
      menuItems.push(menuItem)
      //increment counter
      counter++

    }
   
    //--------------------------------------
    // OPENPANEL METHOD - OPEN A PANEL IN THE ACCORDION MENU
    //--------------------------------------     
    /**
    *   This public method will open a particular menu panel.
    * @param int Representing the menu panel you would like to open. Menus are stored as a zero based array. Some error checking is conducted to test if the menu requested is within the range of available menu items.
    * <p>The same effect can be achieved by dispatching a <code>NpAccordionEvent.EXPAND_MENU</code> event at the Accordion Class instance.</p>
    * @see noponies.accordion.events.NpAccordionEvent#EXPAND_MENU
    * @return
    */

    public function openPanel(menuToOpen:int):void {
      if(menuToOpen>menuItems.length || menuToOpen<0){
        throw new Error("Passed menu index is out of bounds!");
      }else{
        menuItems[menuToOpen].openPane()
      }
    }
   
    //--------------------------------------
    // CLOSEPANEL METHOD - CLOSE ANY OPEN PANEL IN THE ACCORDION MENU
    //-------------------------------------- 
    /**
    *   This public method will close any open menu panels.
    * <p>The same effect can be achieved by dispatching a <code>NpAccordionEvent.RESETALL</code> event at the Accordion Class instance.</p>
    * @see noponies.accordion.events.NpAccordionEvent#RESETALL
    * @return
    */

    public function closePanel():void {
      dispatchEvent(new NpAccordionEvent(NpAccordionEvent.RESETALL,true, false));
    }
   
    //--------------------------------------
    // REMOVED FROM STAGE HANDLER
    //-------------------------------------- 
    private function handleStageRemoval(event:Event):void {
      menuItems = []
      counter=0
    }
  }
}

ActionScript 3 FullScreen Object Resize Class

The NpFSObjectResize Class is a fairly simple ActionScript 3 class for displaying any display object at fullScreen (fullBrowser) screen dimensions. The class gives you the options of resizing to full the entire screen, or to resize to either width or height, and when using these later two options, you can set the class to position your object within the screen dimensions.

This class will likely be deployed across all the various fullscreen demos here. This class can be seen at work in the FullBrowser BG video.

Using this class is super easy to create lightbox type applications or fullScreen views of any display object.

Class Features

  • Min Stage Width - point at which scaling will turn off
  • Min Stage Height - point at which scaling will turn off
  • Use Stage Min - Controls whether or not objects scale or clip at a the MIN stage points
  • Scale Modes - “full”, “height”, “width”
  • Position Objects within stage dimensions

View Example
http://www.noponies.com/dev/as3_fsresize/

Source Files
http://www.blog.noponies.com/wp-content/uploads/npfsobjectresize.zip

Dependencies
None

Class ActionScript

/* AS3
*Copyright 2008 noponies.
*/


package noponies.display {

  import flash.display.Sprite;
  import flash.display.Stage;
  import flash.display.StageAlign;
  import flash.display.StageScaleMode;
  import flash.display.DisplayObject;
  import flash.events.Event;
  /**
  *  The NpFSObjectResize class is a Utility class for resizing a given object to fullscreen dimensions. Note, that the object must be part of the displaylist. The class checks for this and will throw an error if the passed in object
  * is not part of the display list. Using this class you are able to resize an object proportionally to fullscreen dimensions, or you can set it to scale either just its width or height to the corresponding
  *   stage width and height. You are also able position scaled objects within the stages dimensions, a typical use would be to center a width scaled image within the stages height.
  * <p>The class does not enforce smoothing of Bitmap or Video objects. Rather, you should set those object properties on each of your respective objects before
  *   passing them to this class.</p>
  * @langversion ActionScript 3.0
  * @Flash Player 9.0.28.0
  * @author noponies - 2008
  *   @version 1.0
  */


  public class NpFSObjectResize extends Sprite {
    private var resizeTarget:DisplayObject;
    private var stageRef:Stage;
    private var useMinStageSize:Boolean = false;
    private var XminSize:int = 400;
    private var YminSize:int = 400;
    private var stageWidth:int;
    private var stageHeight: int;
    private var resizeMode:String
    private var resizePosition:Number
   
    //--------------------------------------
    // GETTERS/SETTERS
    //--------------------------------------
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  Get / Set the minStageScaleX, which is an int. Used to control at what X point the scaling of the object should stop and it should be clipped.
     *  @default 400
     *  @return int representing the <code>x</code> value at which point clipping rather than scaling should occur.
     */

    public function get minStageScaleX():int{
      return XminSize
    }
    /**
    * @private
    */

    public function set minStageScaleX(newMinScaleX:int):void{
      XminSize = newMinScaleX
    }
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  Get / Set the minStageScaleY, which is an int. Used to control at what Y point the scaling of the object should stop and it should be clipped.
     *  @default 400
     *  @return int representing the <code>y</code> value at which point clipping rather than scaling should occur.
     */

    public function get minStageScaleY():int{
      return YminSize;
    }
    /**
    * @private
    */


    public function set minStageScaleY(newMinScaleY:int):void{
      YminSize = newMinScaleY;
    }
    /**
    *   @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  Get / Set whether or not to use clipping of the display object at a certain stage size. This property overrides the minStageScale setters, which have no
     *  effect if  this Boolean is false. Default
     *  @default false
     *  @return Boolean representing whether or not to enable clipping. A value of <code>true</code> enables clipping. A value of <code>false</code> disables clipping.
     */

     public function get useStageScaleMin():Boolean{
      return useMinStageSize
    }

    /**
    * @private
    */

    public function set useStageScaleMin(scaleOrClip:Boolean):void{
      useMinStageSize = scaleOrClip
    }

    //--------------------------------------
    // CONSTRUCTOR
    //--------------------------------------
    /**
     *  The NpFSObjectResize class is a Utility class for resizing a given object to fullscreen dimensions.
     *  <p>Please review classes public methods for adding content to the class!</p>
     *  @see #addResizeTarget()
     *  @example Demo Constructor and setter arguments.
     * <listing version="3.0">
     *  //Instantiate class first
     *  var fs:NpFSObjectResize = new NpFSObjectResize()
     *  fs.addResizeTarget(someDisplayObject)
     *  //Set properties via setters
     *  fs.minStageScaleX = 500
     *  fs.minStageScaleY = 500
     *  fs.useStageScaleMin = true
     * </listing>
     *  @example Demo Constructor setting an object to scale its width, and center it within the stages height
     * <listing version="3.0">
     *  //Instantiate class first
     *  var fs:NpFSObjectResize = new NpFSObjectResize()
     *  fs.addResizeTarget(monkey, "width", .5)
     * </listing>
     */

    public function NpFSObjectResize() {
    }
    //-----------------------------------------------------------------------------
    // PRIVATE INSTANCE METHODS
    //-----------------------------------------------------------------------------
    private function initResizeTarget():void{
      if (resizeTarget.stage != null) {
        stageRef = resizeTarget.stage;
        setUpListeners();
      } else {
        throw new Error("Passed object is not part of any display list, so its stage property cannot be accessed!");
      } 
    }
    //set up listeners and stage props
    private function setUpListeners():void {
      stageRef.scaleMode = StageScaleMode.NO_SCALE;
      stageRef.align = StageAlign.TOP_LEFT;
      stageRef.addEventListener(Event.RESIZE, resizeListener);
      resizeTarget.addEventListener(Event.REMOVED_FROM_STAGE,cleanUpClass);
      resizeObject(resizeTarget);
    }
    //resize listener
    private function resizeListener(event:Event):void {
      resizeObject(resizeTarget);
    }
    //here we actually resize our object
    //not sure if this is the best peforming approach here. Any opinions are welcome.
    private function resizeObject(targetObject:Object):void {
      //access stage width here. We want to respond to stage dimension changes immediately
      stageWidth = stageRef.stageWidth;
      stageHeight= stageRef.stageHeight;
     
      if (useMinStageSize) {
        if (stageWidth <= XminSize && stageHeight <= YminSize) {
          return;
        }
      }

      //determine what resize mode we are in, and respond accordingly
      switch (resizeMode) {
      case "height" :
        targetObject.height = stageHeight;
        targetObject.scaleX = targetObject.scaleY
        targetObject.x = stageWidth*resizePosition - targetObject.width*resizePosition;
        targetObject.y = 0
        break;
      case "width" :
        targetObject.width = stageWidth;
        targetObject.scaleY = targetObject.scaleX
        targetObject.y = stageHeight*resizePosition - targetObject.height*resizePosition;
        targetObject.x = 0
        break;
      default:

      targetObject.width = stageWidth;
      targetObject.scaleY = targetObject.scaleX;
     
      if (targetObject.height < stageHeight) {
        targetObject.height = stageHeight;
        targetObject.scaleX = targetObject.scaleY;
      }

      targetObject.x = 0;
      targetObject.y = 0;
     
      }

    }
    //clean up any listeners if the target object is removed from the display list.
    private function cleanUpClass(event:Event = null):void {
      stageRef.removeEventListener(Event.RESIZE, resizeListener);
      resizeTarget.removeEventListener(Event.REMOVED_FROM_STAGE,cleanUpClass);
      resizeTarget = null;
    }
    //-----------------------------------------------------------------------------
    // PUBLIC METHODS
    //-----------------------------------------------------------------------------
    /**
     *  The addResizeTarget function will load in a resize target object. Simply pass in a valid DisplayObject.
     *  @param resizeTarget Object which represents the DisplayObject you would like to scale to the full size of your stages dimensions.
     *  @param resizeMode String (Default = full) <strong>Optional param</strong> representing the scale mode for your target object. Possible values are <code>full</code> which will scale your object to match the screen dimensions, at all screen sizes.
     *  A value of <code>height</code> will scale the object to the stages height, and scale its width by the same scale factor. This can result in your object not always fully filling the browser window. A value of
     * <code>width</code> will scale your object to the stages width, scaling its height by the same scale factor. This can result in your object not always fully filling the browser window.
     *  @param resizePosition Number (Default = 0) <strong>Optional param</strong> representing the position on the stage you would like your resize object to be placed. This parameter is designed to allow for you to center your objects within the stage. For instance, a value of <code>0.5</code> will cause
     *  your object to be centered. A value of <code>0</code> will place your object at the top left. <strong>This parameter only affects resize objects when they are in a resize mode of <code>height</code> or <code>width</code>.</strong>
     *  @see #minStageScaleX
     *  @see #minStageScaleY
     *  @see #useStageScaleMin
     *  @return
     * 
     *  @example Demo Flash CS3 Timeline Based Constructor arguments and using public <code>addResizeTarget()</code> method.
     * <listing version="3.0">
     *    import noponies.display.NpFSObjectResize;
     *    //black and green are the instance names of two movieClips sitting on the stage!
     *    var resizeTargetObj:NpFSObjectResize = new NpFSObjectResize()
     *    resizeTargetObj.addResizeTarget(black, "width", .5)
     *    stage.addEventListener(MouseEvent.CLICK, handleClick)
     *
     *    function handleClick(event:MouseEvent):void{
     *      resizeTargetObj.addResizeTarget(green, "height", .5)
     *    }
     * </listing>
     */

    public function addResizeTarget(resizeTarget:DisplayObject,resizeMode:String = "full", resizePosition:Number = 0):void {
     
      if (stageRef == null) {
        this.resizeTarget = resizeTarget;
        this.resizeMode = resizeMode;
        this.resizePosition = resizePosition;
        initResizeTarget();
      } else {
        try {
          //kill any existing targets within this class instance
          removeResizeTarget()
          this.resizeTarget = resizeTarget;
          this.resizeMode = resizeMode;
          this.resizePosition = resizePosition;
          initResizeTarget();
        } catch (error:Error) {
          throw new Error("Problem adding new resize target");
        }
      }
    }
    /**
    *   This public method will remove a resizeTarget from this class. Call this if you would like to disable resizing of a DisplayObject.
    * @example Demo Flash Timeline Based Constructor arguments and using public <code>removeResizeTarget()</code> method.
    * <listing version="3.0">
    * var resizeTargetObj:NpFSObjectResize = new NpFSObjectResize(black)
    * stage.addEventListener(MouseEvent.CLICK, handleClick)
    *
    * function handleClick(event:MouseEvent):void{
    *  resizeTargetObj.removeResizeTarget()
    * }
    * </listing>
    * @return
    */

    public function removeResizeTarget():void {
      if(this.resizeTarget != null){
        stageRef.removeEventListener(Event.RESIZE, resizeListener);
        resizeTarget.removeEventListener(Event.REMOVED_FROM_STAGE,cleanUpClass);
        this.resizeTarget = null
        this.resizeMode = ""
        this.resizePosition = undefined
      }
    }
  }
}

ActionScript 3 Contextual Menu Manager Class

The NpContextMenu Class is a fairly simple ActionScript 3 class for creating and interacting with Contextual Menus.

The class simply redispatches the ContextMenuEvent.MENU_ITEM_SELECT event to any parties interested in responding to menu events outside of the actual class. This allows for a little more flexibility with how events are handled and how the menu itself is set up. By using this approach the menu can be a a little more dynamic.

Class Features

  • Public Methods
  • addMenuItem() - add menu item at run time
  • removeMenuItem() - remove menu item at run time
  • hideMenuItem() - hide menu item at run time
  • showMenuItem()_ - show menu item at run time
  • + a few getters

View Example
http://www.noponies.com/dev/as3_context_menu/

Source Files
http://www.blog.noponies.com/wp-content/uploads/npcontextmenu.zip

Dependencies
None

Class ActionScript

/* AS3
* Copyright 2008 noponies.
*/

package noponies.ui{
  import flash.ui.ContextMenu;
  import flash.ui.ContextMenuItem;
  import flash.ui.ContextMenuBuiltInItems;
  import flash.events.ContextMenuEvent;
  import flash.display.InteractiveObject;
  import flash.events.EventDispatcher;
 
  /**
  * The NpContextMenu Class is a utility class for creating Custom Contextual menus easily. With simple control over the menu items interactivity. Please see the various public methods and
  * properties for useage.
  * @langversion ActionScript 3.0
  * @Flash Player 9.0.28.0
  * @author noponies - 2008
  *   @version 1.0
  * @see #addMenuItem()
  * @see #removeMenuItem()
  * @see #hideMenuItem()
  * @see #showMenuItem()
  * 
  * @example Demo Useage using Flash CS3
  *
  * <listing version="3.0">
  *  //Flash CS3 Timeline based demo for creating a custom contextual menu with a simple navigateToURL
  *  //and fullScreen functionality.
  *  import noponies.ui.NpContextMenu;
  *  //create class instance and pass a reference to the maintime or stage in as the target for menu
  *  var menuTest:NpContextMenu = new NpContextMenu(this);
  *  //add the event listener that will respond to a user selecting a menu item
  *  menuTest.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,handleMenuSelection);
  *
  *  menuTest.addMenuItem("Go FullScreen",false);
  *  menuTest.addMenuItem("Exit FullScreen",false);
  *  menuTest.addMenuItem("By Noponies",true);
  *  menuTest.addMenuItem("© Noponies 2008",false);
  *  //disable the Exit FullScreen menu item on load
  *  menuTest.hideMenuItem("Exit FullScreen");
  *
  *  //add event listener for stage to handle toggling of menus item display
  *  stage.addEventListener(Event.FULLSCREEN, fullScreenHandler);
  *
  *  //Right Click menu case statement switch function. Take actions based
  *  //on what item is selected in the menu
  *  function handleMenuSelection(event:ContextMenuEvent):void {
  *   switch (menuTest.selectedMenu) {
  *    case "By Noponies" :
  *     break;
  *    case "© Noponies 2008" :
  *     var request:URLRequest = new URLRequest("http://www.blog.noponies.com/terms-and-conditions");
  *     navigateToURL(request);
  *     break;
  *    case "Exit FullScreen" :
  *     exitFullScreen();
  *     break;
  *    case "Go FullScreen" :
  *     goFullScreen();
  *     break;
  *   }
  *
  *  }
  *
  *  // functions to enter and leave full screen mode
  *  function goFullScreen():void {
  *   stage.displayState = StageDisplayState.FULL_SCREEN;
  *  }
  *
  *  function exitFullScreen():void {
  *   stage.displayState = StageDisplayState.NORMAL;
  *  }
  *  // Event listener function that handles toggling of menu item visibility
  *  //we simply check the status of the fullscreen param of the fullscreen event
  *  function fullScreenHandler(event:FullScreenEvent):void {
  *   if (event.fullScreen) {
  *    menuTest.hideMenuItem("Go FullScreen");
  *    menuTest.showMenuItem("Exit FullScreen");
  *   } else {
  *    menuTest.hideMenuItem("Exit FullScreen");
  *    menuTest.showMenuItem("Go FullScreen");
  *   }
  *  }
  *  </listing>
  */


  public class NpContextMenu extends EventDispatcher {
    private var customCM:ContextMenu;//the custom menu
    private var target:InteractiveObject;
    private var selectedMenuItem:String
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  Get the current menuitems label which is a string
     *  @return String representing the <code>label</code> value of the current menu item.
     */

    public function get selectedMenu():String {
      return selectedMenuItem;
    }
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  Get the current menuitems within the entire contextual menu
     *  @return Array representing all of the current contextual menu items.
     */

    public function get currentMenuItems():Array {
      return customCM.customItems;
    }
   
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  The NpContextMenu Class requires one parameter to be set via a constructor argument. This is a reference to the DisplayObject you want the contextual menu item to be active on.
     *  @param target InteractiveObject representing the target DisplayObject you want the menu item to be active on.
    * @see #addMenuItem()
    * @see #removeMenuItem()
    * @see #hideMenuItem()
    * @see #showMenuItem()
     *  @return void
     */

    public function NpContextMenu(target:InteractiveObject) {
      this.target = target
      customCM = new ContextMenu();
      removeDefaultItems();
      target.contextMenu = customCM;
    }
    //--------------------------------------
    // PRIVATE INSTANCE METHODS
    //--------------------------------------
    //clean out the built in items
    private function removeDefaultItems():void {
      customCM.hideBuiltInItems();
    }
    //dispatch the menu select event
    private function dispatchMenuEvent(event:ContextMenuEvent):void{
      selectedMenuItem = event.target.caption
      dispatchEvent(event)
    }
    //--------------------------------------
    // PUBLIC INSTANCE METHODS
    //--------------------------------------
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  This function creates a new menu item within the current contextual menu.
     *  @param menuLabel String representing the label of the menu item.
     *  @param separatorBefore Boolean representing whether or not you want a seperator line in the contextual menu before this new menu item.
     *  @return void
     */

    public function addMenuItem(menuLabel:String,separatorBefore:Boolean):void{
        var newCm:ContextMenuItem = new ContextMenuItem(menuLabel, separatorBefore);
        newCm.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, dispatchMenuEvent);
        customCM.customItems.push(newCm);
    }
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  This function will remove an item from the current contextual menu.   
     *  @param menuLabel String representing the label of the menu item you would like to remove.
     *  @return void
     */

    public function removeMenuItem(menuLabel:String):void{
      var currentMenuItemsArray:Array = customCM.customItems
        for(var i:Object in currentMenuItemsArray) {
                 if(currentMenuItemsArray[i].caption==menuLabel){
            currentMenuItemsArray[i].removeEventListener(ContextMenuEvent.MENU_ITEM_SELECT, dispatchMenuEvent);
            customCM.customItems.splice(i, 1)
            break;
          }
          }
     
    }
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  This function will disable an item in the current contextual menu. The item will still be visible, it just wont be selectable.
     *  @param itemToDisable String representing the label of the menu item you would like to disable.
     *  @return void
     */

    public function hideMenuItem(itemToDisable:String):void{
        var currentMenuItemsArray:Array = customCM.customItems;
        for (var i:Object in currentMenuItemsArray) {
          if (currentMenuItemsArray[i].caption==itemToDisable) {
            customCM.customItems[i].enabled = false;
            break;
          }
        }
    }
    /**
    * @langversion ActionScript 3.0
    * @playerversion Flash 9
     *  This function will enable a disabled item in the current contextual menu.
     *  @param itemToEnable String representing the label of the menu item you would like to enable.
     *  @return void
     */

    public function showMenuItem(itemToEnable:String):void {
      var currentMenuItemsArray:Array = customCM.customItems;
      for (var i:Object in currentMenuItemsArray) {
        if (currentMenuItemsArray[i].caption==itemToEnable) {
          customCM.customItems[i].enabled = true;
          break;
        }
      }
    }
  }
}

Simple ActionScript 3 Slideshow Engine

Simple ActionScript 3 Slideshow engine. This class file simply creates a slideshow that in its current setup, cross fades between each image. The class uses external images and is in fact, abstracted from sourcing any images. It is up to you to provide the class with an array of image URLs for it to use. This is a reworking of an earlier class, which has now been removed from this site.

Class currently uses tweenLite to handle the alpha transitions. However, this is simply replaced via a simple timer function. But I’ve left tweenLite in the class so that people can change the transitions to other types, like, blur, photoFlash etc easily by changing the tween type. If you just want an alpha fade and don’t use tweenLite elsewhere in your project, replace the tweenLite functionality with your own alpha fading transition. An example of which, is commented out in the class source code.

Class settings are instance based, which you access via getters/setters. So you can have muliple slideshow instances running at the same time

Class Features

  • External Images
  • Control over image cross fade time
  • Control over image display time
  • Linear or random image progression
  • Automatic (timer) progression, or via mouse event
  • Looping or play once
  • Pause / Resume the slideshow in auto mode

Via setters, you can access and set the following properties for each slideshow instance..

xFadeTime: get/set - DataType:uint - Sets crossfade time or transition time between two slides in seconds
imageTime: get/set - DataType:uint - Sets total image display time, not including xFadeTime in seconds
slidesPlayRandom: get/set - DataType:Boolean - Sets the linear or random play order for slides. Set to true for random playback.
slidesLoop: get/set - DataType:Boolean - Sets whether the slideshow loops, or stops at end of images array. True = looping
slidesAutoPlay: get/set - DataType:Boolean - Sets whether the slides use the timer to auto progress, or whether a user must click on the slides to progress. True = autoPlay

Look in the demo .fla’s document class for examples of listening for the classes various events. You can listen for Open, Progress, Complete and SlideShowComplete events at the class instance level. You can also dispatch a pause and a resume event to the class. Which will pause / resume the class if it is in automatic mode.

View Example
http://www.noponies.com/dev/as3_xslideshow/

Source Files
http://www.blog.noponies.com/wp-content/uploads/as3_xslideshow_1_2.zip

Dependencies
tweenLite

Class ActionScript

/*******************************************************************************
SIMPLE CROSS FADING ACTIONSCRIPT 3 SLIDESHOW CLASS
********************************************************************************

This class file is abstracted from its data source, which is an array of images. The class does not
handle any XML parsing, remoting etc. Rather, you pass an array of images and adjust the classes per instance settings
via its various getters and setters.

********************************************************************************
SETTINGS
********************************************************************************
Via setters, you can access and set the following properties for each slideshow instance..

xFadeTime: get/set - DataType:uint - Sets crossfade time or transition time between two slides in seconds
imageTime: get/set - DataType:uint - Sets total image display time, not including xFadeTime in seconds
slidesPlayRandom: get/set - DataType:Boolean - Sets the linear or random play order for slides. Set to true for random playback.
slidesLoop: get/set - DataType:Boolean - Sets whether the slideshow loops, or stops at end of images array. True = looping
slidesAutoPlay: get/set - DataType:Boolean - Sets whether the slides use the timer to auto progress, or whether a user must click on the slides to progress. True = autoPlay

********************************************************************************
SAMPLE USEAGE - NOTE: SET THE CLASSES PROPERTIES BEFORE YOU ADD IT TO THE DISPLAY LIST
********************************************************************************
Sample Useage
In a .fla or other class
var newSlides:Xslides = new Xslides(an Array of Image URLS);
newSlides.xFadeTime = 1;
newSlides.imageTime = 3;
newSlides.slidesPlayRandom = false;
newSlides.slidesLoop = true;
newSlides.slidesAutoPlay = true;
//Note, add to display list after class instance props are set..
addChild(newSlides);

Once the class is set up, you can listen for these events to create progress displays, track what slide is currently playing etc..
********************************************************************************
EVENTS
********************************************************************************
Class dispatches these events that correspond to various stages of loading and displaying slides
Event.OPEN - Dispatched with each request for a new slide
ProgressEvent.PROGRESS - Dispatched as slide loads
Event.COMPLETE - Dispatched once slide has loaded
Xslides.SLIDE_SHOW_COMPLETE - Dispatched only if slideshow is in non looping mode and the slideshow reaches the last image in the slidearray.

//demo event listeners showing how you can listen in for slide events and the use of some of the
//classes getter functions to access information about each slide.
newSlides.addEventListener(Event.OPEN, handleSlideOpen);
newSlides.addEventListener(ProgressEvent.PROGRESS, handleSlideProgress);
newSlides.addEventListener(Event.COMPLETE, handleSlideLoad);
newSlides.addEventListener(Xslides.SLIDE_SHOW_COMPLETE, handleSlideShowComplete);

********************************************************************************
Version 1.2: Release 17 July, 2008 - Fixed Remove from stage error
********************************************************************************
Made by noponies in 2008
http://www.blog.noponies.com

Terms and Conditions for use
http://www.blog.noponies.com/terms-and-conditions

*********************************************************************************/

package noponies.display {
  import flash.display.Sprite;
  import gs.TweenLite;//using TweenLite to handle alpha fades
  import flash.events.*;
  import flash.net.URLRequest;
  import flash.display.Loader;
  import flash.display.Bitmap;
  import flash.display.BitmapData;
  import flash.utils.Timer;

  public class Xslides extends Sprite {
    //--------------------------------------
    // CLASS CONSTANTS
    //--------------------------------------
    public static  const SLIDE_SHOW_COMPLETE:String  = "slideshowcomplete";
    public static  const PAUSE_SLIDE_SHOW:String  = "pauseslideshow";
    public static  const RESUME_SLIDE_SHOW:String  = "resumeslideshow";
    //--------------------------------------
    // PRIVATE INSTANCE VARS
    //--------------------------------------
    //access via getters/setters
    private var crossFadeTime:uint = 2;//SECONDS
    private var imageDisplayTime:uint = 10;//SECONDS
    private var randomXshow:Boolean = false;//random or linear slide progression
    private var looping:Boolean = true;//do the slides loop?
    private var autoSlideProgression:Boolean = false;//autoSlideProgression movement through slideshow
    private var pauseSlideShow:Boolean = false//var to track pausing/playing of slideshow. Get only!
    //internal vars
    private var contentHolder:Sprite;//the target sprite the slides load into
    private var p:int;//counter var
    private var slideArray:Array;//array of images
    private var loader:Loader;//loader for loading in images
    private var slide:Bitmap;//sprite that serves as a content holder for loaders content
    private var repeat:uint = 1;//timer repeat amount
    private var slideTimer:Timer = new Timer(imageDisplayTime*1000, repeat);//timer
    private var contentLoaded:Boolean = false
   
    //--------------------------------------
    // GETTERS/SETTERS
    //--------------------------------------
    //get crossFadeTime
    public function get xFadeTime():uint {
      return crossFadeTime;
    }
    //set crossFadeTime
    public function set xFadeTime(newXFadeTime:uint):void {
      crossFadeTime = newXFadeTime
    }  
    //get imageDisplayTime
    public function get imageTime():uint {
      return imageDisplayTime;
    }
    //set imageDisplayTime
    public function set imageTime(newImageDisplayTime:uint):void {
      imageDisplayTime = newImageDisplayTime
      slideTimer.delay = imageDisplayTime*1000
    }
    //set random or ordered slideShow
    public function get slidesPlayRandom():Boolean{
      return randomXshow
    }
    public function set slidesPlayRandom(randomOrder:Boolean):void{
      randomXshow = randomOrder
    }
    //set get slideShow looping
    public function get slidesLoop():Boolean{
      return looping
    }
    public function set slidesLoop(loop:Boolean):void{
      looping = loop
    }
    //set get autoSlideProgression or auto playback
    public function get slidesAutoPlay():Boolean{
      return autoSlideProgression
    }
    public function set slidesAutoPlay(auto:Boolean):void{