Flash Essential

Create A Custom Scrollbar In AS3

May 14th 2008
14 Comments
respond
trackback

This is a simple and quick tutorial for creating a custom scroll bar. We'll dynamically load in our text using an array in Actionscript then we'll connect a custom scrollbar. In the files below we have three Movie Clips on the stage, two hands and a square. The two hands will act as our pointers allowing us to gradually scroll up and down. The square will act as our slider allowing us to slide the content up or down as you would do with a normal scrollbar slider.

Here's What We Are Creating

Starter Download:

Finished Download:

Step 1 - Creating Our Text Fields

Open up the Starter File, go to the Actions Layer and press F9 to open up our Actions Panel. We need to create a Text Field and Format the text inside it, so we declare our variables for the Text Field and Text Format, and then give them some basic properties.

var myText:TextField = new TextField();
var myFormat:TextFormat = new TextFormat();

myFormat.font = "Arial";
myFormat.color = 0×333333;
myFormat.size = 24;

addChild(myText);
myText.text = "This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!This is the Flash Essential custom scrollbar tutorial!!!";
myText.setTextFormat(myFormat);
myText.wordWrap = true;
myText.multiline = true;
myText.setTextFormat(myFormat);
myText.x = 100;
myText.y = 100;
myText.width = 300;
myText.height = 200;

Step 2 - Adding Our Mouse Events

Now we add some Mouse Events to our movie clips on the stage. Inside the functions we give our myText text field a scrollV method which means it's scrolling vertically, we then add some math so it reduces the scroll value by one each time its clicked. We do the same for the scrollDown_mc except we use += which adds one to the scroll value every time it's clicked.

scrollUP_mc.addEventListener(MouseEvent.CLICK, upScroll);
function upScroll(event:MouseEvent):void
{
trace(myText.scrollV);
myText.scrollV -= 1;
}

scrollDown_mc.addEventListener(MouseEvent.CLICK, downScroll);

function downScroll(event:MouseEvent):void
{
trace(myText.scrollV);
myText.scrollV += 1;
}

Step 3 - Controlling The Slider

First we'll add our mouse events, you'll notice we add our dropSlider to the stage instead of our slider_mc. This is to stop it scrolling once you have clicked away from the scroll bar.

slider_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragSlider);
stage.addEventListener(MouseEvent.MOUSE_UP, dropSlider);

var bounds:Rectangle = new Rectangle(slider_mc.x, slider_mc.y,0,70);
var dragging:Boolean = false;
function dragSlider(event:MouseEvent):void
{
slider_mc.startDrag(false,bounds);
dragging = true;
}
function dropSlider(event:MouseEvent):void
{
slider_mc.stopDrag();
dragging = false;
}
function checkSlider(event:Event):void
{
//if(dragging){trace("scroll");}
myText.scrollV = Math.round ((slider_mc.y - bounds.y)* myText.maxScrollV/70)
}
stage.addEventListener(Event.ENTER_FRAME, checkSlider);
function textScrolled(event:Event):void
{
slider_mc.y = bounds.y + (myText.scrollV * 70/myText.maxScrollV);
}
myText.addEventListener(Event.SCROLL, textScrolled);

Conclusion

Custom scrollbars can be useful if you want a custom look to your site. If you have a grunge style site the last thing you want is the ordinary scroll bars showing up, so this gives you a chance to create your own. Hope it helps.


This post is tagged , ,



Sponsors

Explore Recent





Monthly Archives



Friends and Affiliates



