AS3: SliderUI

UPDATE: Please use SliderUI v1.51 for the latest and greatest.

View Example
View Documentation
Download Class & Example Files

If you're anything like me, you hate using components and try to steer clear of them WHENEVER you can. The SliderUI was spawned from this hate and is a super easy way to create a slider (the equivalent to the Slider component, except it weighs in at a whopping 1KB compared to the 17KB of the component). The SliderUI has pretty much all of the same functionality of the Slider component.

There is a start and end value you can set for the slider to match up with any "unit of measure" you want to use. You can also set where the slider should begin (value-wise) and ou can get back the position of the slider as the current value or the percentage value.

Here is the class:

Actionscript:
  1. package com.reintroducing.ui
  2. {
  3.     import flash.display.Sprite;
  4.     import flash.display.Stage;
  5.     import flash.events.MouseEvent;
  6.     import flash.events.TimerEvent;
  7.     import flash.geom.Rectangle;
  8.     import flash.utils.Timer;
  9.     import flash.utils.getQualifiedClassName;   
  10.  
  11.     /**
  12.      * The SliderUI is a class that allows you to quickly create sliders with tracks without the need to use components.
  13.      * There is a "percent" and a "currentValue" property that you can tap into to see what position the slider is at on the track.
  14.      * </ p>
  15.      * Please note that if you are using the SliderUI on the "y" axis your track's registration point needs to be on the
  16.      * bottom (NOT the top) and the slider will go up to raise the value and down to lower it.  If you do not pay attention
  17.      * to this your slider will be "broken".
  18.      *
  19.     * @author Matt Przybylski [http://www.reintroducing.com]
  20.     * @version 1.0
  21.     */
  22.     public class SliderUI
  23.     {
  24. //- PRIVATE & PROTECTED VARIABLES -------------------------------------------------------------------------
  25.  
  26.         private var _stage:Stage;
  27.         private var _track:Sprite;
  28.         private var _slider:Sprite;
  29.         private var _timer:Timer;
  30.         private var _percent:Number;
  31.         private var _lowVal:Number;
  32.         private var _highVal:Number;
  33.         private var _startVal:Number;
  34.         private var _currentVal:Number;
  35.         private var _range:Number;
  36.         private var _axis:String;
  37.         private var _changeProp:String;
  38.        
  39. //- PUBLIC & INTERNAL VARIABLES ---------------------------------------------------------------------------
  40.        
  41.        
  42.        
  43. //- CONSTRUCTOR -------------------------------------------------------------------------------------------
  44.    
  45.         /**
  46.          * Creates an instance of the SliderUI with the given parameters.  If the $startVal parameter is set to something
  47.          * higher than the $highVal or lower than the $lowVal parameter, the $startVal parameter is reset to one of those two values.
  48.          *
  49.          * @param $stage The stage that the track and slider are sitting on
  50.          * @param $axis The axis that the slider will be used on
  51.          * @param $track The track to be used for the slider
  52.          * @param $slider The object that will function as the slider
  53.          * @param $lowVal A number representing the low value of the slider
  54.          * @param $highVal A number representing the high value of the slider
  55.          * @param $startVal A number representing the value the slider should start at (default: 0)
  56.          *
  57.          * @return void
  58.          */
  59.         public function SliderUI($stage:Stage, $axis:String, $track:Sprite, $slider:Sprite, $lowVal:Number, $highVal:Number, $startVal:Number = 0):void
  60.         {
  61.             this._stage = $stage;
  62.             this._axis = $axis;
  63.             this._track = $track;
  64.             this._slider = $slider;
  65.             this._lowVal = $lowVal;
  66.             this._highVal = $highVal;
  67.             this._startVal = $startVal;
  68.            
  69.             this._changeProp = (this._axis == "x") ? "width" : "height";
  70.             this._range = (Math.abs(this._lowVal) + this._highVal);
  71.             this._slider.buttonMode = true;
  72.             this._timer = new Timer(10);
  73.            
  74.             if (this._startVal <this._lowVal) this._startVal = this._lowVal;
  75.             if (this._startVal> this._highVal) this._startVal = this._highVal;
  76.            
  77.             if (this._startVal <0)
  78.             {
  79.                 this._percent = (Math.abs(this._lowVal + Math.abs(this._startVal)) / this._range);
  80.             }
  81.             else
  82.             {
  83.                 this._percent = (Math.abs(this._lowVal - this._startVal) / this._range);
  84.             }
  85.            
  86.             this._currentVal = (this._lowVal + (this._range * this._percent));
  87.            
  88.             if (this._axis == "x")
  89.             {
  90.                 this._slider[this._axis] = (this._track[this._axis] + (this._percent * this._track[this._changeProp]));
  91.             }
  92.             else
  93.             {
  94.                 this._slider[this._axis] = (this._track[this._axis] - (this._percent * this._track[this._changeProp]));
  95.             }
  96.            
  97.            
  98.             this.initEvents();
  99.         }
  100.        
  101. //- PRIVATE & PROTECTED METHODS ---------------------------------------------------------------------------
  102.        
  103.         /**
  104.          * Initializes the slider and timer events.
  105.          */
  106.         private function initEvents():void
  107.         {
  108.             this._slider.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
  109.             this._slider.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
  110.             this._timer.addEventListener(TimerEvent.TIMER, updateInfo);
  111.         }
  112.        
  113. //- PUBLIC & INTERNAL METHODS -----------------------------------------------------------------------------
  114.    
  115.         /**
  116.          * Enables the controls of the SliderUI.
  117.          *
  118.          * @return void
  119.          */
  120.         public function enable():void
  121.         {
  122.             this.initEvents();
  123.         }
  124.        
  125.         /**
  126.          * Disables the controls of the SliderUI.
  127.          *
  128.          * @return void
  129.          */
  130.         public function disable():void
  131.         {
  132.             this._slider.removeEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
  133.             this._slider.removeEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
  134.             this._timer.removeEventListener(TimerEvent.TIMER, updateInfo);
  135.         }
  136.        
  137.         /**
  138.          * Cleans up the SliderUI for garbage collection.
  139.          *
  140.          * @return void
  141.          */
  142.         public function destroy():void
  143.         {
  144.             this.disable();
  145.            
  146.             this._timer = null;
  147.         }
  148.    
  149. //- EVENT HANDLERS ----------------------------------------------------------------------------------------
  150.    
  151.         /**
  152.          * Starts the dragging of the slider and starts the timer to dispatch percentage.
  153.          */
  154.         private function handleMouseDown($evt:MouseEvent):void
  155.         {
  156.             if (this._axis == "x")
  157.             {
  158.                 this._slider.startDrag(false, new Rectangle(this._track.x, this._slider.y, this._track.width, 0));
  159.             }
  160.             else
  161.             {
  162.                 this._slider.startDrag(false, new Rectangle(this._slider.x, this._track.y, 0, -this._track.height));
  163.             }
  164.            
  165.             this._timer.start();
  166.            
  167.             this._stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
  168.         }
  169.        
  170.         /**
  171.          * Stops the slider dragging and timer.
  172.          */
  173.         private function handleMouseUp($evt:MouseEvent):void
  174.         {
  175.             this._slider.stopDrag();
  176.             this._timer.reset();
  177.            
  178.             this._stage.removeEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
  179.         }
  180.        
  181.         /**
  182.          * Updates the info of the slider's position.
  183.          */
  184.         private function updateInfo($evt:TimerEvent):void
  185.         {
  186.             this._percent = Math.abs((this._slider[this._axis] - this._track[this._axis]) / this._track[this._changeProp]);
  187.             this._currentVal = (this._lowVal + (this._range * this._percent));
  188.         }
  189.  
  190. //- GETTERS & SETTERS -------------------------------------------------------------------------------------
  191.    
  192.         /**
  193.          * Returns the percentage of the slider's position on the track, between 0 and 1.
  194.          *
  195.          * @return Number
  196.          */
  197.         public function get percent():Number
  198.         {
  199.             return this._percent;
  200.         }
  201.        
  202.         /**
  203.          * Returns the current value of the slider's position on the track.
  204.          *
  205.          * @return Number
  206.          */
  207.         public function get currentValue():Number
  208.         {
  209.             return this._currentVal;
  210.         }
  211.    
  212. //- HELPERS -----------------------------------------------------------------------------------------------
  213.    
  214.         public function toString():String
  215.         {
  216.             return getQualifiedClassName(this);
  217.         }
  218.    
  219. //- END CLASS ---------------------------------------------------------------------------------------------
  220.     }
  221. }

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

