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{
      autoSlideProgression = auto
    }
    //get total slides
    public function get totalSlides():int{
      return slideArray.length
    }
    //get current slide num
    public function get currentImage():int{
      return p
    }
    //get current slide file name
    public function get currentImageName():String{
      return slideArray[p]
    }
    //get current slideshow play status
    public function get slideShowPaused():Boolean{
      return pauseSlideShow
    }
    //--------------------------------------
    // CONSTRUCTOR
    //--------------------------------------
   
    public function Xslides(slideArray:Array) {
      this.contentHolder = new Sprite();
      addChild(contentHolder)
      this.slideArray = slideArray;
      addEventListener(Event.ADDED_TO_STAGE,addedToStage)
      addEventListener(Event.REMOVED_FROM_STAGE,removedFromStage)
      addEventListener(Xslides.PAUSE_SLIDE_SHOW, handleSlideShowPause)
      addEventListener(Xslides.RESUME_SLIDE_SHOW, handleSlideShowResume)
    }
    //--------------------------------------
    // PRIVATE INSTANCE METHODS
    //--------------------------------------
    private function addedToStage(event:Event):void{
      //initial slide start position value
      if (randomXshow) {
        p = Math.floor((Math.random()*slideArray.length));
      } else {
        p = 0;
      }
      //call the image loader function
      loadImage();
      //add a timer event listener or mouse click if we are not in autoSlideProgression mode
      slideTimer.addEventListener(TimerEvent.TIMER_COMPLETE, loadImage);
      if (!autoSlideProgression) {
        contentHolder.addEventListener(MouseEvent.CLICK, loadImage);
      }
    }
    //main load image function
    private function loadImage(event:Event = null) {
      loader = new Loader();
      loader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
      loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
      loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);   
      loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, handleProgress);
      var request:URLRequest = new URLRequest(String(slideArray[p]));//access our array of url's
      loader.load(request);
      contentLoaded = false

    }
    /*COMPLETE Event Call Back function, does the work of the slideshow.  The timer is reset, new slides are faded into place and old slides
    are removed, the p counter variable is incremented and the timer is restarted*/


    private function loaded(event:Event):void {
     
      if(autoSlideProgression){
        slideTimer.reset();//reset the timer
      }
     
      slide = Bitmap((loader.content));//create a sprite to load
      slide.alpha = 0;//set the slide content to have an alpha of 0
      slide.x = 0;//position the slide content
      slide.y = 0;//position the slide content
      loader.unload()
      loader = null
      contentHolder.addChild(slide);
      TweenLite.to(slide, crossFadeTime, {alpha:1, onComplete:onFinishAlpha});//alpha in the slides

      function onFinishAlpha():void {
        dispatchEvent(new Event(Event.COMPLETE,true, false));
        if(autoSlideProgression){
        //check to see if we are looping or not, if we are, kill the timer and stop at this last slide
        if (!looping && p==slideArray.length) {
          slideTimer.reset();
        } else if(!pauseSlideShow) {
          slideTimer.start();//start the timer again when we have loaded in the slide
        }
        }
        /*check here to see if we have a slide existing, delete it if we do
        takes advantage of AS3's depth manager shuffling the slides clip depths
        for us.*/

        if (contentHolder.numChildren>1) {
          var tempBit:Bitmap = Bitmap(contentHolder.getChildAt(0))
          tempBit.bitmapData.dispose()
          tempBit = null
          contentHolder.removeChildAt(0);
         
        }
        contentLoaded = true
      }
      /*reset the p counter variable based on if we have a random or linear slide show, and also check to see that the
      value is not beyond the total number of images we actually have in our array.*/

      //if we are not sposed to loop, and we are in random mode, we need to remove items from the slide array to force the
      //slide show to stop when all possible images have been displayed
      if(!looping && randomXshow){
          slideArray.splice(p,1)
          if(slideArray.length ==0){
            dispatchEvent(new Event(Xslides.SLIDE_SHOW_COMPLETE,true));
          }
        }
       
      if (!randomXshow) {
        p++;
      } else {
        p = Math.floor((Math.random()*slideArray.length));
      }
      if (!randomXshow && p==slideArray.length && looping) {
        p =0;
      }
      if (!randomXshow && p==slideArray.length && !looping) {
        dispatchEvent(new Event(Xslides.SLIDE_SHOW_COMPLETE,true));
      }
    }
    //--------------------------------------
    // EVENT HANDLERS
    //--------------------------------------
    //open event handler, simply redispatch
    private function openHandler(event:Event):void{
      dispatchEvent(event);
    }
    //load progress handler, simply redispatch the progress event at class scope level
    private function handleProgress(event:ProgressEvent):void {
      dispatchEvent(event)
    }
   
    //rudimentary IO Error handling
    private function onIOError(event:IOErrorEvent):void {
      trace("There was an IOerror accessing the image file: " + event);
    }
    //handler for pause slideshow events. First set the bool that tracks slideshow pause status
    //then reset the timer. The reason we use both a var and reset the timer is that the timer
    //may not actually be running when we get a pause event, as the slideshow might be loading an image
    //the bool is checked against in the class when it add the main image display timer.
    private function handleSlideShowPause(event:Event):void{
      pauseSlideShow = true
      slideTimer.reset()
    }
    //restart the slideshow if it is paused
    private function handleSlideShowResume(event:Event):void{
      pauseSlideShow = false
      slideTimer.start()
    }
    //handle removal from stage
    private function removedFromStage(event:Event):void{
      try {
      if(loader !=null){
        loader.close()
      }
      slideTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, loadImage);
      removeEventListener(Xslides.PAUSE_SLIDE_SHOW, handleSlideShowPause)
      removeEventListener(Xslides.RESUME_SLIDE_SHOW, handleSlideShowResume)
      slideTimer.reset()
      //kill any tweens running through tweenLite
      if(!contentLoaded){
      TweenLite.killTweensOf(slide, false);
      }
      slideArray = null
      slide = null
      contentHolder = null
      removeEventListener(Event.REMOVED_FROM_STAGE,removedFromStage)
      } catch (e:Error) {
        throw new Error("There was an error when attempting to delete all slide content: "+Error);
      }
    }

  }

}
/*//fade alpha function
    //will run slower if the screen is being resized.
  private function fadeTimerListener(event:TimerEvent) {
      slide.alpha += .01;
      if (slide.alpha >= 1) {
        fadeTimer.removeEventListener(TimerEvent.TIMER, fadeTimerListener);
        fadeTimer.reset();
        onFinishAlpha();
    }
    event.updateAfterEvent();
  }
   
  private function onFinishAlpha():void {
      //stuff
}*/