14 Comments

  1. nate

    my out put keeps saying that my .fla is not a function what do i do?

  2. I looked hi and low for this, but as an xml fed textbox, so I came up with this highbred:

    //Create the URLLOader instance
    var myLoader:URLLoader = new URLLoader()
    //the data will come as URL-encoded variables
    myLoader.dataFormat = URLLoaderDataFormat.VARIABLES
    //Load using an URLRequest, even beeing local
    myLoader.load(new URLRequest("about.txt"))
    //onLoad handler listener
    myLoader.addEventListener(Event.COMPLETE, onDataLoad)
    //Error handling
    myLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError)
    myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError)
    //Could be an error or just a message
    myLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus)
    //add a listener for the complete event
    function onDataLoad(evt:Event){
    Title_txt.text = evt.target.data.Title
    Comments_txt.text = evt.target.data.Comments
    }
    //error callbacks
    function onIOError(evt:IOErrorEvent){
    trace("IOError: "+evt.text)
    }
    function onHTTPStatus(evt:HTTPStatusEvent){
    trace("HTTPStatus: "+evt.status)
    }
    function onSecurityError(evt:SecurityErrorEvent){
    trace("SecurityError: "+evt.text)
    }

    scrollUP_mc.addEventListener(MouseEvent.CLICK, upScroll);
    function upScroll(event:MouseEvent):void
    {
    trace(Comments_txt.scrollV);
    Comments_txt.scrollV -= 1;
    }

    scrollDown_mc.addEventListener(MouseEvent.CLICK, downScroll);

    function downScroll(event:MouseEvent):void
    {
    trace(Comments_txt.scrollV);
    Comments_txt.scrollV += 1;
    }

    slider_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragSlider);
    stage.addEventListener(MouseEvent.MOUSE_UP, dropSlider);

    var bounds:Rectangle = new Rectangle(slider_mc.x, slider_mc.y,0,70);
    var dragging:Boolean = false;
    function dragSlider(event:MouseEvent):void
    {
    slider_mc.startDrag(false,bounds);
    dragging = true;
    }
    function dropSlider(event:MouseEvent):void
    {
    slider_mc.stopDrag();
    dragging = false;
    }
    function checkSlider(event:Event):void
    {
    //if(dragging){trace("scroll");}
    Comments_txt.scrollV = Math.round ((slider_mc.y - bounds.y)* Comments_txt.maxScrollV/70)
    }
    stage.addEventListener(Event.ENTER_FRAME, checkSlider);
    function textScrolled(event:Event):void
    {
    slider_mc.y = bounds.y + (Comments_txt.scrollV * 70/Comments_txt.maxScrollV);
    }
    Comments_txt.addEventListener(Event.SCROLL, textScrolled);

    Works like a champ! Thanks!

  3. miriam

    hello - i tried your script and the following problem appeared: if i use static text (converted into mc of course), the scroller will move, but the text won't. if i use dynamic text (also converted into mc of course), the text will not be displayed at all.
    why is that and how can it be fixed?

    ( i did not create a scripted text field from scratch, i used one from my library. but still, it shouldn't make any difference so long as i have my layers in order and my text converted into movie clips, right?)
    +

  4. Hector

    I can't seem to set the color of the text, it's says that 0×333333 is an error i don't know if you wrote ir wrong but i would apriciate a litle help

  5. bagheri

    hello and thank for your nice tutorial

    in step 1 the first code has a problem

    myFormat.color = 0×333333; must change to myFormat.color = "0×333333″;

    appreciate you

  6. Hello,

    Does anyone seem to have the issue of the slide bar slightly shifting left only after the first click?

    thanks.

  7. vio

    thanks is so good
    i had some, and that is
    the solution

    back here

  8. Yes, I search this since 3 days !!!! I love this tuto, is very so good !!!!

  9. id

    miriam, this will only work for text, don't convet it into a new symbol.

  10. Charles

    Hi! Great code. But is there any line of code to make it continuously scroll up/down when either scrollUP_mc or scrollDown_mc is held down? I know in as2 you can use setInterval, but this is as3 and i am a noob.

    Thanks!

  11. will Adams

    Hi,

    Great tutorial, I just have one problem. I have a few paragraphs of text but working from this code it wont let me use line breaks in the text.

    I keep getting the following error

    1095: Syntax error: A string literal must be terminated before the line break.

  12. gran tutorial….!! gracias!

  13. If you're using this on a dynamically changing textfield, you should kill that "70″ in the update functions and change it to bounds.height.

  14. This is sloppy. Add…

    trace("Updated");

    to the "checkSlider" function and you can see that it continuously polls the checkSlider function. Anyone that cares about CPU cycles should refuse to use this code.

    Your downloadable example is from some out of date version of Flash too.

Incoming Links

Leave a Reply

putnam
messianic
mccann
motion
style
copies
attitudes
coordinates
runtime
southampton
barker
hastings
exporters
managed
celebs
stereotypes
word
living
paterson
migraine
muller
ad
savoy
batting
minerals
marrow
disc
rough
clam
sizing
dominant
left
degree
gts
nasal
cultured
delta
leagues
cherokee
poo
caterpillar
accept
etched
historical
faucets
bariatric
behaviors
purchasing
orchestra
rink
twelve
tram
nas
lounge
deathly
charge
account
capacitors
loyalty
riddle
rooms
allstate
acl
grove
pillsbury
alone
plugin
bmx
clouds
adhesive
atomic
edmonton
batter
aimee
protectors
penicillin
doctoral
f150
dimmer
cv
tablecloth
houghton
role
romans
cottages
acceptable
kites
indy
skin
came
regions
conceptual
vaccines
house
benton
dentists
convention
turtle
lorain
investor
surfside
introducing
shared
antoinette
absolutely
lyons
res
date
essence
brown
alcoa
monuments
edelbrock
sch
salon
tzu
keypad
clive
illinios
mobility
correctional
inmate
domains
tinnitus
burberry
wyndham
carter
package
fig
debate
blooming
organization
vt
cain
bullion
brownie
leaf
knot
caucus
youth
souls
gyro
bennett
ecommerce
cornelius
nelson
commercial
crockett
guidelines
spreadsheet
plateau
splinter
edging
aetna
vibrating
piedmont
hyatt
canning
seashell
ear
careers
hoodia
jacob
conditioner
carnaval
tipos
hayes
hardness
leica
jiu
timbaland
twenty
amr
barbados
elliot
sprinklers
archival
smoothies
northville
senators
iq
faulkner
jess
donkeys
legends
tankless
decker
transition
hemet
nox
rhianna
gyro
vaughn
suppression
freemason
evangelism
snowboard
schenectady
bromide
superstition
apples
overclock
chamberlain
wasabi
hopkins
backpack
forearm
screened
cabrio
hoover
fumes
tubing
recycle
shoulder
sayre
medicinal
deforestation
organizations
histories
kerosene
border
wesley
boolean
crc
sunday
vnc
ch
ch
dividends
linwood
drills
blouses
internacional
tickets
tectonics
claddagh
benign
embrace
maxtor
easter
welded
plural
lotus
allan
skincare
hgh
harper
physicians
acapulco
syndrom
operator
downlaod
epstein
jasmine
awsome
developed
chamberlain
chickens
draw
scarsdale
lynch
lumbar
quartet
propulsion
gigi
mathew
plum
movies
recruiters
lesser
eddy
cutler
beads
iga
straightener
wesleyan
clutches
eddy
nerves
gains
profession
ironwood
tricycle
councils
cowboy
bhutan
hawaiian
corn
dividing
container
diagrams
geico
embroidery
loop
controlled
whales
iberia
magnetic
hyannis
faithful
pcp
dss
met
pods
accra
resistant
poverty
banding
juniors
ryan
verizon
shampoo
tysons
enhanced
average