33 Comments

[...] - Make draggable sliders easily and quickly! 1 Minute Ago View Example View Documentation View Post/Download If you

Any body have hands of experience with maya?

Hi,
It sure looks promising but is not fully working for me: I wanted to have a starting value of 30 and it does put the drag handle closer to the right side of the scroll bar not not quite there--it places some pixels to the left of the right edge of the bar. Basically, I want to create a date slider where the user can slide back 1 day or 2 day, up to 30 days back.
Any ideas?
Thanks and here is my code:

-------------------------
import com.digitalwatershed.SliderTick;

var sui:SliderTick = new SliderTick(stage, "x", track_mc, slider_mc, 1, 30, 30);
//var sui2:SliderTick = new SliderTick(stage, "y", track2_mc, slider2_mc, -2, 1, -1);

trace("FIRST PERCENT: " sui.percent " & VALUE: " sui.currentValue);
//trace("SECOND PERCENT: " sui2.percent " & VALUE: " sui2.currentValue);

I think I have found a way around it. In your Class, modified the line as per:

//this._slider[this._axis] = (this._track[this._axis] (this._percent * this._track[this._changeProp]));
this._slider[this._axis] = (this._track[this._axis] (this._track[this._changeProp]));

Now, it would be nice to show the TickBars too!

But thanks a bunch anyway. The Flash CS3's built-in Slider doesn't seem to allow the starting position and that had me stuck for a while.