29 Responses to “Simple ActionScript 3 Slideshow Engine”


  1. 1 NEERAJ

    hii,
    can we create same slideshow without using xml or flashvars,
    i need that the image will readed from a one single directory,if we update or delete somthing flash will work accordingly.

    is it possible

    thanks,
    neeraj

  2. 2 Dale

    Sure, you would have to use a PHP or similar solution to parse the directory for files.

  3. 3 Roman

    Hey,

    great thing. It would be really nice if you could add controls to it and a loading status of the current loading image. Controls like
    stop the slide show, start the slide show.

    have a look at this website and it´s slide show feature

    http://www.sasokos.com/

    Greets,

    Roman

  4. 4 Dale

    Roman,

    The class is meant as a base example that can be extended on. It already supports a progress event for each slide loading. I have demonstrated in the demo how to hook into that event. For pausing and starting, simply adjust the classes timer interval.I added in a pause / resume event pair for pausing and resuming the slideshow.

  5. 5 Mike

    I can’t view the flash after embed. But I can view the flash by directly type the full URL SWF path. What’s wrong with me?

  6. 6 Dale

    Mike,

    NO idea.

  7. 7 Nick

    glad to see you switched back to this layout! It’s much nicer :)

  8. 8 Dario Gutierrez

    Awesome slideshow engine, thanks for sharing!! Oye Dale, if i modify your flash source, can i publish it in my blog?

  9. 9 Dale

    Dario,
    yeah thats fine. Just put in a credit etc. Be interested to see what you make.

  10. 10 Dario Gutierrez

    Thanks Dale, i will tell u when publish it!! Best Regards from Mexico.

  11. 11 Budy

    Hi Dale,

    If I want to use this slideshow without using xml and php, just point to specific folder, how difficult to do it? Do you mind to show me how to do it in simplest way? The main reason why I want this is currently I have a project, and it requires to update the content from the directory (a folder), then every six hours, they will change the images (6 images) by replacing the old images.

    Hope you can help and really appreciate it!

    Thank you so much.

    Budy

  12. 12 meowsk

    I am curious if it is possible to have the images fade out like they fade in. I have several different sized images in my slide show so when a smaller one shows up over a larger one the on in the back just disappears without any fading.

  13. 13 kai

    I’m still a poor student so I can’t afford much but I’ve sent you what I can. To be honest, it’s not just because I’ve used this bit of flash (twice) but because I really do respect people who take the time to write concise code. And not just that but it’s easy to use (which takes good planning to achieve) and has notes that are all useful. Cheers. Buy yourself a good meal along with a tasty beer :)

  14. 14 Dale

    Kai,

    Thanks a lot. Your support is very appreciated. :)

  15. 15 Niklas

    Hi there!
    Love the stuff you have here..!!
    I have a question - does anyone know how would you go about to have the lower right corner fixed instead of the top left one? That way the image would still be cropped when needed but on the left side instead…

    All the best, Nikals

  16. 16 John

    Howdy,
    I just got your Full Browser XML Slideshow working, and out of curiosity i checked the rest of your blog and found this script. I have a few question:

    1. How is this script different than FullBrowserXShow class you published in Feb 2008?

    2. Is this new class meant to replace FullBrowserXShow class, or were you referring to a different outdated script at the beginning of this post?

    3. Would you recommend using this script instead for a simple fullscreen slideshow?

    Thanks and great work,
    John

  17. 17 Dale

    John,

    The only difference is the fullScreen element of it.

    The reference to the older class was about a version of this particular example, that I reworked to better handle memory and improve the overall structure etc.

    For a simple fullScreen slide show, I’d still use the other fullBrowserSlideshow example. You could use this one, but you would have to implement the resizing to browser size etc.

    A future update to most of the fullscreen classes etc here will abstract out the fullScreen elements of each class. I’ve written a more modular class that takes any display object and resizes it to fullScreen. Once I post that, you will be able to simply plug in content as you see fit, and have it scale to full browser size etc. Its all part of the fullScreen video demo I’ve been working on, and taking too long to finish. :)

  18. 18 Byron

    Thanks for the clean script. In response to the folks above who want the old slide to fade out, add ‘onStart:oldSlideAlpha’ to the TweenLite function, then paste the following function right before the onFinishAlpha one:

    function oldSlideAlpha():void {
    if (contentHolder.numChildren>1) {
    TweenLite.to(contentHolder.getChildAt(0), crossFadeTime, {alpha:0});
    }
    }

    This will crossfade the old slide for the same duration as the new slide fade-in

  19. 19 Byron

    Oops! I forgot to mention that the tween function is located on line 212 of the Xslides.as file. :)

  20. 20 Nabil

    Hi , thx for the slideshow
    i get an error when i try to remove the xslides from the display list
    newSlides = new Xslides(imgNames);
    .
    .
    .

    removeChild (newSlides);

    err:”There was an error when attempting to delete all slide content: class [error]”
    ot seems this is the culprit: //loader.unload(); inside removedFromStage

    thx any ideas?

  21. 21 Dale

    Nabil,

    Yeah, I knew about that error and had fixed it, but had not quite uploaded it to the site.

    I’ve uploaded it now, but if you just wanted to change your version; Remove that unload call from the RemovedFromStage handler and add in this..

    if(loader !=null){
            loader.close()
          }

    The version I’ve uploaded also kills any running tweens, which can also cause an issue when removed from the stage, as tweenLite will continue to tween and then look for an object when it completes is tween, which of course is no longer there, and throws and error.

  22. 22 Nabil

    Awesome Dale- thank you so much for getting back to me so quickly i should have also thought about it too -but thx and i ll download your latest files.

  23. 23 Nabil

    Hi - is there a way to just cached the images after the slideshow has done rotating once ? instead of loading again the same images ?thx nabil

  24. 24 Dale

    Hi,

    No, no method to cache the images.

  25. 25 Joel

    This is really awesome. I was having a huge issue with getting a good crossfade in Flex. I changed your class to extend UIComponent, and it works like a dream.

    Cheers.

  26. 26 Bernhard

    Hi thanks for sharing this cool viewer!

    Is it possible to add urls to the images you load?

    Cheers.

  27. 27 Dale

    Bernhard,

    No, that functionality is not present at the moment.

  28. 28 Empas

    Thank you very much for your script. It helps a lot to all of us that are moving from AS2 to AS3!!

    Cheers.

  1. 1 ActionScript 3.0 Image Galleries « Bauhouse

Leave a Reply