Flash Essential

Create A Custom Scrollbar In AS3

May 14th 2008
15 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



15 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.

Leave a Reply

auto battery discharge cold
blake holman sioux falls sd
ameican pitbull terrier
character story elements powerpoints
construct a wheelchair ramp
paralysis.org
bangladesh orphanages
2000 lb bomb
kristi rowley
concrete acid etching supplies
bossier city la real estate
bedford indiana job openings
cordura bags 2008 hayabusa
hana kimi direct downloads
07 tahoe lug pattern
stroke-jobs.com
2008 satilite map
arctic zone lunch bag
04 g35 body kit vader 3
blackpool town fc
reserved sugar
animal control in evansville
1927 roadster
myspacelayouts.net
cast costumes for hello dolly
art for the heart fundraising
treesforyou.org
agape gaddis
1080p 24 lcd monitor
etymotic.com
article about dpms lr 308
27713 nc zip code
boo creepy foot doctor
convicted offenders listed in british columbia
daybed covers toile
job predict
butas sa pinto silipan
0 andreas test residence
foxpro serial port fll
dr natura and oldest man
2000 mercury sable too lean
frozen liquid longest
2003 exotic spices calendar
1 bedroom suite orlando
1 2 inch vinyl micro blinds
colleges that teach veterinarian toxicology
dieter klimm germany
3 cm dialated
captain william fowler
mmahq.com
1st lady on my
ancient mayan popol vuh
pinky and the brain avatar
claire pruitt doll patterns
xbux.com
av 2009 virus blocking malware bytes
2002 mountain aire 4097 floorplan
emeritus restraint policy
arizona diamond backs fan club
ftd florists oneida ny
courier service pretoria rundu luanda
insane clown posse downloads
bello pr-25 review
4 bedroom rental in yorba linda
5 estacion flores de alquiler video
americus vespucius
ati modified driver vista 32
adoption paralegal in toronto
dish pvr 501 mod
1800 daniel brothers in tn
irony.com
dominant bodybuilding females
custody911.com
adm buyout
alex moulton mark 1
hughesspeednet.com
byron hinton
shoehunting.com
experiment on rl circuit
1296 mhz power amplifier circuits
7th level of hell survey
constitutional class
anemia and skin itch
goofy gold download
webshapes.org
car jacks 3.5 ton costco
neopostinc.com
brookfield athletic shoe company inc
cause transaction lagging bank reconciliation
fire at mann gulch
ambridge duck hunting
application coding wikipedia
12 1 2 womens cowboy boot
cci cb short
before the hammer strikes the nail
interpretation of low oxygen saturation
autosearch.com
outrigger condos
carl erickson pole vault camps
matchmaker pittsburgh pa
cheats gba pokemon emerald
and eminem forgot about dre
howtomaketime.com
andorra property
1939 indian scout timing specs
diet plans for chronic indigestion
applied kinesiology for hiatal hernia
read socrates in love online free
nutone-home.com
air europa seating arrangements
8 configuration sacral fracture
assfucked to tears
alto sax 575 allegro
geological features in the appalachians
bill clinton comment obama
addicting games territory war
irc mythos cx slick 700x42c
msn messenger signup
kissed his feet bet
apache2 debian etch amd64
bnvillage.co.uk
do horses have treat preferences
10mb network
cantv.net
noel chance racehorse winners at warrick
cmu waterproofing techniques
brenda adams bebo
1967 ford shelby mustang pics
charlotte witt
13th century mens clothing france
embassyhomepage.com
blood draining out nasal passages
sprinklerfitters669.org
stephan a rhodes
cemeteries in holyoke ma
gallstone purge
emma tryon
amboy washington mptels
branson ultra sonic cleaner
anti-tank obstacle
chris mcgee
auto dealers mit
belle meade united methodist
hotel regent paris
smdailyjournal.com
1995 ford f150 sputters on acceleration
dan sommer in omaha nebraska
academy of our lady chicago il
accrual method 12 month membership
1941 luger manufacturing plants
curry mussels
construction-business-forms.com
gym clothing catalogues in south africa
american portrait painter a jacobsen
hotels in patagonia
but seriously folks joe walsh
address of lima polo club
william butler yeats home address
another instance of voice platform genesys
bonney m stille nacht
former french canadian provinces
creole echoes excerpt
seekingxxx.net
gods goddesses
100 reason stop smoking
all-about-style.com
andre d sparks
map of the westward expansion
examples of meta search engines
aluminum sliding glass door lock
brattleboro vermont nakedness
2008 norton update problems
betty joyce harrison
panasonic.net
7th grade science dothan al
clearwatertribune.com
age of consent in nc
nineteenth century cultural stereotypes
smt contract manufacturing at elgin il
20mn.com
avian immune
arresting or reversing foot neuropathy
citalopram actavis pirist v l ke
netinfo.bg
1929 cadillac imperial
mikesradioworld.com
anatomical mold
12 days of christmas gift ideas
asx-200bx lan
gaydadsandyoungersons.com
isabella fiore let love reign purse
allow interactive logon to workstations
computer sent received meter
amicroe ready boost usb drive
augustinespiritualgoods.com
basilica di bologna
cj fitzgerald
chicks in sturgis
buenos aires art supplies
password protect folder sme server
australia port fairy accomodation
chantal hensley
ariston dishwasher
2009 liturgical year
soundproofwindows.com
absent cells on pap
gold rush miners in california 1852
content for newsletters
academy countdown leader
craaigslist.com
air race reno 2007
pdfsoftwarecenter.com
desert crepes
battlefield 1942 home page
assignments on employee made by organisations
a taste of thai instant meals
custom stainless products etobicoke ontario
a w d hammond ltd website
frcp exemptions
albums released in 1989
2wire router problem wii
amanda marie gould
greek writing utensils
child abuse coppell texas
snappysoftware.com
jillian barberi
keeler hydraulics
install fedora on mac powerbook g4
exoticagirls.com
cakewalk music creator crossfader
cats beta carotene treat tylenol toxicity
norterrashopping.com
american culinary wagner ware wholesale
belinda jensen autobiography
ben hogan golf tips
concave and convex
antelope complex fires in the west
alan dresner and natalie
bluetooth setting cingular t616
adolf hitlars childhood
endorsement for your friend
artificial intelligence checkers
albright on ot phoenicians
label stuck in tde laminator
aimpoint style reflex sight
brook skye video
contemporary perspectives in writing
acmediy.com
franconia sami fakhouri
custom shower curtains with longer lengths
sacramentorealestatevoice.com
express scribe dss problems
air travel carry on rules
abraham lincoln association
bilingual baptist minister indianapolis in
atomic absorption spectrometry free book welz
bacon club t-shirt at journeys
1700 hemlock oxnard
a little pain tabs nana
40th birthday rhymes
ahadees.com
brookside equestrian centre kitchener
adanal roofing langley bc
h clinton supporters
burning crusade
1760 59th avenue sacramento ca 95822
atkins beach diet south vs
bible xml
elder david pennington
1903 legare circular sock machine
asparagus baked wine
1911 22 rimfire conversions
191 2nd avenue cochrane ontario
agatha christie novels online
american pledge
bellcad.org
circut city rebates
crater lake green outcropping
condos townhouses new bern nc
download stairway to heaven
bed robe
adobe epic app cannot be launched
11x17 4c process preliminary poster examples
daytime emmy award talk show
burley samba
char-broil rotisserie
adoro las es liebe sein
homosexuality umass amherst
100 cc suzuki sv
birch carrol cinema townsville
1973 firebird radiator support
sandia memory gardens
probeindustries.com
fumani dialect
nacelink.com
avalon title ltd mclean virginia
farwestfamilyservices.com
antwerp cut diamonds
dino van eeckhaut cairo appointed sofitel
dosha.org
2008 sport touring
bleeding doge truck breaks
johnnycrosslin.com
24071 desert drive florence az 85232
bioclusive overlay
areas effected in 2007-2012
geography hottest part of the world
aikenregional.com
antarctic centre new zealand shop
coupons for amazon purchases
add affiliate link program
alicia keys samsonite man
saltlaketribune.com
accessory lady
aboutlilacs.com
banner insurance rockville md
elvi fashion stockists uk
federal govt
nalco.com
ankle fracture lower extremity
beloved sisters mc
alisha lanier
cindy ziegler re max of wasilla
32 degrees mesa watch
beat the clickbank competitors
audi a4 fuse changing
adjusting bernina 1001 bobbin tension
australian olympics bike riders
cheap las vagas limos
pulmicortrespules.com
1611 bosch power tool parts breakdown
12 ci engine hp
articles about human resource managment
cal state university pomona anthropology
buses into motorhomes
international tae kwan do karate federation
ana and muscle antibody
dav pilkey biogrpahy
12 week old boxer puppy photos
5 interesting facts about scallops
darnell crisconi
foxfire banjo
4gazebos.com
research terrestrial orchids
cloudster.com
allergic reaction to dust
hickoryortho.com
lexis nexus herb
milky cat torrent
comprehensive-kidney-facts.com
b strep symptoms
07 ford mustang gt
waterfrontbluesfest.com
antique wardrobe trunk pricing
banana fana fo fana
856 edi invoice