meengla, i imagine it has something to do with your registration points and the way your clips are set up. the programming behind the SliderUI has worked very well for me through various tests I have run and you shouldn't have to edit it any. if you want to send me your FLA i can take a look at it. and what do you mean by showing tickbars? if you want to show little ticks on your track all you'd have to do is set up a clip that sits on top of the track that shows the tick marks, the way you design it is entirely up to you.

Hi Matt,
Please see my previous post. I think that particular problem is solved now.
Thanks!

Meengla,
I think I ran into the same problem you described just now and have fixed it. I've updated the download files in the v1.5 update (not this pot, the 1.5 one) so you should grab those files and it will have the latest version with the correct range. Sorry about that.

Hey Matt,
No problem. I may download it later.
Thanks!

Wonderful class, I really enjoy using it. It does everything I need other than update the slider through the current value. In other words, I would like to be able to set the currentValue and have the slider position updated accordingly. Otherwise, wonderful work and thank you πŸ™‚

Ben,
It does have that functionality in version 1.5:

http://evolve.reintroducing.com/2008/08/14/as3/as3-sliderui-v15/

πŸ˜›

Woohoo, thanks πŸ˜€

And the precision parameter is great, too. Nice update πŸ™‚

pretty buggy for me... i'm gonna switch to somthing else or spend an hour writing my own... but thanks anyways i think if i had managed to get some of the bugs ironed out i would have used it...

ryan,
what bugs are you experiencing?

Hi Matt,
Thanks for your sharing. I have one question. I want to put content when the user is using this slider and dragging to the certain point, the content will show up on the stage. But I have no clue how to do that. Hope you could give me some direction. Thanks.

smile,
I'm not sure I understand what you're trying to do.

Hi Matt, Sorry I mean I want to cretae an effect like google map, using slider to control an image zoom in and zoom out. But I have no clude how to do that.

smile,
you can use this for the sliding behavior and then just have the currentValue be the actual scaleX and scaleY of the movie clip. set the minimum and maximum zooms in the method and its that easy.

this is probably a newbie question, so sorry in advance, πŸ™‚
how do i get values from these sliders, say when i slide it to the right, i'd like a trace statement to tell me what its value is and then update a variable with that value

thank so much, your class is awsome!

