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

maniacs preachers
1 18 scale aircraft
amy larson attyorney indio ca
coco and ice tee
1 banking golden online
andorra playa de las americas
high perfomance house greencraft
1908 studios
jacqueline and leo perry
12vdc to 9vdc lighter plug
amazon prebook harry potter
dr william rigby
100.5 fm atlanta
riotkayaks.com
la mujer de mi hermano
lyrics to chopped and screwed
christopher plummer i
fireconcepts.com
crowne at razorback
agenda hsie
ab slider
culligan man
a t ireland
slcentral.com
holistic puppy by susie
dr hahn tomball orthopedic surgeons
anthony wayne school and bullying
13799 commerce parkway richmond
celtic masonry in nj
1998 chevy s10 lambo doors
roseanne cash brain surgery
dog sniffing poop
are wood square floors durable
croatian letter writing
black and white dragonballz pics
enzo angiolini sandles
chineese flute
digitalhymnal.org
ala acrl events amp conferences
isafreedom.com
consequences for children
2007 international quilt festival houston
avenues bistro brookside
bert ott
afro american life and history
datetheuk.com
linux logitech quickcam chat
gabrielle carteri pictures
100 compression golf balls
css cursor
advanced health media lose pfizer account
combination traffic and pedestrian railing
aduiepyle.com
2001 pontiac grand am manuals
how tp make a candy bouquet
brown spotting during second trimester
arthritis psoriasis hair loss
bird cronin maternity si belt
mandarin leaf discoloration
guitarimports.com
marginal do rio pinheiros
johnys selected seeds
1986 mazda parts
voaautoauction.org
call of the horned piper
1 4hp stud motor dallas
job software engineer oracle ahmedabad
allied veterans cyber center
nat pmp said
delete file on reboot
advertising is not responsible destroy world
oldworlddistributors.com
atichoke arrangement
santander consumer bank
102.1 the edge dallas tx
1990 audi 100
lampshade bands
cfl vs metal halide
britney spears hot fotos
basis of western institutions
april 2007 frost in mo
cuny nursing schools
afghanistan abduction
african themed ceramic tiles
4chan lists site
gartner 2006 mentoring
dailey news record harrisonburg
art-customer.net
clip movie singapore tammy
balkan pictures archive military photos
arnold chiari ii expectations
cancellations hotline
walkerschools.org
opel 15727
bournemouth international conference centre
applesauce and oatmeal muffin recipe
oregon wic program
business recommendations on disney
account free join
astrology gemstones
buying a car in shanghai
a4 style buttstock for ak
aussie amber
antique needlework pattern
controlling antibiotic induced diarrhea with loperamide
philadelphialiving.com
1980 kawasaki kx 125 gas tank
appliqueing quilts
acc countdown with kix brooks
federated garden clubs of conn
city office riga
19th century wagons
webspheria.org
activities for listening speaking
flagstone floors
aussie gas grill koala
acme boots
spoletousa.org
bale bundles
soccer.ru
c tic tac toe vector
alice 96.7 fresno
gary fackrell hooper
antique finishing furniture
2327 malcolm
travelsdc.com
c c cylinders
aloha aina wellness center
amy buchanan michigan
facilities maintenance soo
amanda macdonald sherwood park
ancient scottish dresses
book of quotations
preplogic.com
waterside holiday park
citgo lite
airline tickets kingston acc fic
hugh jackman michael caine
longs furniture company indiana
apple cider tablets
cabins in pagosa colorado
cca division of taxation
canine lymphoma cure
gleevec.com
cemeteries dartmouth halifax nova scotia canada
animal stacks
duty suppression of fact
frisbee golf washington
venicesuites.com
anglo irish war perspectives
kwik kamp parts
20 facts volcanoes for kids
1999 keystone cabana trailer
muppet closing theme song instrumental
aeroquip distributors in corpus christi texas
1103 silas creek parkway winston salem
shemale-dick.com
bonney lake cao
bridal elegance salon
how to build a sandbox
emma barnum california
news alerts zdnet services companies
blackburn cathedral uk
gbm tumors thc
bluevelvetvintage.com
consumer perception of southwest airline
5 bedrooms lrg lot outside citylimits
a white heron setting jewett
workoutpass.com
schoo closing cadillac mi
handpainted porcelain religious medal
australian composer katy abbott
marisa del portillo feet
1982 honda goldwing gl 1100
argenine citroline vitc vit a
black leather spike dog collar
lyrics sweet tangerine gold
crayon holder
invader zim myspace graphics
alfredo escondon ca
belvedere saugatuck
cd dvd protectors from scratches
bakersfiled brazilian jiu jitsu
2mp ic usb camera chip
armstrong professional thinwall flutes
trillion diamonds in anniversary band
jaymen ooh la lishious
back ground of scooter libby jury
chronicles of narnia review
barbara lahr chambersburg pa
1948 ford f100 truck parts
about ask com binoculars faq
bigtitvideoclips.com
happenings tidewater
dr james alpheus seaman brooklyn ny
australia gdp
2000 ford ranger troubleshoot
acquire shares press release
42 x 42 receiving blanket
dance dance revolution un deux trois
bridgeport barnum festival
cheats for def jam vendetta
gemini love a sagittarius
doncaster interchange
creating excel spreadsheets
canon in d in indie music
pudcat.com
1996 sea-doo spi engines
jennie dugan concord 1805
enlargementgum.com
ally aj potential breakup song lyrics
2 hot twins 2 bang
astronaut space traveler costume
ecc leg cuffs
blanche dubois illusions
1940 s cocktail dresses
bowles indian territory
dogs and hips
cytochrome p450 1a2 enzyme testicular cancer
arctostaphylos uva-ursi point reyes
georges du tam scouts
1960 a time of change
girl killed in hoboken
benedito jos nascimento
bryants poems william cullen bryant
bermuda coco reef
pavillon puebla
pathologist career
ellicott city porcelain fillings
alla and lotr and forums
csrs offset confusion
adelaide dutton
american baby childbirth educator conference
nudewear.com
irritation of the liver
download epsilon 2nd movement
191 cessna plans
gayhardcoreporn.net
linkin park chords faint
athens tech faculty
half price hookers
bayfidan 250 ec
peritoneal cavety
dcr engineering
56k modem hourly transfer rate
cimetidine induced apoptosis
aromatase inhibitor bodybuilding
heel bursa and treatment
buick rainer v-8 reviews
1837 cherokee war 2nd georgia militia
jenni bick coupon
americanfence.com
astrology cancer pisces decendant
albino doberman
buy clothing from hm online
buffalo psychiatric center history
altair advisors
1977 trans am review
natureandscience.org
copiers and air quality
scatkingdom.com
barbara in hebrew
frys eletronic
candlestick cassia
38181 memphis tn
1977 ford brakr caliper brackets
susie orman retirements
a1worldwidelimo.com
army spouse discussion board
desi anju bhabhi mms clips
final fantasy xii gamesharke codes
address find name people
accessing lawsuit risk
choosing a cavalier king charles spaniel
dunbar associated
usfcu.us
greenleaf inc
3ft antenna tripod
quilt-this.com
ed mcmahon next big star
financial advice cambridgeshire
action item sheet
messagebot.com
alfredo baena jr
hd limitation on tc1100
teeny bopper club cindy crawford
breastgirls.com
homestead pools lewistown pa

arkansass democrat gazette classifieds may 2008
at t tilt downloading music
carbon dioxide combustion pe polyethylene
buyuklericin.net
a speech about immortality
invincible 1992 namibia
answers for self evaluations
how to make clothing in morrowind
buy squid beak
jem lyrics 24
bcpassport.com
bally doyle pub downers grove
24 volt lawn mowers
geniimagazine.com
100 greatest villains
l5 s1 herniation loose stools
lowest price on s2 jago
wholesomesweeteners.com
anjelica sinn tennis court mpeg
11 alive news west palm beach
1080 video fireplace
used yanmar vermont
bamboo camouflage boot
dui defense plea
date palm phoenix dactylifera taxonomy
blue da ba dee eiffel 65
alternativa grupo
cbscompanies.com
1965 churchill token
lombardi inn oh
skoar.com
aar comments for presentations
100 ways to praise a child