@matt: you can use sliderInstance.percent if you want the percent or sliderInstance.currentValue which will give you the actual value.

thanks so much!

very nice indeed! I modded it a little bit to add scroll wheel functionality and allowing you to click on the track to make it jump to that point. It is such a super well written class and so customizable! Really really top coding well done!

@Shaedo: Thanks for the kind words. I thought I updated this post with the link to v1.51 but I guess not. Make sure you're using that one for the latest files. added it to this post as well now.

Just some advice,

1) AS3 is not Perl or PHP, stop it.

2) You can improve the quality of your code by making it more self documenting.

@Tony: umm, ok?

@ Tony... Well spotted, As3 != Perl or PHP. Congratulations! go to the head of the class.... and out the door ... yep just keep going .... I tell you when to stop ....

Hi,

Thanks for the class. Works great saved me loads of time πŸ™‚

Chris

[...] SliderUI von Matt Przybylski ist eine Klasse um Schieberegler (Slider) in Flash zu generieren. Somit kΓΆnnen [...]

Awesome! Easiest way to create sliders i could find! Took me 5 minutes to create working sliders for controlling the volume on different sound channels.

Thumbs up!

@Zach: Glad it helped!

How is the range:

this._range = (Math.abs(this._lowVal) + this._highVal);

If you take lowval = 1 and highval = 2 - this would give a range of 3, even though the range is 1 here.

@Rutger: I think the term range is a bit misleading here and I'm not sure why I called it that at the time. I'm looking at the latest version of the class and that code has since changed so I can't really answer that for you properly to be perfectly honest πŸ™‚

Here's what I put in my document class:

package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.Sprite;

public class DocumentClass extends MovieClip {

private var kneeSlider:SliderUI;
private var sliderGrip:SliderGrip;
private var sliderBar:SliderBar;

public function DocumentClass() {

kneeSlider = new SliderUI(stage,"x",sliderBar.slider,sliderGrip.grip,0,2);
addChild(kneeSlider);
kneeSlider.x = 100;
kneeSlider.y = 200;
}
}
}

The sliderBar instance is a SliderBar class which is:

package {
import flash.display.Sprite;
import flash.display.Graphics;
import flash.display.MovieClip;

public class SliderBar extends MovieClip {

public var slider:Sprite;

public function SliderBar() {
// constructor code
slider.graphics.moveTo(0,0);
slider.graphics.lineTo(100,0);
addChild(slider);

}

}

}

The sliderGrip instance is a SliderGrip class which is:

package {
import flash.display.Sprite;
import flash.display.Graphics;
import flash.display.MovieClip;

public class SliderGrip extends MovieClip {

public var grip:Sprite;

public function SliderGrip() {
// constructor code
grip.graphics.moveTo(0,0);
grip.graphics.lineTo(100,0);
addChild(grip);
}
}
}

I'm not sure why I get an Error #1009: cannot access a property or null object reference. at DocumentClass()

I'm a super noob at as3 programming so any help would be great! I see people posted that it's fast and easy to add slider bars but I been trying for 4 hours and nothing. I also note the date of the posts and sorry about the necro.

Matt, I've been using this slider for a few years now. I love it.

However, I've discovered an issue in the way I'm using it, and I've been trying my hardest to figure out why it's occurring. I'm just wondering if you'd be able to point me in the right direction.

Take a look here: http://www.hrtrain.com/2014_v3/preview/index.cfm?course=harass_preview

You will see your slider there at the bottom. All works great.

However, here's the issue:

1. Click on it, hold the mouse button down,
2. While your mouse button is still down, move the mouse outside of the Flash Player area entirely,
3. Release the mouse button

Now bring the mouse back into the Flash Player.

You will see that the slider is reacting as if the user is still holding their mouse button down, no matter where the mouse icon is within the Flash Player. Not that they indeed unclicked outside of the Flash Player.

Any idea what can be done to address this? Essentially, do you know how/if I can run the handleMouseUp function if the user rolls out of the Flash Player entirely while still holding it down?

If you can help, I thank you so, so much. Overall this thing rules. I've used it in a couple of different projects.

Thanks man!
Dan

Leave a comment

(required)

(required)