Sei sulla pagina 1di 75

Modern Javascript

Lesso n 1: Int ro duct io n


Ho w to Learn using O'Reilly Scho o l o f Techno lo gy Co urses
Understanding the OST Learning and Wo rk Space Enviro nment
Using the Co deRunner® Edito r
Saving and Retrieving Yo ur Page
Previewing Yo ur File

Yo u're Ready to Go !

Lesso n 2: Int ro duct io n


Abo ut Javascript
JavaScript is no t Java
Java
JavaScript
Lo o king Ahead...

Lesso n 3: Re cycling J avaScript s


Using Javascript Scripts
Number 1: The Script Itself
Number 2: The Event
Number 3: The Related Objects
Number 4: Co pyright Infringement
Custo mizing the Script

Lesso n 4: Eve nt Handle rs


Event Handlers

Lesso n 5: Int ro duct io n t o Script ing


Intro to Scripting
Yo ur First Script
An Intro ductio n to Metho ds

Lesso n 6 : Me t ho ds and Variable s


Metho ds and Variables
Metho ds
Variables

Lesso n 7: Me t ho ds

The windo w Object


The o pen Metho d
The fo cus Metho d
The do cument Object

Lesso n 8 : Pro pe rt ie s and t he Do cum e nt Obje ct Mo de l


The Do cument Object and Its Pro perties
The Do cument Object Mo del

Lesso n 9 : Do cum e nt Obje ct Me t ho ds: ge t Ele m e nt ById

The Style Object Pro perties


Changing Pro perty Values

Lesso n 10 : Funct io ns

Using Multiple Functio ns


Functio n Parameters
Multiple Parameters

Lesso n 11: Ope rat o rs


Operato rs in Javascript
The Arithmetic Operato rs
The Assignment Operato rs
Co mpariso n Operato rs

Lesso n 12: T he if St at e m e nt
The if Statement
Lo gical Operato rs

Lesso n 13: Fo r and While Lo o ps


fo r and while Lo o ps
The while Lo o p
The fo r Lo o p
Nesting Statements

Lesso n 14: Obje ct Arrays


Arrays
do cument Object Co llectio ns
The fo rms Co llectio n
table Co llectio ns and innerHTML

Lesso n 15: Arrays


Mo re Arrays
Building Dynamic Select Bo xes

Lesso n 16 : Ope rat io ns wit h No de s

Intro ductio n to No des


Creating and Manipulating Elements
Wo rking with tables

Lesso n 17: Cre at ing J avascript Me nus


Javascript Menus
The Script

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Introduction

How to Learn using O'Reilly School of T echnology Courses

Because yo u are taking the JavaScript co urse, we assume that yo u already kno w HTML. If yo u need a
Note refresher, feel free to email yo ur mento r at le arn@ o re illyscho o l.co m fo r info rmatio n abo ut the O'Relly
Scho o l o f Techno lo gy (OST) HTML co urse.

To learn a new skill o r techno lo gy, yo u must sit do wn and experiment with the techno lo gy. The mo re experimentatio n
yo u do , the mo re yo u learn. Our learning system is designed to maximize yo ur experimentatio n and help yo u le arn
ho w t o le arn the techno lo gy. Here are so me tips fo r learning:

Le arn in yo ur o wn vo ice --Wo rk thro ugh yo ur o wn ideas and listen to yo urself and take o wnership o f yo ur
new skill. We avo id lengthy video o r audio streaming and keep spurio us animated demo nstratio ns to a
minimum, because we kno w yo u'll learn mo re and better by practicing.
T ake yo ur t im e --Learning takes time -- rushing thro ugh wo n't help yo u learn. By taking yo ur time to try
new things, yo u'll disco ver mo re than yo u (o r we) ever imagined.
Cre at e yo ur o wn e xam ple s and de m o nst rat io ns--In o rder fo r yo u to understand a co mplex pro blem,
yo u must understand its simpler parts. Fo r this reaso n, yo u'll build each demo nstratio n piece by piece
yo urself, fo llo wing o ur guidance.
Expe rim e nt wit h yo ur ide as and que st io ns--Wander fro m the path to see what's po ssible. We can't
po ssibly anticipate all o f yo ur questio ns and ideas, so yo u must experiment and create.
Acce pt guidance , but do n't de pe nd o n it --Try to o verco me difficulties o n yo ur o wn. Go ing fro m
misunderstanding to understanding o n yo ur o wn is the best way to learn. It's ho w yo u LEARN HOW TO
LEARN. Our go al is to make yo u independent o f us. Of co urse, o ur instructo rs are here to help in extreme
cases.
Do REAL pro je ct s--Real and live pro jects, as o ppo sed to simulated o nes, are mo re rewarding and
challenging. They help to ensure that yo u learn what's invo lved in real-wo rld situatio ns. Our Learning
Sandbo x is built aro und a real develo pment to o l fo r do ing real jo bs. We'll give yo u pro jects to do in the
o bjectives and quizzes fo r each lesso n.

Understanding the OST Learning and Work Space Environment


Since this may be yo ur first OST co urse, it's impo rtant fo r yo u to be intro duced to the Le arning Sandbo x learning
enviro nment. Belo w is the Co de Runne r® Edit o r, which will serve as yo ur wo rkspace fo r experimenting with co de we
give yo u, as well as yo ur o wn ideas. Co deRunner is a multi-purpo se edito r that allo ws yo u to create applicatio ns in
many techno lo gies. One o f the techno lo gies that Co deRunner will enable yo u to create in is HTML.

All o f the co mmunicatio n to o ls and learning co ntent go es in the upper part o f the screen, as yo u can see. Frequently
we will ask yo u to type co de into the Co deRunner Edito r belo w and experiment by making changes. When we want yo u
to type co de o n yo ur o wn, yo u'll see a white bo x like the o ne belo w with co de in it (in this case it is no t necessary to
type the suggestio n):

Type the fo llo wing into Co deRunner belo w:


We'll ask you to type code that
occurs in white boxes like this into CodeRunner below. Every time you see a white b
ox like this,
it's your cue to experiment.

Similarly, when we want yo u to "o bserve" so me co de o r result, we will put it in a gray bo x like this:
Observe the fo llo wing:
Gray boxes like this will be used for observing code. You
are not expected to type anything from these "example" boxes.

Since Co deRunner is a multi-purpo se edito r, yo u'll need to use the co rrect Synt ax. In this co urse yo u will o nly be
using HT ML Syntax. The Syntax menu lo o ks like this:

Thro ugho ut this co urse we will give yo u mo re tips fo r using the learning enviro nment as needed.

Using the CodeRunner® Editor


This is an OST Learning Lab, where yo u learn by trying the suggested lesso ns and experimenting o n yo ur o wn. In
these labs, yo u'll script fo r the web and make yo ur very o wn webpages using the Edito r belo w. Let's take a clo ser lo o k.

In the bo tto m half o f the windo w, yo u sho uld see the Co de Runne r® Edit o r. In the space pro vided, please type
"HELLO WORLD." Be sure that HT ML is selected fro m the dro p-do wn menu.

Type the fo llo wing into the Edito r belo w:


HELLO WORLD

Saving and Retrieving Your Page


Let's practice saving yo ur page o n the OST server. Go ahead and click o n the butto n. Cho o se a name fo r
yo ur file and type it in the Save As text bo x. Yo u also need to include the html extensio n (.html) o r the bro wser
wo n't kno w to treat yo ur co de as html.

Yo u sho uld also practice using the Save as butto n to save ano ther versio n o f yo ur file.

Pretty easy, eh? After successfully saving yo ur file, anybo dy can go o n the web, type the URL
(http://yo urusername.o reillystudent.co m/myfilename.html) in the lo catio n bar o f their bro wser, and see this
page.

To retrieve yo ur page click simply click o n the Lo ad File ico n o r do uble-click the file name in the File
Bro wser windo w at the left.

Previewing Your File


After yo u type "HELLO WORLD", click o n the Preview ico n, which lo o ks like this:

The first thing that happens when yo u Preview a file is that Co deRunner checks to see whether this file has
been saved previo usly. If it has, the page will be saved with the same name. If no t, the Save File windo w will
o pen.

Keep in mind that every time yo u Preview a file, yo ur changes will be saved. Think abo ut whether
Note
yo u want the previo us co de o verwritten o r no t. If no t, use File Save As befo re yo u Preview.

Once the file has been saved, ano ther bro wser windo w o r tab sho uld o pen and sho w yo u yo ur first web page.

You're Ready to Go!


At this po int yo u sho uld be co mfo rtable using the Preview butto n and with saving and retrieving yo ur files. Yo u're go ing
to use this a lo t, so if yo u feel like it wo uld help, go practice it a co uple mo re times.

Thro ugho ut the rest o f these learning labs, whenever I want yo u to type so mething into yo ur do cument, I'll put it into a
white bo x. When I just want yo u to lo o k so I can sho w yo u so mething, I'll put it into a gray bo x. Yo u'll pro bably want to
save yo ur page after each lesso n so yo u can go back and get it later, but that's up to yo u.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Introduction

About Javascript
JavaScript, as a language, is mo re co mplex than HTML. While HTML is a markup language, JavaScript is a
pro gramming language. If yo u're no t familiar with pro gramming languages, JavaScript might be a bit co nfusing at first.
There are many "wo rds" in this language. If yo u try to memo rize each "wo rd" yo u see thro ugho ut the lesso ns, yo u
may feel o verwhelmed. Instead, co ncentrate o n learning things like:

o bjects, metho ds, and pro perties, and ho w to refer to them.


when to utilize event handlers.
the syntax fo r writing functio ns.

Armed with this kno wledge, yo u'll be able to understand the JavaScript language, even if yo u do n't necessarily kno w
every "wo rd." This is the same philo so phy we used in the HTML class; we didn't co ver every available tag, but instead
empo wered students with the kno wledge o f ho w tags wo rk and the right to o ls to be co mfo rtable learning new o nes as
needed.

All o f the examples, quizzes, and o bjectives fo r this co urse sho uld be co mpleted in the Sandbo x. If yo u
Note have never taken an OST Pro gramming co urse, please click here to learn abo ut the different features o f
this to o l.

JavaScript is not Java


Okay, so yo u've decided to learn JavaScript. Great! At this po int, yo u pro bably do n't kno w to o much yo u
abo ut it tho ugh, at least beyo nd its general usefulness fo r web pro gramming. Befo re we dive into Javascript
tho ugh, let's go o ver the differences between JavaScript and Java.

JavaScript and Java are bo th widely used in web develo pment. Because their names are so similar, yo u
might assume that they are o ne and the same, but that's no t the case.

Java
Yo u may be familiar with Java Applets (pro grams written in Java that can o nly be run in a bro wser) o n web
pages, but applets represent o nly a small po rtio n o f the capabilities o f the Java language. Java was o riginally
develo ped to be used as a pro gramming language fo r things like wo rd pro cesso rs, calculato rs, car
co mputers, watches, PDAs (Perso nal Digital Assistants), and micro waves. One o f the go als the creato rs o f
Java had was to create a language that co uld be used by multiple platfo rms, like tho se I just mentio ned. In the
pro cess o f develo ping this language, pro grammers fo und that Java was great fo r the internet as well, and
wo rked with a wide variety o f platfo rms fo und there (UNIX, Windo ws, Macinto sh, and so o n).

Java is based o n C++, the language currently used mo st by so ftware develo pers. The creato rs o f Java
inco rpo rated the best qualities o f C++, while getting rid o f the wo rst (like po inters...ugh!).

Java is an Obje ct -Orie nt e d (OO) language, which means that yo u wo rk with o bjects o f so me type and
apply actio ns to them. This is in co ntrast to pro cedural pro gramming where yo u apply o bjects to so me
pro cedure. (If yo u have a pro gramming backgro und, yo u're pro bably aware that my definitio n is pretty
co ndensed, but it will help us to co ntrast Java with JavaScript later.)

Java is also a co m pile d language, which means that the pro gram is written in text, then co nverted to a
co mputer pro gram (which yo u can't read) when it's executed.

JavaScript
JavaScript has no thing to do with Java. JavaScript, o riginally created by Netscape, is po rted to Internet
Explo rer as J Script . It is a language devo ted to enhancing HTML. Because it can be used to impro ve design,
create interactive webpages, and create co o kies, it is the mo st po pular scripting language o n the internet.

JavaScript is an Obje ct -Base d language; it uses many o f the co ncepts o f OO pro gramming, but it's no t
co mpletely Object-Oriented.

JavaScript gives yo u (the pro grammer) mo re co ntro l o ver yo ur webpage. Java simply uses the do cument as
an enviro nment fro m which to run applicatio ns.
JavaScript is an int e rpre t e d language, meaning it is written and executed as is. Unlike Java, no special
pro gram is needed to co nvert JavaScript befo re the bro wser can understand it.

Looking Ahead...
So , we've to uched o n the basics abo ut the o rigins and go als o f JavaScript. By the time yo u've finished this
co urse, yo u'll be able to apply the po werful abilities o f JavaScript to yo ur o wn do cuments. What kind o f stuff
will yo u be able to do ? Well, just take a lo o k at this example belo w. After wo rking thro ugh the co urse, I'm
co nfident yo u'll be able to create so mething like this and a who le lo t mo re:

OST Tic Tac To e

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Recycling JavaScripts

Using Javascript Scripts


Yo u do n't need to kno w anything abo ut JavaScript in o rder to start using it o n yo ur page. Yo u can recycle scripts
written by o ther peo ple.

Here's a case scenario : yo u're surfing the internet and yo u co me acro ss a web page that do es so mething interesting
using JavaScript. Yo u think to yo urself, that would look great on my web page! Yo u're sure yo u can replicate the HTML
tags that are wo rking with the script, but yo u do n't kno w anything abo ut JavaScript. No pro blem! To recycle scripts fro m
o ther web pages, yo u need to kno w just these f o ur things:

Number 1: T he Script Itself


First things first -- yo u need to kno w where to get the script. JavaScripts are always placed within script t ags
and may be placed within co m m e nt t ags as well. Here's a typical script:

OBSERVE:

<script type="text/javascript">

<!--

function displayTime(){

var date = new Date()


var hours = date.getHours()
var min = date.getMinutes()
var sec = date.getSeconds()

document.getElementById("myText").value=hours+":"+min+":"+sec

setTimeout("displayTime()",500)
}

//-->

</script>

In the abo ve example, the script t ags are re d and the co m m e nt t ags are blue .

The co de between these tags co mpo ses the script itself. The scripts are o ften lo cated in the head o f the HTML
do cument, but they can be just abo ut anywhere. The co de co uld seem like a fo reign language to yo u right
no w. Do n't wo rry! We'll discuss it in detail later. Fo r no w, I just want yo u to reco gnize that this is the script. Yo u
wo uld need to co py all o f this co de into yo ur HTML do cument in o rder to recycle it. It's a go o d idea to place it
in the same sectio n yo u fo und it. In o ther wo rds, if it was in the head o n the o riginal page yo u're bo rro wing
fro m, put it in the head o f yo ur page as well.

If yo u see a web page that's using JavaScript and yo u want to recycle it, mo ve yo ur mo use o ver the page and
click the right mo use butto n. A list will appear. Select Vie w So urce fro m the o ptio ns in the list to see the
co de used to generate the page. Then try to lo cat e t he script , then co py and paste it into yo ur do cument.

Let's give that a try. Lo cate a script and co py it into yo ur HTML do cument. Click here!

Number 2: T he Event
No w we'll adress the co mpo nent being used to make the script go ! It's called an e ve nt handle r. Yo u do n't
need to kno w to o much abo ut event handlers in o rder to recycle them. (We'll go o ver event handlers in greater
detail in a future lesso n.)

Event handlers are always lo cated within HTML tags, usually within bo dy, input , o r ancho r tags. Event
handlers specify when and why the bro wser sho uld execute a script.

Even if yo u aren't familiar with specific event handlers, there is a reliable way to lo cate them. First, find the
functio n (yo u'll learn abo ut these later) that co ntains the script yo u want to use:
OBSERVE:
<script type="text/javascript">

<!--

function displayTime(){

var date = new Date()


var hours = date.getHours()
var min = date.getMinutes()
var sec = date.getSeconds()

document.getElementById("myText").value=hours+":"+min+":"+sec

setTimeout("displayTime()",500)
}

//-->

</script>

The name o f the f unct io n is displayT im e . We are able to identify it because the wo rd displayT im e fo llo ws
the wo rd f unct io n.

Once yo u find the functio n name, check o ut the bo dy o f the HTML do cument. Inside the tags, yo u'll find
so mething that lo o ks like this:

o ne ve nt =" f unct io nNam e ()"

In this example, the event handler is lo cated within the bo dy tag. It lo o ks like this:

OBSERVE:
<body onload="displayTime()">

Ano ther helpful way to lo cate event handlers is to be aware that they begin with the wo rd "o n."

Click here to see the page yo u lo o ked at befo re. Vie w So urce o n the page and see if yo u can lo cate the
event handler that starts the script. Co py and paste it into yo ur HTML do cument (in the same place that
co rrespo nds to where yo u fo und it o n the o riginal do cument).

Number 3: T he Related Objects


The script that yo u are recycling displays the time in a text field, so yo u will have to create a text field in yo ur
HTML do cument where the time can be displayed as well. Yo u must repro duce the o bject e xact ly as it
appears in the do cument fro m which yo u are recycling the script. The co de to create this particular text bo x
lo o ks like this:

OBSERVE:
<form>
<input id="myText" />
</form>

Failure to repro duce the co de exactly as it appears o riginally, co uld cause the script to run inco rrectly o r no t at
all.

See if yo u can recycle this script. Be sure to co py all necessary co mpo nents!

Number 4: Copyright Infringement


So no w that yo u have this info rmatio n at yo ur fingertips, yo u can expo lit all o f tho se who came befo re yo u by
recycling their Javascript scripts and using them yo urself, right? WRONG! Yo u sho uld never take a script
witho ut asking. Sure, it's likely that no o ne wo uld ever kno w, let alo ne co mplain, but it's always a go o d idea to
ask the script o wner fo r permissio n and avo id any co mplicatio ns.

Often, info rmatio n regarding allo wable usage, perso ns to co ntact in o rder to request permissio n, o r o ther
co pyright info rmatio n is included in the script itself and is co mmented o ut.

Customizing the Script


So no w yo u can recycle a script "as-is" fro m so meo ne else's web page. It's also po ssible to custo mize
scripts to suit yo ur o wn needs. See if yo u can figure o ut ho w to use the scripts in this lesso n to display yo ur
o wn perso nal message instead o f the messages currently displayed.

Surf the web a bit and see if yo u can find so me JavaScript to recycle and custo mize!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Event Handlers

Event Handlers
In this lesso n yo u'll create an interactive web page that will allo w visto rs to yo ur page to perfo rm an actio n (o r e ve nt )
that will cause so mething to happen o n the screen. Mo ve yo ur curso r o ver the image belo w to see an example o f that:

Eve nt s allo w yo u to create web pages that will respo nd to input by visito rs and are part o f what makes JavaScript so
fun and po werful!

Co py and paste the script belo w into the Edito r. We'll be using this script thro ugho ut the rest o f this lesso n. Do n't panic
if yo u do n't understand the script—yo u're no t suppo sed to yet!

Keep in mind that every time yo u Pre vie w an html file, yo ur changes will be saved. If yo u do n't want yo ur

Note previo us co de o verwritten, think abo ut using Save As befo re yo u Pre vie w. Yo u can use the Go

Back ico n to retrieve previo us versio ns even after yo ur file has been saved, if necessary.

In HTML mo de, type the co de belo w into the Edito r:

CODE TO TYPE:

<html>
<head>
<script type="text/javascript">
<!--

function rollon(){
document.getElementById("myImage").src="http://courses.oreillyschool.com/javascript1/im
ages/zap.gif"
}

function rolloff(){
document.getElementById("myImage").src="http://courses.oreillyschool.com/javascript1/im
ages/pow.gif"
}

//-->
</script>
</head>

</html>

Okay, no w that yo u have the script, let's get back to o ur discussio n o f events. Events make things happen. We're go ing
to add so me HTML to the script. The HTML we add will include e ve nt handle rs to allo w interactio n between the HTML
and the script.

Fo r the rest o f this lesso n, be sure that the script remains unchanged. This includes everything between
Note the <script> and </script> tags. Any changes yo u make will be applied to the bo dy o f yo ur do cument.

In HTML mo de, type the fo llo wing co de just belo w the clo sing head tag in yo r Edito r:
CODE TO TYPE:
<body>
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" onm
ouseover="rollon()" />
</body>

Click Preview. When yo ur do cument co mes up, mo ve yo ur mo use o ver the image that is displayed. Pay clo se
attentio n to what happens. Do es the image change? If no t, go back and try it again.

When yo u mo ve yo ur mo use o ver the image, an event is triggered, causing the image to change. Take a clo ser lo o k at
the co de:

OBSERVE:
<body>
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" onm
ouseover="rollon()" />
</body>

When yo u mo ve the m o use o ve r the im age , the ro llo n functio n is executed.

o nm o use o ve r is the e ve nt handle r. No tice that o nm o use o ve r is used as an attribute o f the im age t ag, just like
the src attribute. The event handler is set equal to the actio n that sho uld take place when the event o ccurs. In this case,
when the mo use is mo ved o ver the image, the ro llo n functio n is executed. This functio n is defined within the script
tags. Yo u'll learn ho w to create yo ur o wn functio ns later in the co urse. Altho ugh there are many types o f event
handlers, they're all used within HTML tags. Certain event handlers that can be used within certain HTML tags. At the
end o f this lesso n, there's a table that lists all o f the po ssible co mbinatio ns.

No w that yo u kno w a little so mething abo ut event handlers, we'll have so me fun! In HTML mo de, replace the bo dy o f
the do cument with this co de:

CODE TO TYPE:
<body>
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" onm
ouseover="rollon()" onmouseout="rolloff()" />
</body>

Click Preview. Mo ve yo ur mo use o ver and o ff o f the image this time. Pay clo se attentio n to what happens.

When yo u mo use o ver the image, the same thing happens as in the previo us example. When yo u mo ve yo ur mo use
o ff o f the image tho ugh, it changes back to the o riginal image. This is do ne using a new event handler called
o nm o use o ut . o nmo useo ut is also used within the image tag; it's triggered when the mo use leaves the image.

No w that yo u're familiar with events used in the image tag, let's talk abo ut a special type o f event. Mo st events begin
with o n, but there is o ne that do esn't. This event can o nly be used within the ancho r tag.

Whenever yo u select a link o n a web page, yo u're actually triggering an event. The event causes the web page
specified with the href attribute to appear. Instead o f setting the href attribute equal to a URL, try using it to call a script. In
HTML, replace the bo dy o f the do cument with this co de:

CODE TO TYPE:

<body>
<a href="javascript:rollon()">
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" />
</a>
</body>

Click Preview. When the page co mes up, click the image and see what happens.

Yo u sho uld have seen the image change. Let's analyze the syntax:
OBSERVE:
<body>
<a href="javascript:rollon()">
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" />
</a>
</body>

When yo u click o n the im age , the J avaScript functio n called ro llo n is executed.

The o nly difference between this ancho r tag and a "no rmal" ancho r tag is that the hre f attribute is set equal to a
J avaScript functio n. The specific functio n is listed after the co lo n (:), which allo ws yo u to execute JavaScript using the
natural clicking event o f the ancho r tag. In o ther wo rds, the event yo u wish to execute is triggered when the link is
clicked. All o f the co mmands necessary to execute the desired co mmand are lo cated within the link rather than the
URL.

Let's see events in actio n with a different HTML tag. In HTML, replace the bo dy o f the do cument with this co de:

CODE TO TYPE:
<body>
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" />
<form>
<input type="button" value='Click Me' onclick="rollon()" />
</form>
</body>

Click Preview. This time yo u sho uld see the image change when the butto n is clicked.

o nclick is an event that can be used with a but t o n. When yo u click the butto n, the event is triggered, causing the
ro llo n functio n to be called.

In HTML, type the fo llo wing into the Edito r belo w:

<body>
<img src="http://courses.oreillyschool.com/javascript1/images/pow.gif" id="myImage" />
<form>
<input type="text" size="20" onFocus="alert('You focused the text field!'); this.blur()
" />
</form>
</body>

Click Preview. Yo u'll see a text field. When yo u click in the text field, it is bro ught into fo cus, thereby triggering the
o nFo cus event. The result is that an alert message appears.

What do yo u suppo se t his.blur(); do es? Blur is the o ppo site o f fo cus. Fo cus means to bring an o bject into view. Blur
means to take an o bject o ut o f view. When yo u take the text field o ut o f fo cus, yo u get stuck in a lo o p o f alert
messages. Take t his.blur o ut o f yo ur co de and click PREVIEW.

Yo u've learned a lo t abo ut events in this lesso n! Yo u can click here fo r a list o f events and the types o f HTML o bjects
that yo u can use with them.

See yo u in the next lesso n!


Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Introduction to Scripting

Intro to Scripting
By no w yo u kno w quite a bit abo ut JavaScript. Yo u kno w abo ut the o rigins o f JavaScript, the basics o f recycling
JavaScripts fo r yo u o wn use, and ho w to use event handlers to call tho se scripts. No w yo u're ready to begin writing
yo ur o wn scripts!

Your First Script


Let's start with a basic script that will write text to a web page. This type o f script is referred to as st at ic
because it always do es the same thing. It requires no event handlers; instead, it's executed when the web
page is lo aded by the bro wser.

In HTML mo de, type this co de into yo ur edito r:

CODE TO TYPE:

<html>
<body>

</body>
</html>

Click Preview. Yo u'll see a blank web page. We'll use JavaScript to write text to this blank web page. In HTML,
type this cde into the Edito r:

CODE TO TYPE:
<html>
<body>

<script type="text/javascript">
<!--
window.document.write("Here is some text")
//-->
</script>

</body>
</html>

Click Preview. Yo u sho uld see a web page displaying the text He re is so m e t e xt . Co ngratulatio ns, yo u have
just written yo ur first script!

When including a script within an HTML page, yo u m ust enclo se yo ur scripts within script t ags. These tags
give the lo catio n o f yo ur script to the bro wser. The t ype =" t e xt /javascript " attribute indicates that the text
within the script tags sho uld be interpreted as JavaScript.

Yo ur script sho uld also be enclo sed within co m m e nt t ags. These tags hide the script fro m o lder bro wsers
that do n't suppo rt JavaScript. Altho ugh mo st bro wsers do suppo rt JavaScript, it's still a go o d idea to get into
the habit o f including them. These tags can also be used to include co mments abo ut yo ur co de, which can
help yo u to edit yo ur co de at a later date.

The line o f co de between the script and co mment tags is a JavaScript co mmand. When the co mmand is
executed, the phrase He re is so m e t e xt will be writ t e n to the HTML do cum e nt .

No tice that there's a perio d (.) between windo w and do cum e nt . It lets the script reco gnize relatio nships
between o bje ct s. In o bje ct -o rie nt e d pro gram m ing, yo u wo rk o n o bje ct s. In o rder to wo rk o n tho se
o bjects, yo u have to define exactly which o bject yo u are wo rking o n, using hierarchical relatio nships. Take a
lo o k at this diagram:
car.gast ank

If yo u co nsider a car in pieces, a gas tank is a part o f a car. In pro gramming terms, the car is the parent o f the
gast ank o bject, and the gast ank is the child o f the car o bject. To reference the gas tank in JavaScript, yo u
wo uld use:

car.gast ank

The co de instructs the bro wser to first lo cate the car o bject, then lo cate the gast ank o bject within the car
o bject. So , to reference the car engine using JavaScript, yo u might use car.e ngine .

In the script that we wro te, we used:

windo w.do cum e nt

The windo w o bject represents the bro wser windo w. A windo w o bject is created auto matically with every
instance o f a <bo dy> tag. The windo w o bject is the parent o f the do cum e nt o bject. The do cum e nt o bject
represents the entire HTML do cument and can be used to access all elements in a page.

An Introduction to Methods
Metho ds define functio ns perfo rmed by an o bject. Thus, windo w.do cum e nt .writ e () calls the writ e ()
metho d o f the do cum e nt o bject.

Yo u can think o f o bje ct s as no uns - like car and gast ank o r windo w and do cum e nt . Yo u can think o f
m e t ho ds as verbs - like f ill o r writ e .

Let's say that o ur car is o ut o f gas, and we need to fill it up:

car.gast ank.f ill(gas)

f ill() is a metho d o f gast ank. It do esn't make sense to fill the car with gas - that wo uld be really dangero us
and hard to clean! What yo u actually do is take yo ur car to the gas statio n, walk aro und to the gas tank, and fill
up yo ur tank with gas. To reference the f ill() metho d in JavaScript, yo u wo uld use:

car.gast ank.f ill(gas)

This is kno wn as calling the f ill() metho d.

We use the same co ncept in the script that we're writing:

windo w.do cum e nt .writ e (" He re is so m e t e xt " )

The writ e metho d is used to write a string o f text to the do cument. It's a metho d o f the do cument o bject, no t
the windo w o bject. What do yo u think wo uld happen if yo u remo ved do cument fro m the co mmand? In HTML,
type this co de into the Edito r:
CODE TO TYPE:
<html>
<body>

<script type="text/javascript">
<!--
window.write("Here is some text")
//-->
</script>

</body>
</html>

Click Preview. The script no lo nger wo rks, and yo u likely go t an erro r such as, Erro r: windo w.writ e is no t a
f unct io n o r Obje ct do e sn't suppo rt t his pro pe rt y o r m e t ho d. Be sure to go back and put do cum e nt
back into yo ur reference!

All metho ds are fo llo wed by a set o f parentheses. If a metho d requires additio nal info rmatio n it is included
within the parentheses. The writ e () metho d requires o ne piece o f info rmatio n -- the text yo u wish to write to
the do cument. That text is lo cated within the parentheses and is placed inside quo tatio n marks:

windo w.do cum e nt .writ e (" He re is so m e t e xt " )

The He re 's so m e t e xt par o f the co de is also kno wn as a st ring. A string is a sequence o f characters such
as letters, numbers, and punctuatio n marks. Other metho ds require different data types; we will learn mo re
abo ut that later.

The abo ve statement do es no t end with a semico lo n. With traditio nal pro gramming languages, like C++ and
Java, each co de statement must end with a semico lo n. So me pro grammers co ntinue this habit when writing
JavaScript, but in general, semico lo ns are o pt io nal. Semico lo ns are required if yo u want to put mo re than
o ne statement o n a single line tho ugh.

Get into the habit o f using a reference when yo u are writing yo ur scripts. That way yo u can see which o bjects
and metho ds are available to yo u, and the type o f data the metho ds require. See if yo u can use this link to
determine which o ther metho ds can be used with the do cument o bject.

Yo u're do ing great so far! Keep it up. Mo re abo ut metho ds in the next lesso n...

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Methods and Variables

Methods and Variables


Methods
In the last lesso n yo u wro te yo ur first script and learned abo ut metho ds. In this lesso n yo u'll learn even mo re
abo ut metho ds by creating an interactive script. This script will pro mpt yo u fo r input, then it will use the writ e ()
metho d to print what yo u've entered to the do cument. In HTML mo de, type this co de into yo ur Edito r:

CODE TO TYPE:

<html>
<body>
<script type="text/javascript">
<!--

window.document.write(window.prompt("Enter your name:",""))

//-->
</script>
</body>

</html>

If yo u are using IE7, yo u may need to change a bro wser setting fo r this script to wo rk pro perly.
Note Check that To o ls > Internet Optio ns > Security >
"allo w websites to pro mpt fo r info rmatio n using scripted windo ws" is enabled.

Click Preview.

The pro m pt () metho d returns a value o f the text entered into the pro mpt dialo g bo x. The writ e () metho d is
then used to print the value returned to do cument.

Expanding o n this, yo u co uld use the write() metho d to write additio nal text, part o f which includes the value
returned by the pro m pt () metho d. Let's try that. In HTML mo de, type this co de into the Edito r:

CODE TO TYPE:
<html>

<body>
<script type="text/javascript">
<!--

window.document.write("Hi " + window.prompt("Enter your name:","") + ". Welcome


to my page.")

//-->
</script>
</body>

</html>

Click Preview.

This time yo ur name was added to o ther text, and then the full text was written to the do cument. The text
lo cated within quo tatio n marks is treated as a co nstant value, that is, the script uses it as-is. The + o pe rat o r
is used to co mbine the value returned fro m the pro m pt metho d to the text that is used as is. The text that is
co mbined and the final text that is written to the do cument are kno wn as st rings.
Note Yo u'll learn mo re abo ut o perato rs in a later lesso n.

Variables
Yo u may have no ticed in the last example that the co mmand line go t kind o f co nfusing because metho ds
were used within metho ds: strings were added to o ne ano ther within a metho d. Yo u co uld do that in o ne step
like we did abo ve, but the mo re yo u pro gram, the mo re yo u'll experience that it's well wo rth it to break yo ur
scripts do wn into smaller chunks. No t o nly do es it make yo ur intitial pro gramming easier, but it also makes it
easier to find any mistakes when yo ur bro wser gives yo u an erro r message.

A majo r to o l at yo ur dispo sal fo r simplifying scripts is variable s.

Let's revisit o ur car example. Recall that when we wanted to f ill the gast ank o n o ur car with gas, we used
the javascript equivalent:

car.gast ank.f ill(gas)

So , what kind o f gas are we go ing to put into the gast ank? Re gular, pre m ium , die se l? Respectively, fo r
each o f these o ptio ns, we wo uld write:

car.gast ank.f ill(re gular)


car.gast ank.f ill(pre m iun)
car.gast ank.f ill(die se l)

Or, suppo se fo r so me reaso n we wanted to fill o ur gast tank with a mixture o f all t hre e types o f gas; ho w
wo uld we do that? If we had a gascan, we co uld put so me o f each o f the different grades o f gas into that first.

Let's inco rpo rate the co ncept o f variable s into o ur pro gram. In this co ntext, a variable is like the gascan. It's
called a variable because its co ntents can vary. That is, we can fill the gascan with re gular, pre m ium , die se l
o r a m ixt ure o f all t hre e .

Let's see what the JavaScript equivalent o f using the variable gascan wo uld be:

To fill the car with a single type o f gas, such as regular, yo u wo uld use this syntax:

gascan=re gular
car.gast ank.f ill(gascan)

To fill the car with three types o f gas, yo u wo uld use this syntax:

gascan=re gular + pre m ium + die se l


car.gast ank.f ill(gascan)
The gascan variable is set equal to re gular + pre m ium + die se l. The variable no w co nt ains these
value s. Values are any co nstant entity. The number 1 is a value, and the string My Ho use is a value. A
variable can be set equal to these values. Say it alo ud a co uple o f times, "variables are co ntainers fo r values."

Let's apply these co ncepts to o ur previo us example. In HTML, type this co de into the Edito r:

CODE TO TYPE:
<html>

<body>
<script type="text/javascript">
<!--

beginPhrase = "Your name is "


userName = window.prompt("Enter your name:","")
endPhrase = " Welcome to my page."
finalString = beginPhrase + userName + endPhrase
window.document.write(finalString)

//-->
</script>
</body>

</html>

Click Preview. The results are the same, but yo u'll find the co de mo re readable no w that it is split into several
statements.

All o f the wo rds in blue are variable nam e s. Each o f the first three variables ho lds the value o f the re d t e xt .
In the case o f the use rNam e variable, the windo w.pro m pt () metho d is called first, and the value that is
entered by the user is sto red in the use rNam e variable.

The fo urth variable, f inalSt ring, ho lds the co mbined value o f each o f the previo us variables. Then the
writ e () metho d is used to write the value o f the f inalSt ring variable to the do cument.

When the f inalSt ring variable was used by the writ e () metho d, it was no t enclo sed in quo tatio n marks.
That's because we didn't want finalString to be treated as a co nstant value. Try enclo sing f inalSt ring within
quo tatio n marks and see what happens. The text f inalSt ring will be written to the do cument. The use o f
quo tatio n marks within the write() metho d is limited to text yo u want to print as a literal string.

One last no te abo ut variables befo re we mo ve o n to the next lesso n: Variable names must begin with either a
letter o r the undersco re character. Yo u can use any wo rd fo r a variable name as lo ng as it's no t a wo rd
reserved by JavaScript, o r the name o f a JavaScript o bject, metho d, o r pro perty. If yo u ever get an erro r
regarding a variable that yo u do no t think sho uld be causing a pro blem, try changing to name o f the variable
to so mething that is no t o ne o f the reserved wo rds. This rule is also true fo r o bjects, which yo u will learn
mo re abo ut later in the co urse.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Methods
Welco me back! In this lesso n, we'll wo rk to ward a deeper understanding o f m e t ho ds. Me t ho ds are functio ns that
belo ng to o r act upo n o bjects. We wo n't talk abo ut every single metho d in this co urse--there are just to o many!
Instead, we'll make sure yo u're familiar with metho ds and the way they wo rk; we want yo u to have the ability to
understand each metho d as yo u enco unter it, and be able to put it to use fo r yo urself. This particular lesso n will co ver
so me o f the metho ds that can be used with the windo w o bject and the do cum e nt o bject.

T he window Object
windo w.ale rt ()

Yo u're already familiar with the ale rt () metho d fro m earlier lesso ns. The ale rt () metho d displays an alert
bo x with a message and an OK butto n. The syntax lo o ks like this:

OBSERVE:
window.alert(message)

ale rt () is a metho d o f the windo w o bject. It requires o ne parameter which is the m e ssage to be displayed in
the bo x. The value o f the message can be entered o ne o f two ways:

Within quo tatio n marks: Fo r example, yo u co uld use " so m e t hing yo u want t o say." The
message is displayed in the alert bo x as-is. That is, so m e t hing yo u want t o say is displayed in
the bo x.
Witho ut quo tatio n marks: In this case, the value is treated as a variable name. Yo u must assign the
value equal to a string elsewhere in yo ur co de. Fo r example, yo u can use the statement:

m e ssage = " so m e t hing yo u want t o say"


windo w.ale rt (m e ssage )
to display so m e t hing yo u want t o say in the bo x.

In HTML mo de, type this co de into the Edito r as sho wn:

CODE TO TYPE:

<html>
<head>
<script type="text/javascript">
<!--

value = "This O'Reilly thing is GREAT!"


window.alert(value)

//-->
</script>
</head>
</html>

Click Preview.

At this po int, yo u're familiar with the alert() metho d. Let's take a lo o k at so me o ther metho ds o f the windo w
o bject, starting with o pe n():

T he open Method
This metho d is used to o pe n() a new windo w where yo u can display additio nal info rmatio n to yo ur visito rs.
The syntax lo o ks like this:

OBSERVE:

localname = window.open(URL,name,options)
The o pe n() metho d requires three parameters. The first parameter gives the URL to be displayed in the new
windo w. The seco nd parameter gives the new windo w a nam e (This name is impo rtant if yo u need to refer to
an o bject within this windo w later in yo ur co de). The third parameter allo ws yo u to co ntro l the appearance o f
the new windo w. There are many o pt io ns yo u can cho o se within the third parameter, like the height and
width o f the new windo w, whether it's resizable, has scro llbars, a to o lbar, o r a menubar. The next example will
give yo u a clearer picture o f ho w these parameters wo rk.

The result o f the o pe n() metho d will be sto red in the lo calnam e variable. This defines a lo cal name fo r the
new windo w. In o ther wo rds, it sto res the windo w into a variable. This part isn't abso lutely necessary, but, as
yo u'll see, it can make fo r mo re efficient scripting later.

Our example will use an event handler to call a functio n. Functio ns will be discussed in greater detail later. Fo r
no w, just fo cus o n the statements that are being executed within the functio n. In HTML, type this co de into the
Edito r as sho wn:

CODE TO TYPE:

<html>
<head>

<script type="text/javascript">
<!--

function openit(){

winda = window.open("http://www.oreillyschool.com/cert/javascript1/udidit.htm
l","newone","width=620,height=400")

//-->
</script>

</head>

<body>

<form>
<input type="button" onClick="openit()" value="open a window" />
</form>

</body>
</html>

Click Preview.

Do no t put return characters in the statement with the o pen() metho d! JavaScript
WARNING co nsiders each line to be a co mplete co mmand. Try putting a carriage return in the co de
(after widt h=6 20 fo r instance) and see fo r yo urself.

T he focus Method
Did the new windo w that yo u o pened in the last example appear in fro nt o f all the o ther windo ws that are o pen
o n yo ur co mputer? The f o cus() metho d will ensure that this is always the case! In HTML, type this co de into
the Edito r belo w as sho wn:
CODE TO TYPE:
<html>
<head>

<script type="text/javascript">
<!--

function openit(){

winda = window.open("http://www.oreillyschool.com/cert/javascript1/udidit.html",
"newone","width=620,height=400")
winda.focus()

//-->
</script>

</head>

<body>

<form>
<input type="button" onClick="openit()" value="open a window" />
</form>
</body>
</html>

Click Preview.

No tice that yo u used the lo calname winda to specify which windo w wo uld be in f o cus.

T he document Object
Theses metho ds are all metho ds o f the do cum e nt o bject:

do cum e nt .o pe n()
do cum e nt .writ e ()
do cum e nt .clo se ()

These three metho ds are o fen used to gether, so we may as well learn abo ut them all at o nce!

Suppo se yo u want to o pen a new windo w, but do n't want to place a pre-existing web page in the windo w.
Instead, yo u just want to display a quick message. To do that, yo u will have to write to the new do cument fro m
the o riginal page. In HTML mo de, type this co de into the Edito r as sho wn:
CODE TO TYPE:
<html>
<head>

<script type="text/javascript">
<!--

function openit(){

winda = window.open("","newone","toolbar=no,width=200,height=200")
winda.focus()
winda.document.open()
winda.document.write("IT WORKS DUDE!")
winda.document.close()

//-->
</script>

</head>

<body>

<form>
<input type="button" onClick="openit()" value="open a window" />
</form>

</body>
</html>

Click Preview.

No tice that yo u did no t supply a URL when yo u o pened the new windo w this time. Yo u left this parameter
empty, and used " " instead.

In this example, the wo rds IT WORKS DUDE! were written to the new windo w. Yo u can writ e any HT ML
t ags t o t he ne w windo w as we ll. Be careful with return characters! Try adding a carriage return after o ne o f
the wo rds in IT WORKS DUDE! and see happens.

Yo u must o pe n() the do cument befo re yo u can writ e () to the do cument that will appear in the new windo w.
When yo u're finished, yo u must clo se () it. If yo u do n't, yo ur co de will pro duce erro rs!

Try to write() so me HTML tags to the new windo w to make it mo re beautiful!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Properties and the Document Object Model

T he Document Object and Its Properties


So far in the co urse, we've intro duced the do cument o bject and its metho ds. In this lesso n we'll learn abo ut
pro pe rt ie s. Pro perties are the characteristics o f an o bject. Let's reco nsider the car we used in an example earlier:

One distinguishing characteristic o f a car is its co lo r. If we wanted to access the co lo r pro perty o f a car, we wo uld use
this syntax:

car.co lo r

If we wanted to set the co lo r o f the car equal to an actual value, we wo uld use this syntax:

car.co lo r=" re d"

We can also access and set pro perties o f HTML o bjects. Let's do that no w. In HTML mo de, type this co de into the
Edito r belo w as sho wn:

CODE TO TYPE:

<html>
<head>
<title>
Your title
</title>
</head>
<body bgcolor="white">
<script type="text/javascript">
<!--

alert(window.document.title)

//-->
</script>
</body>
</html>

Click Preview. Yo u'll see an alert in which the t it le o f yo ur do cument is displayed.

The windo w o bject has no pro perties; it o nly has sub-o bjects. do cum e nt is a sub-o bject o f windo w. It is used to
retrieve pro perties o f the do cument, and to examine and mo dify the HTML elements and text within the do cument. As
its name implies, the t it le pro perty is used to access the title o f the do cument o bject.

Try altering yo ur script to access these pro perties o f the do cument o bject:

bgCo lo r
linkCo lo r
vlinkCo lo r

Co o l, huh? We can also use JavaScript to set these values. In HTML mo de, type this co de into the Edito r belo w as
sho wn:
CODE TO TYPE:

<html>
<body bgColor="white">
<script type="text/javascript">
<!--
window.document.bgColor = "blue"
//-->
</script>
</body>
</html>

Click Preview. Even tho ugh yo u set the bgCo lo r attribute o f the bo dy tag to whit e , the backgro und co lo r o f the page is
actually blue . That's because yo u reset the bgCo lo r pro perty o f the do cum e nt to " blue " using JavaScript.

Okay, no w try do ing the same thing using the t it le pro perty; change the text displayed in the title bar to so mething
else.

Did it wo rk? Well, that all depends o n which bro wser yo u're using. No t all o f the pro perties that can be accessed with
JavaScript can be set with JavaScript. In additio n, Internet Explo rer's JScript do esn't always pro duce the same results
as o ther versio ns o f JavaScript. The mo ral o f the sto ry is to test yo ur scripts o n both browsers whenever yo u can!

T he Document Object Model


The HTML Do cum e nt Obje ct Mo de l (DOM) was bo rn o ut o f necessity. As client-side web pro gramming
languages evo lved, so did the way bro wsers implemented them. This o ften pro duced pages that lo o ked
radically different depending o n which bro wser was being used to view the page.

An o rganizatio n called the Wo rld Wide Web Co nso rtium (W3C) was created to help develo p co mmo n
pro to co ls and ensure intero perability o n the internet. Part o f their wo rk has been to define the HTML DOM.

A DOM is an applicatio n pro gramming interface (API) fo r representing do cuments (such as HTML
do cuments); it allo ws access and manipulatio n o f the vario us elements (such as HTML tags and strings o f
text) that make up that do cument. The HTML DOM is ro o ted in the hierarchical structure o f HTML do cuments. It
is represented in the DOM as a tree structure.

OBSERVE:
<html>

<head>
<title>The DOM</title>
</head>

<body>
<center>The document</center>
<p>
This is <b>bold</b> text
</p>
</body>
</html>

The DOM representatio n o f this do cument in the tree structure:


The no de directly abo ve a no de is the pare nt o f that no de. The no de directly belo w a no de is the child o f that
no de. Yo u co uld also visualize this hierarchy like this.

In the next lesso n, we'll co ntinue o ur discussio n o f the DOM and ho w to access and manipulate HTML
o bjects. Fo r no w, just center yo urself and visualize HTML do cuments as hierarchical...

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Document Object Methods: getElementById
In the last lesso n, yo u learned ho w to access and set so me pro perties o f the do cument o bject. In this lesso n, yo u'll
learn ho w to access and set pro perties o f o ther o bjects within yo ur do cument, using the ge t Ele m e nt ById() metho d.
In HTML, type this co de into the Edito r belo w as sho wn:

CODE TO TYPE:
<html>
<body>

<span id="someText" style="position:absolute; top:100; left:120; background-color:red;


color:white;">
Here is a some text
</span>

<script type="text/javascript">
<!--

var someText = document.getElementById("someText")


alert(someText)

//-->
</script>

</body>
</html>

Click Preview. Yo u'll see an alert displaying the text [o bje ct ]. While this info rmatio n might seem kind o f vague, it can
actually be used to gather much mo re specific info rmatio n abo ut the element.

The ge t Ele m e nt ById() metho d returns a reference to the first o bject with the specified ID. Once yo u have this
reference, yo u can get mo re info rmatio n abo ut the o bject. Fo r example, yo u co uld retrieve the t agNam e o f the
element. In HTML, type this co de into the Edito r belo w as sho wn:

CODE TO TYPE:

<html>
<body>

<span id="someText" style="position:absolute; top:100; left:120; background-color:red;


color:white;">
Here is some text
</span>

<script type="text/javascript">
<!--

var someText = document.getElementById("someText").tagName


alert(someText)

//-->
</script>

</body>
</html>

Click Preview.

Using the getElementById() metho d, yo u can access and set the style o bject pro perties.

T he Style Object Properties


As the web pages yo u build beco me mo re co mplex, yo u'll need to access and change the style pro perties o f
elements mo re o ften. Yo u'll do that using this syntax:

do cum e nt .ge t Ele m e nt ById(" id" ).st yle .st yle Pro pe rt y

The getElementById() metho d returns a reference to the first o bject with the specified ID. Then the st yle o bject
is used to access the pro perties o f this o bject.

Let's try an example to see ho w this wo rks. In HTML, type this co de into the Edito r as sho wn:

CODE TO TYPE:

<html>
<body>

<span id="someText" style="position:absolute; top:100; left:120; background-colo


r:red; color:white;">
Here is some text
</span>

<script type="text/javascript">
<!--

var someText = document.getElementById("someText").style.top


alert(someText)

//-->
</script>

</body>
</html>

Click Preview. Yo u'll see an alert displaying the to p po sitio n o f the element.

No w change the co de to o btain so me o ther pro perty, like the left po sitio n o r backgro und co lo r o f the o bject.
Check o ut this reference to see a list o f available pro perties.

Changing Property Values


No w that yo u kno w ho w to access pro perties o f the style o bject, let's use JavaScript to change so me o f tho se
pro perties. In HTML, type this co de into the Edito r as sho wn:
CODE TO TYPE:
<html>
<head>

<script type="text/javascript">
<!--

function changeBackground(){

document.getElementById("someText").style.backgroundColor = "blue"
}

//-->
</script>
</head>

<body>

<span id="someText" style="position:absolute; top:100; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground()">
Here is some text
</span>

</body>
</html>

Click Preview. The co lo r o f the backgro und sho uld change fro m red to blue when yo u ro ll yo ur curso r inside
o f the bo x. Go ahead and change so me o f the o ther pro perties, such as the po sitio n pro perties o r the co lo r o f
the text.

Later in the co urse we'll learn ho w to change pro perties o f an o bject to create mo re co mplex pro jects, like
dynamic pull-do wn menus. To do that, yo u'll need to beco me familiar with writing yo ur o wn functio ns.
Fo rtunately, we're co vering functio ns in the next lesso n! See yo u in the there!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Functions
So , we've created scripts that will be executed when a webpage is lo aded into a bro wser, explo red abo ut event
handlers, and learned ho w to use events to trigger yo ur script. In this lesso n yo u'll learn ho w to create and use
f unct io ns so that yo ur script can be executed at specific times.

A f unct io n is a self-co ntained sectio n o f co de that perfo rms o peratio ns o n so me input and returns a result. Once yo u
define a functio n, it can be called in much the same way as yo u'd call a metho d and it can be called as many times as
yo u'd like.

Let's get to wo rk o n an example. In HTML, type this into the Edito r as sho wn:

CODE TO TYPE:

<html>

<head>
<script type="text/javascript">
<!--

function changeBackground(){

document.getElementById("someText").style.backgroundColor = "blue"
}

//-->
</script>
</head>

<body>

<span id="someText" style="position:absolute; top:100; left:120; background-color:red;


color:white"
onmouseover="changeBackground()">
Here is a some text
</span>

</body>
</html>

Click Preview. I ho pe thiis lo o ks familiar to yo u--it's the exact co de fro m an example in the previo us lesso n. When yo u
mo ve yo ur m o use o ve r the element, the change Backgro und functio n is called and the backgro und co lo r o f the
element changes fro m red to blue.

The placement o f the functio n in the co de. Functio ns, like all JavaScript, must be lo cated inside script
Note tags, usually in the head o f the do cument. I enco urage yo u to fo llo w this practice, even tho ugh yo u can
place functio ns just abo ut anywhere.

Functio ns must be defined using f unct io n f unct io nNam e (). Yo u can name yo ur functio ns anything yo u like, but it's
a go o d idea to cho o se a name that describes the script's actio n. In this case, we named the functio n
change Backgro und because the script changes the backgro und co lo r o f an element. Remember, functio n names
are case-sensitive, so make sure the name yo u use to call the functio n is exactly the same as the o ne yo u use to
define it.

The name o f the functio n will always be fo llo wed by a set o f pare nt he se s. Items placed within these parentheses are
called param e t e rs. Parameters are passed to the functio n when it's called. They are values that are used by variables
within the functio n. In o ur current example, we are no t passing any parameters, so the parentheses are empty.

In o ur example, the co ntents o f the functio n are placed within a set o f curly brackets. An o pen bracket { tells the bro wser
that we are beginning to define the co ntents o f o ur functio n. A clo sing bracket } tells the bro wser that we've co mpleted
the functio n definitio n.

Using Multiple Functions


As yo ur co de beco mes mo re co mplex, yo u'll need to create and use mo re than o ne functio n. Let's add a
functio n to o ur co de so that the backgro und co lo r o f the element will change back to its o riginal co lo r. In
HTML, type this co de into the Edito r belo w as sho wn:

CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function changeBackground(){

document.getElementById("someText").style.backgroundColor = "blue"
}

function changeBackgroundBack(){

document.getElementById("someText").style.backgroundColor = "red"
}

//-->
</script>
</head>

<body>

<span id="someText" style="position:absolute; top:100; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground()" onmouseout="changeBackgroundBack()">
Here is a some text
</span>

</body>
</html>

Click Preview. Mo ve yo ur mo use in and o ut o f the element and see the co lo rs change!

This time we're calling a new functio n called change Backgro undBack when the m o use is m o ve d o ut o f
the element.

Function Parameters
Suppo se yo u want to create a web page with several bo xes that functio n just like the o ne in the previo us
example. One way to do it wo uld be to create two new functio ns fo r this bo x. In HTML, type this co de into the
Edito r belo w as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function changeBackground1(){

document.getElementById("someText").style.backgroundColor = "blue"
}

function changeBackgroundBack1(){

document.getElementById("someText").style.backgroundColor = "red"
}

function changeBackground2(){

document.getElementById("moreText").style.backgroundColor = "blue"
}

function changeBackgroundBack2(){

document.getElementById("moreText").style.backgroundColor = "red"
}

//-->
</script>
</head>

<body>

<span id="someText" style="position:absolute; top:100; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground1()" onmouseout="changeBackgroundBack1()">
Here is a some text
</span>

<span id="moreText" style="position:absolute; top:130; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground2()" onmouseout="changeBackgroundBack2()">
Here is more text
</span>

</body>
</html>

Click Preview, then mo ve yo ur mo use in and o ut o f the elements to make sure the co lo rs change.

Wo rks great! But o ur co de will be lo ng and inefficient if we keep building it like this, especially if we want to add
mo re elements that will functio n in the same way. Instead, we can use parameters to sho rten the co de. In
HTML, type this co de into the Edito r as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function changeBackground(id){

document.getElementById(id).style.backgroundColor = "blue"
}

function changeBackgroundBack(id){

document.getElementById(id).style.backgroundColor = "red"
}

//-->
</script>
</head>

<body>

<span id="someText" style="position:absolute; top:100; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground('someText')" onmouseout="changeBackgroundBack('
someText')">
Here is a some text
</span>

<span id="moreText" style="position:absolute; top:130; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground('moreText')" onmouseout="changeBackgroundBack('
moreText')">
Here is more text
</span>

</body>
</html>

Click Preview. Yo u'll see the same results as befo re.

The co de in this example is much sho rter than the co de used in the previo us o ne. To sho rten it, we wro te it so
the functio n requires a parameter. When a parameter is passed to o ur functio n, the value will be sto red in the
parameter, much like a variable. This value will be used anywhere yo u see the parameter name inside the
functio n. So , when we execute the functio n call:

o nm o use o ve r=" change Backgro und('so m e T e xt ')"

'so m e T e xt ' is passed to the functio n and is sto red in id where it will be used in this statement:

do cum e nt .ge t Ele m e nt ById(id).st yle .backgro undCo lo r = " blue "

Multiple Parameters
It is also po ssible to pass multiple parameters to yo ur functio ns. In HTML, type this co de into the Edito r as
sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function changeBackground(id,theColor){

document.getElementById(id).style.backgroundColor = theColor
}

function changeBackgroundBack(id,theColor){

document.getElementById(id).style.backgroundColor = theColor
}

//-->
</script>
</head>

<body>

<span id="someText" style="position:absolute; top:100; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground('someText', 'blue')" onmouseout="changeBackgrou
ndBack('someText', 'red')">
Here is a some text
</span>

<span id="moreText" style="position:absolute; top:130; left:120; background-colo


r:red; color:white"
onmouseover="changeBackground('moreText', 'yellow')" onmouseout="changeBackgr
oundBack('moreText', 'red')">
Here is more text
</span>

</body>
</html>

Click Preview. This time when the mo use is mo ved o ver the seco nd element, the backgro und sho uld change
to 'ye llo w' instead o f 'blue '.

Being able to create and use functio ns is impo rtant fo r JavaScript pro grammers, so yo u'll want to be sure yo u
understand the abo ve examples. Experiment! What o ther functio ns can yo u create?

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Operators

Operators in Javascript
An o pe rat o r is a symbo l used to perfo rm an o peratio n o n so me value. In JavaScript, o perato rs can act o n either
numbers o r strings. The o perato rs fall into the fo llo wing catego ries: arithmetic, assignment, and co mpariso n

T he Arithmetic Operators
Arithmetic o perato rs are pro bably mo st familiar to yo u. Let's take a lo o k at the additio n (+), subtractio n (-),
multiplicatio n (*), and divisio n (/) o perato rs in actio n. In HTML, type this co de into the Edito r belo w as sho wn:

CODE TO TYPE:

<html>
<head>

<script type="text/javascript">
<!--

var topPosition = 200

function changeIt(){
topPosition = topPosition + 100
document.getElementById("someText").style.top = topPosition
}

//-->
</script>

</head>

<body>

<span id="someText" style="position:absolute; top:200;">


Here is some text
</span>
<br/><br/>
<form>
<input type="button" onClick="changeIt()" Value="Click Me!" />
</form>

</body>
</html>

Click Preview. When yo u click the butto n, 10 0 is adde d to the t o pPo sit io n variable. The to p po sitio n o f the
element is set to this value, so the text mo ves do wn 10 0 pixels.

If yo u are viewing this example using Firefo x yo u must use:

Note do cument.getElementById("so meText").style.to p = to pPo sitio n + 10 0 + "px"

Firefo x requires that all po sitio n pro perties be specified as pixel (px) o r percentage (%) values.

So , what do yo u think wo uld happen if yo u subt ract e d 10 0 fro m the to p po sitio n? If yo u m ult iplie d the to p
po sitio n by 5? Or if yo u divide d the to p po sitio n by 10 ? Try so me experimenting and find o ut!

Ano ther arithmetic o perato r, the m o dulus o perato r (% ), is used to find the remainder o f a divisio n. Since any
even number divided by 2 gives no remainder, yo u can use this o perato r to determine whether o r no t a
number is o dd o r even. In HTML, type this co de into the Edito r belo w as sho wn:
CODE TO TYPE:

<html>
<head>

<script type="text/javascript">
<!--

function findIt(){
var oddOrEven = document.getElementById("myText").value % 2
alert(oddOrEven)
}

//-->
</script>

</head>

<body>
Enter a whole number in text field below.
<br/>
<form>
<input type="text" id="myText" />
<input type="button" onClick="findIt()" Value="Click Me!" />
</form>

</body>
</html>

Click Preview. The alert bo x sho uld display 0 if the number entered is even, and 1 if the number entered is
o dd.

Finally, we have the incre m e nt (++) and de cre m e nt (--) o perato rs. These o perato rs are used to increase
o r decrease a value by 1. In HTML, type this co de into the Edito r belo w as sho wn:

CODE TO TYPE:
<html>
<head>

<script type="text/javascript">
<!--

var topPosition = 200

function changeIt(){
topPosition++
document.getElementById("someText").style.top = topPosition
}

//-->
</script>

</head>

<body>

<span id="someText" style="position:absolute; top:200;">


Here is some text
</span>
<br/><br/>
<form>
<input type="button" onClick="changeIt()" Value="Click Me!" />
</form>

</body>
</html>
Click Preview. Be sure to click the butto n repeatedly--the element sho uld mo ve do wn by o ne pixel each time.
That's because the increment o perato r incre ase s the to p po sitio n o f the element by 1 each time the functio n
is executed.

What do yo u think wo uld happen if yo u used the decrement o perato r to de cre ase the to p po sitio n o f the
element by 1? Give that a try!

T he Assignment Operators
The assignment o perato rs are used to set values. Fo r that reaso n, all o f the assignment o perato rs use an
e quals (=) sign. We have used this o perato r befo re. Remember this functio n fro m the first example in this
lesso n?:

OBSERVE:
function changeIt(){
topPosition = topPosition + 100
document.getElementById("someText").style.top = topPosition
}

Here yo u used the = to assign the po sitio n o f the element so m e T e xt to a new value. Yo u also co uld have
do ne this using the += o perato r. Mo dify yo ur co de as sho wn:

CODE TO TYPE:
<html>
<head>

<script type="text/javascript">
<!--

var topPosition = 200

function changeIt(){
topPosition += 100
document.getElementById("someText").style.top = topPosition
}

//-->
</script>

</head>

<body>

<span id="someText" style="position:absolute; top:200;">


Here is some text
</span>
<br/><br/>
<form>
<input type="button" onClick="changeIt()" Value="Click Me!" />
</form>

</body>
</html>

Click Preview. Yo u'll get the exact result that yo u did when yo u viewed the first example fro m the lesso n.

The expressio n x += y is equivalent to the expressio n x = x + y. Bo th expressio ns yield the same result.
Here's a table illustrating the o ther assignment o perato rs:

Assignment Operato r Equivalent Expressio n


x += y x=x+y
x -= y x=x- y
x *= y x=x*y
x /= y x=x/y
x %= y x=x%y

Experiment freely with these o perato rs!

Comparison Operators
Co mpariso n o perato rs are used to co mpare two values. Yo u wo n't use these o perato rs until the next lesso n,
but here's a table yo u can use as a reference later in the co urse:

Co mpariso n Operato r Example


var x = 3
var y = 4
equal ==
x == y returns false
var x = 3
var y = 4
no t equal !=
x != y returns true
var x = 3
var y = 4
greater than >
x > y returns false
var x = 3
var y = 4
less than <
x < y returns true
var x = 3
var y = 4
greater than o r equal to >=
x >= y returns false
var x = 3
var y = 4
less than o r equal to <=
x <= y returns true

Operato rs are an impo rtant part o f JavaScript; yo u'll use them regularly as yo u co ntinue thro ugh the co urse and
whenever yo u pro gram in Javascript. Make sure yo u understand the co ncepts discussed here tho ro ughly befo re
mo ving o n to the next lesso n.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
The if Statement

T he if Statement
The if statement is o ne o f the mo st po werful to o ls at yo ur dispo sal. It allo ws yo u to make co mpariso ns and react to
the result o f tho se co mpariso ns. The if statement is kno wn as a co nditio nal statement because it's used to perfo rm
different actio ns based o n different co nditio ns.

Take a clo ser lo o k. In HTML, type the fo llo wing into the Edito r so it lo o ks like this:

CODE TO TYPE:
<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

var i = Math.ceil(Math.random()*10)
var oddOrEven = i%2

if (oddOrEven == 0){
alert(i + " is an even number.")
}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. Be sure to click the butto n several times until an alert bo x is displayed.

When the functio n is called, two variables are set. First, the i variable is set equal to a rando m integer. The m o dulus
o pe rat o r is then used to find the remainder o f this integer when it is divided by 2. The remainder is sto red in a variable
called o ddOrEve n.

Keep in mind that when an even integer is divided by 2, there will be no remainder. When an o dd integer is divided by 2,
the remainder is 1. And o ur if statement can test fo r just that!

An if statement must co ntain these three elements: if , pare nt he se s, and a se t o f curly bracke t s. The wo rd if is
used to designate the beginning o f the if statement. The pare nt he se s are used to co ntain the co nditio n to be
evaluated. The curly bracke t s co ntain the co de that sho uld be executed if the co nditio n evaluates to true.

In this case, the co nditio n uses the e qualit y o perato r to determine whether the o ddOrEve n variable is equal to 0 . If it
is equal to 0 , then there was no remainder. We kno w that i is an even number; the alert will tells us.

What will happen if the variable is o dd? Fo r no w, no thing! Let's add co de to fix that. In HTML, mo dify yo ur co de as
sho wn:
CODE TO TYPE:

<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

var i = Math.ceil(Math.random()*10)
var oddOrEven = i%2

if (oddOrEven == 0){
alert(i + " is an even number.")
}

else{
alert(i + " is an odd number.")
}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. Again, be sure to click the butto n several times so that yo u get a lo o k at the two different alert bo xes.

This time, we added an e lse statement to o ur functio n. The else statement will be executed whenever the co nditio n in
the if statement do es no t evaluate to true. In this case, that means anytime the o ddOrEve n variable co ntains a value
o ther than 0 .

No w suppo se yo u want so mething special to happen if the variable i is equal to 2. To do that, yo u'll include an e lse if
statement. In HTML, mo dify yo ur co de as sho wn:
CODE TO TYPE:
<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

var i = Math.ceil(Math.random()*10)
var oddOrEven = i%2

if (i == 2){
alert("The number is 2!")
}

else if (oddOrEven == 0){


alert(i + " is an even number.")
}

else{
alert(i + " is an odd number.")
}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. Again, click the butto n several times so that yo u can o bserve all three alert bo xes.

No te that in this case, the initial if statement checks to see if the i variable is equal to 2. The functio n m ust be written in
this way. What do yo u think wo uld happen if i was equal to 2 and o ddOrEve n variable was checked first? Po nder this
fo r a mo ment, and experiment at will!

Logical Operators
Lo gical o pe rat o rs are used to link sequences o f co mpariso ns. Yo u can use them to check two co nditio ns
in a single if statement. Two o f the mo re co mmo n lo gical o perato rs are the AND o perato r and the OR
o perato r.

We'll try an example. In HTML, type the co de as sho wn:


CODE TO TYPE:
<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

var i = Math.ceil(Math.random()*10)
var oddOrEven = i%2

if (oddOrEven == 0 && i > 6){


alert(i + " is an even number. It is greater than 6.")
}

else if (oddOrEven == 0 && i <= 4){


alert(i + " is an even number. It is less than or equal to 4.")
}

else if (oddOrEven == 0 && i == 6){


alert(i + " is an even number. It is equal to 6.")
}

else{
alert(i + " is an odd number.")
}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. As befo re, be sure to click the butto n several times.

Here, we used the AND o perato r (&&) to check two co nditio ns simultaneo usly. That is, we checked to see if
the variable was even AND whether it was gre at e r t han 6 , le ss t han o r e qual t o 4 , o r exactly equal to 6 .

As yo ur co de beco mes mo re co mplex, yo u'll use if statements mo re o ften. Experiment with them a fo r a while befo re
mo ving o n to the next lesso n. See yo u there!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
For and While Loops

for and while Loops


A lo o p is a sectio n o f co de yo u want to execute a specific number o f times o r while a specified co nditio n is true.
Here's a real life example:

Suppo se yo u're really hungry, so yo u sit do wn to eat so me spaghetti. To eat, yo u perfo rm the same set o f actio ns
repeatedly. That is, yo u use yo ur fo rk to deliver a small amo unt o f fo o d to yo ur mo uth, then yo u chew the fo o d, and
finally yo u swallo w. Yo u co ntinue this pro cess fo r as lo ng as yo u're still hungry. That is, yo u lo o p thro ugh this
pro cess until yo u are satisfied.

The two main types o f lo o ps used in JavaScript are while lo o ps and f o r lo o ps. Let's take a clo ser lo o k.

T he while Loop
A while lo o p is used to execute the same sectio n o f co de while a specified co nditio n is true. In HTML, type
this co de into the Edito r belo w as sho wn:

CODE TO TYPE:

<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

var i=0

while (i<5 ){

alert("The number is" + i)


i++

}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. No te that an alert is displayed each time the lo o p is repeated, and that a to tal o f five alert
messages are displayed.

When the butto n is clicked, the do It functio n is called, and a variable i is init ialize d (o r set equal to ) 0 . This
is an impo rtant step because i is also used in the while lo o p to t e st and see if a co nditio n is true. As lo ng as
value o f i is less than 5 , the co de written within the curly bracke t s will be executed.

Each time this sectio n o f co de is executed, the value o f i is incre m e nt e d by 1. So , after the fifth time the
piece o f co de is executed, the value o f i will be equal to 5. After that, since 5 is exactly equal to 5, the co nditio n
is no lo nger true and the lo o p terminates.
T he for Loop
The f o r lo o p is similar to a while lo o p, but a f o r lo o p will execute a sectio n o f co de a specified number o f
times. Take a lo o k. In HTML, type this co de into the Edito r as sho wn:

CODE TO TYPE:
<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

for (i=0;i<5;i++){

alert("The number is" + i)

}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. The result o f this co de is the same as the result o f the previo us co de.

In the case o f a f o r lo o p, a variable is init ialize d, t e st e d, and incre m e nt e d in the same lo catio n.

Initially, i is equal to 0 . Since i is le ss t han 5 the co de written within the curly bracke t s will be executed.

After this co de is executed, i is incre m e nt e d by 1 and so it is no w equal to 1. Since 1 is still le ss t han 5 , the
alert is displayed again, and the value o f i is incre m e nt e d. This pro cess co ntinues until the value o f i is no
lo nger less than 5.

Nesting Statements
No w that yo u're familiar with while lo o ps, f o r lo o ps, and if statements, let's try using them to gether. In this
example, we'll ne st an if statement within a f o r lo o p. In HTML, type this co de into the Edito r as sho wn:
CODE TO TYPE:

<html>

<head>

<script type="text/javascript">
<!--

function doIt(){

for (i=0;i<5;i++){

if(i==4){

alert("The number is 4. This is the last time through the loop.")

else{

alert("The number is" + i)

}
}
}

//-->
</script>

</head>
<body>

<form>
<input type="button" onclick="doIt()" value="Do It" />
</form>

</body>

</html>

Click Preview. The result will be similar to the last example, except this time a special message will be
displayed the last time the lo o p is executed.

When i is exactly e qual t o 4 , an alert bo x will be displayed to let yo u kno w that it's the final time the lo o p will
be executed. If i is no t equal to 4, a "no rmal" alert bo x is displayed.

Lo o ps are a po werful to o l, o ne yo u'll use o ften in yo ur scripts. Experiment with them fo r a bit befo re mo ving o n to the
next lesso n. See yo u there!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Object Arrays

Arrays
An array is a single variable name that can be used to sto re a set o f values. It can ho ld a series o f values, and the
individual values are accessed by their po sitio n in the array. Yo u can think o f an array like a list o r a filing cabinet.

An array called nam e s might lo o k so mething like this:

This is the syntax used to reference an element sto red in an array:

arrayNam e [inde x]

The first name sto red in the array is sco t t . If yo u wanted to access this name, yo u wo uld do so using:

nam e s[0 ]

Be aware that the first index o f an array is always 0 . So , if yo u wanted to change the name sto red in the fifth po sitio n
fro m Mike to J o sh, yo u wo uld use:

nam e s[4 ] = " J o sh"

The array then beco mes:

Arrays will be the fo cus o f the next two lesso ns. Yo u'll create yo ur o wn arrays, like the nam e s array abo ve, in the next
lesso n. Fo r no w, we're go ing to learn abo ut the arrays that already exist when yo u create an HTML do cument.

document Object Collections


Suppo se yo u had an HTML do cument that lo o ked like this. In HTML, type this co de into the Edito r as sho wn:
CODE TO TYPE:

<html>

<head>
<script type="text/javascript">
<!--

function displayText(){

document.getElementById("myText").value = document.getElementById("myForm").n
ame

//-->
</script>
</head>

<body>

<form id="myForm" name="myFormName">


<input type="text" id="myText" />
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. When yo u click the butto n, the name o f the fo rm will be displayed in the text field.

At this po int, yo u're familiar with the ge t Ele m e nt ById syntax. Yo u can acco mplish the same task that syntax
do es, using the f o rm s co llectio n. Let's give thatt a try. In HTML, type this co de into the Edito r as sho wn:

CODE TO TYPE:

<html>

<head>
<script type="text/javascript">
<!--

function displayText(){

document.getElementById("myText").value = document.forms[0].name

//-->
</script>
</head>

<body>

<form id="myForm" name="myFormName">


<input type="text" id="myText" />
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. Yo u'll see the same results that yo u did earlier using syntax.

The fo rms co llectio n is just o ne o f the do cum e nt o bje ct co lle ct io ns available in Javascripts. To learn
abo ut the o thers, click he re . Fo r o ur purpo ses in this lesso n, we'll fo cus o n the fo rms co llectio n.
T he forms Collection
All inputs, textareas, and select bo xes are co nsidered elements that are co ntained by a fo rm. As such, they
can be referenced using the e le m e nt s array. In HTML, type the co de into the Edito r as sho wn:

CODE TO TYPE:

<html>

<head>
<script type="text/javascript">
<!--

function displayText(){

document.getElementById("myText").value = document.forms[0].elements[0].id

//-->
</script>
</head>

<body>

<form name="myForm">
<input type="text" id="myText" />
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. The first element in the fo rm is the t e xt input . Because it's the first element, it can be
referenced using the 0 index.

Let's add ano ther element within the fo rm. In HTML, mo dify yo ur co de in the Edito r belo w as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function displayText(){

document.getElementById("myText").value = document.forms[0].elements[1].name

//-->
</script>
</head>

<body>

<form id="myForm" name="myFormName">


<input type="text" id="myText" />
<select name="mySelect">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. Yo u'll see the nam e o f the se le ct bo x displayed. Since it's the seco nd element in the fo rm, it's
referenced using the 1 index.

The select bo x is a special element because it has o pt io ns asso ciated with it. These o ptio ns are co nsidered
elements co ntained by the select bo x, so they can be referenced using the o pt io ns array. In HTML, mo dify
yo ur co de as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function displayText(){

document.getElementById("myText").value = document.forms[0].elements[1].optio
ns[0].text

//-->
</script>
</head>

<body>

<form id="myForm" name="myFormName">


<input type="text" id="myText" />
<select name="mySelect">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. Yo u'll see the text Opt io n 1 displayed in the text field. This text is co ntained by the first o pt io n,
so it's referenced using the 0 index.

table Collections and innerHT ML


Tables have two co llectio ns that can be used to change the co ntent o f a table dynamically. The ro ws
co llectio n can be used to return an array co ntaining each ro w fro m a table. The ce lls co llectio n can be used
to return an array co ntaining each cell fro m a table.

To get a better idea o f ho w these co llectio ns wo rk, we'll use the inne rHT ML pro perty. The inne rHT ML
pro perty sets o r retrieves the HTML between the start and end tags o f the o bject.

In HTML, mo dify yo ur co de as sho wn:


CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

function displayRowInfo(){

alert(document.getElementById("theTable").rows[2].innerHTML)

function displayCellInfo(){

alert(document.getElementById("theTable").rows[2].cells[0].innerHTML)

//-->
</script>
</head>

<body>

<table id="theTable" border="2">


<tr>
<td>Row1, cell1</td>
<td>Row1, cell2</td>
</tr>
<tr>
<td>Row2, cell1</td>
<td>Row2, cell2</td>
</tr>
<tr>
<td>Row3, cell1</td>
<td>Row3, cell2</td>
</tr>
</table>

<br/>

<form name="myForm">
<input type="button" value="Row Info" onClick="displayRowInfo()" />
<input type="button" value="Cell Info" onClick="displayCellInfo()" />
</form>

</body>
</html>

Click Preview. Be sure to click bo th butto ns o n the webpage.

Clicking the first butto n will alert the inne rHT ML o f the third ro w. Because it's the third ro w, yo u can access it
using ro ws[2].

Clicking the seco nd butto n will alert the inne rHT ML o f first cell in the third ro w. Because it's the first cell, yo u
can access it using ce lls[0 ].

As yo ur scripts beco me mo re co mplex, yo u might find it helpful to ado pt syntax that uses
variables within yo ur references. Fo r example, yo u co uld also access the inne rHT ML o f the first
cell in the third ro w using:
Note
var ce ll1=do cum e nt .ge t Ele m e nt ById(" t he T able " ).ro ws[2].ce lls[0 ]
ale rt (ce ll1.inne rHT ML)
In the next lesso n we'll discuss arrays in mo re detail. Be sure to experiment with what yo u learned here befo re mo ving
o n!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Arrays

More Arrays
In the last lesso n, yo u learned abo ut arrays and used them alo ng with several o bject co llectio ns available via the
do cument o bject mo del. In this lesso n, yo u'll define yo ur o wn o bject arrays to use in yo ur o wn JavaScripts!

Recall that an array is a single variable name that can be used to sto re a set o f values. Let's lo o k at the example fro m
the previo us lesso n:

The first name sto red in the array is sco t t . If yo u wanted to access this name yo u wo uld do so using:

nam e s[0 ]

Let's build this array in o ur script, and access o ne o f the values sto red within it. In HTML, type this co de into the Edito r
as sho wn:

CODE TO TYPE:

<html>

<head>
<script type="text/javascript">
<!--

var names = new Array()

names[0] = "scott"
names[1] = "kendell"
names[2] = "Trish"
names[3] = "Tony"
names[4] = "Mike"
names[5] = "Debra"
names[6] = "Curt"

function displayText(){

alert(names[0])

//-->
</script>
</head>

<body>

<form id="myForm">
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. Be sure to click o n the butto n, which calls the displayT e xt functio n, which in turn will display nam e s[0 ]
in an alert bo x. sco t t is displayed, because it is the 0 index o f the nam e s array.

To define yo ur o wn array, yo u must first create an Array o bject; use the ne w keywo rd to do that.

There are two ways to add values to an array. One is to add a single value per line, as we did here:
nam e s[0 ] = " sco t t "
nam e s[1] = " ke nde ll"
nam e s[2] = " T rish"
nam e s[3] = " T o ny"
nam e s[4 ] = " Mike "
nam e s[5 ] = " De bra"
nam e s[6 ] = " Curt "

Alternatively, yo u can add values using a single line o f co de. In HTML, mo dify yo ur co de in the Edito r as sho wn:

CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

var names = new Array("scott","kendell","Trish","Tony","Mike","Debra","Curt")

function displayText(){

alert(names[0])

//-->
</script>
</head>

<body>

<form id="myForm">
<input type="button" value="Do It" onClick="displayText()" />
</form>

</body>
</html>

Click Preview. Yo u get the same results as yo u did in the previo us example. This time tho ugh, we assigned values to
the nam e s array when we declared it as a ne w Array o bject.

Let's experiment with the names array so me mo re! In HTML, mo dify yo ur co de as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

var names = new Array()

names[0] = "scott"
names[1] = "kendell"
names[2] = "Trish"
names[3] = "Tony"
names[4] = "Mike"
names[5] = "Debra"
names[6] = "Curt"

function displayText(){

alert(names[document.getElementById("myText").value])

//-->
</script>
</head>

<body>

<form id="myForm">
<input type="text" id="myText" />
<input type="button" value="Do It" onClick="displayText()" />
</form>

<br/>
Please enter an integer, 0 through 6.

</body>
</html>

Click Preview. No w try entering different integers! No te that the index o f the array will be the value we enter into the text
field.

Building Dynamic Select Boxes


Suppo se yo u want to create a web page that includeds so mething like this:

.........................

Choose a Team...

Try selecting different teams to see ho w the player names change. We are dynam ically po pulat ing the
seco nd select bo x based o n the cho ice selected in the first select bo x. Even if yo u're no t a rabid basketball
fan, this is a go o d example o f ho w a pro grammer might use arrays in the real wo rld.

Let's start by creating the select bo xes. In HTML, type this co de into yo ur Edito r as sho wn:
CODE TO TYPE:
<html>

<body>

<form>
<select id="theTeams">
<option> Choose a Team</option>
<option>Boston Celtics</option>
<option>LA Lakers</option>
<option>Chicago Bulls</option>
</select>
<select id="thePlayers" size="3">
<option> ...............</option>
<option></option>
<option></option>
</select>
</form>

</body>

</html>

Click Preview.

This co de pro bably lo o ks familiar to yo u. Yo u have two select bo xes. One co ntains a list o f three teams fro m
which yo u can cho o se. The o ther is empty fo r no w, tho ugh it do es have o ne o ptio n o f .............. This is a so rt
o f place ho lder to keep the select bo x wide eno ugh--it wo uld co llapse o therwise. We also have three o ther
empty <o pt io ns> listed. This is impo rtant: Yo u m ust have as m any o pt io ns as t he lo nge st list wit h
which yo u want t o po pulat e t he se le ct bo x.

Next, yo u need to make an array to sto re the names that will be displayed upo n selecting a team. This array is
called t e am s and co ntains fo ur arrays -- t e am s[" no ne " ], t e am s[" ce lt ics" ], t e am s[" lake rs" ], and
t e am s[" bulls" ]. In HTML, mo dify yo ur co de as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

var teams = new Array("none","celtics","lakers","bulls")

teams["none"] = new Array("........................","","")


teams["celtics"]= new Array("Larry Bird","Bill Russell","Kevin McHale")
teams["lakers"] = new Array("Wilt Chamberlain","Jerry West","Shaquille ONeil")
teams["bulls"] = new Array("Micheal Jordan","Scottie Pippen","Dennis Rodman")

//-->
</script>
</head>

<body>

<form>
<select id="theTeams">
<option> Choose a Team</option>
<option>Boston Celtics</option>
<option>LA Lakers</option>
<option>Chicago Bulls</option>
</select>
<select id="thePlayers" size="3">
<option> ...............</option>
<option></option>
<option></option>
</select>
</form>

</body>

</html>

No w yo u'll write the functio n that will display the appro priate names based o n the selected team. In o rder to
create this functio n, yo u need to understand ho w to reference the teams arrays using numeric indices.

Try to predict which values wo uld be returned if yo u used these alerts with the abo ve co de. (If yo u're having
tro uble, yo u can always insert them o ne at a time, just befo re the ending script tag):

ale rt (t e am s[1])
ale rt (t e am s[t e am s[1]][2])
ale rt (t e am s[" ce lt ics" ])
ale rt (t e am s[" ce lt ics" ][3])

Yo u may recall that the se le ct e dInde x o f a select bo x returns an integer based upo n the highlighted cho ice.
Because yo u can also access array values using numeric indices, we can use the se le ct e dInde x pro perty
to display the appro priate values in the names array based upo n the highlighted team. In HTML, type the co de
into yo ur Edito r as sho wn:
CODE TO TYPE:
<html>

<head>
<script type="text/javascript">
<!--

var teams = new Array("none","celtics","lakers","bulls")

teams["none"] = new Array("........................","","")


teams["celtics"]= new Array("Larry Bird","Bill Russell","Kevin McHale")
teams["lakers"] = new Array("Wilt Chamberlain","Jerry West","Shaquille ONeil")
teams["bulls"] = new Array("Micheal Jordan","Scottie Pippen","Dennis Rodman")

function fillPlayers(){

var whichIndex = document.getElementById("theTeams").selectedIndex


var numberOfPlayers = teams[teams[whichIndex]].length

for(i=0;i < numberOfPlayers; i++){


document.getElementById("thePlayers").options[i].text = teams[teams[whichI
ndex]][i]
}
}

//-->
</script>
</head>

<body>

<form>
<select id="theTeams" onChange="fillPlayers()">
<option> Choose a Team</option>
<option>Boston Celtics</option>
<option>LA Lakers</option>
<option>Chicago Bulls</option>
</select>
<select id="thePlayers" size="3">
<option> ...............</option>
<option></option>
<option></option>
</select>
</form>

</body>

</html>

Click Preview. Yo u'll see that the co de wo rks exactly like the example fro m earlier in the lesso n. Let's take a
clo ser lo o k at the co de.

The f illPlaye rs functio n is called o nChange o f the select bo x. When the functio n is called, the fo llo wing
values are returned:

var whichInde x = do cum e nt .ge t Ele m e nt ById(" t he T e am s" ).se le ct e dInde x


var num be rOf Playe rs = t e am s[t e am s[whichInde x]].le ngt h

The first line retrieves the selectedIndex o f theTeams select bo x, which will be an integer between 0 and 3.
This value is sto red in the whichInde x variable.

The seco nd line retrieves the le ngt h o f the array sto red in t e am s[t e am s[whichInde x]]. Suppo se
whichInde x is equal to 1. Then t e am s[whichInde x] is actually t e am s[1], o therwise kno wn as ce lt ics.
Since the t e am s[" ce lt ics" ] array has three items, the num be rOf Playe rs wo uld be set equal to 3.

The f o r lo o p is used to po pulate the select bo x:


f o r(i=0 ;i < num be rOf Playe rs; i++){
do cum e nt .ge t Ele m e nt ById(" t he Playe rs" ).o pt io ns[i].t e xt = t e am s[t e am s[whichInde x]][i]
}

If num be rOf Playe rs is set equal to 3 (and it will be no matter which team is selected since all o f the arrays
co ntain three items), then the co de within the fo r lo o p will be executed three times. Each time this statement:

do cum e nt .ge t Ele m e nt ById(" t he Playe rs" ).o pt io ns[i].t e xt = t e am s[t e am s[whichInde x]][i]

is executed, the t e xt o f o ne o f the o pt io ns in t he Playe rs select bo x is written. The text will be the value
sto red in t e am s[t e am s[whichInde x]][i]. If whichInde x is set equal to 1 and i is set equal to 0 , then the
text written to the first o ptio n wo uld be t e am s[t e am s[1]][0 ], o therwise kno wn as Larry Bird.

Let's pratice--here is ano ther way yo u can co de the abo ve example.


In HTML, type the fo llo wing into the Edito r belo w:
<html>

<head>
<script type="text/javascript">
<!--

var teams = new Array()

teams[1] = new Array()


teams[1][0] = "Larry Bird"
teams[1][1] = "Bill Russell"
teams[1][2] = "Kevin McHale"

teams[2] = new Array();


teams[2][0] = "Wilt Chamberlain"
teams[2][1] = "Jerry West"
teams[2][2] = "Shaquille Oneil"

teams[3] = new Array()


teams[3][0] = "Micheal Jordan"
teams[3][1] = "Scottie Pippen"
teams[3][2] = "Dennis Rodman"

function fillPlayers(){

var whichIndex = document.getElementById("theTeams").selectedIndex


var numberOfPlayers = teams[whichIndex].length

for(i=0;i < numberOfPlayers; i++){


document.getElementById("thePlayers").options[i].text = teams[whichIndex][
i]
}
}

//-->
</script>
</head>

<body>

<form>
<select id="theTeams" onChange="fillPlayers()">
<option> Choose a Team</option>
<option>Boston Celtics</option>
<option>LA Lakers</option>
<option>Chicago Bulls</option>
</select>
<select id="thePlayers" size="3">
<option> ...............</option>
<option></option>
<option></option>
</select>
</form>

</body>

</html>

Click Preview.

Do yo u reco gnize and understand the abo ve changes? Take time to practice so yo u can use what yo u've
learned when yo u do the pro ject fo r this lesso n.

Copyright © 1998-2014 O'Reilly Media, Inc.


Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Operations with Nodes

Introduction to Nodes
Every HTML do cument has a "tree" structure. A tree structure is an embedded heirarchical list o f o bjects.
Co nsider an HTML page that has the fo llo wing structure:

OBSERVE:
<html>
<head>
<title>Example page</title>
</head>

<body>

<table name="toptable">
<tr id="firstrow">
<td>first cell, first row</td>
<td>second cell, first row</td>
</tr>
<tr id="secondrow">
<td>first cell, second row</td>
<td>second cell, second row</td>
</tr>
<tr id="thirdrow">
<td>first cell, third row</td>
<td>second cell, third row</td>
</tr>
</table>

</body>
</html>

Just like the abo ve table, HTML fo rms a hierarchy. The table tag abo ve has t hre e childre n (the three tr tags)
and they in turn have two children each (they each have two td tags in them). Click o n the butto n belo w to see
a T re e Vie w o f the abo ve table in a web page (in fact yo u'll see a full tree view o f the entire page).
Click here

Each o f the fo lders abo ve is a no de o f the HTML DOM tree fo r this web page. A no de is simply where the tree
branches. In fact, every HTML element o n a webpage is a no de. There are two kinds o f no des: e le m e nt s and
t e xt no de s. Bo th kinds can be created and manipulated using JavaScript.

Creating and Manipulating Elements


Here is an example using createTextNode and createElement to create so me text and an element. Then
using appendChild and insertBefore, we place the elements and text into the do cument where we want it:
Type the fo llo wing into Co deRunner:

<html>
<head>
<script type="text/javascript">
<!--
function insertStuff(){

var theNewElement = document.createElement("b")


var theNewElement2 = document.createElement("i")
var theNewText1 = document.createTextNode(" Here is the first text ")
var theNewText2 = document.createTextNode(" Here is the second text ")
theNewElement.appendChild(theNewText1)
theNewElement2.appendChild(theNewText2)

var here = document.getElementById("scott")


var parentDiv = here.parentNode

parentDiv.insertBefore(theNewElement,here)
parentDiv.appendChild(theNewElement2)

}
//-->
</script>
</head>
<body>

<a href="javascript:insertStuff()">Click here to insert the HTML</a>

<p id="scott" style="color:red;">


hello there
</p>

</body>
</html>

After yo u've previewed it, click the link to see bo ld text placed befo re the red "hello there" and italic text placed
after it.

Let's break do wn the co de and see what's happening. In the insertStuff() functio n, we declared a new
variable called theNewElement. This is o ur co ntainer fo r the new element instance we created using
createElement("b"), where we created an instance b element (the bo ld element) (it's no t a new element
but it is a new instance o f a familiar element). In the seco nd line we created a new i using createElement("i").

After creating a co uple o f elements, we created a co uple o f t e xt no de s using the createTextNode("Here


is the first text").

And since we created a co uple o f e le m e nt no de s and a co uple o f t e xt no de s, we can append the text
no des as children o f the element no des. We do that by using the appe ndChild() metho d. The element we
are appending to is theNewElement, so we write theNewElement.appendChild(theNewText1). The no de
we are appending go es in the argument o f the metho d (in this case, theNewText1). This o peratio n is the same
as fo rming <b>He re is t he f irst t e xt </b> and <i>He re is t he se co nd t e xt </i>.

No w, the go al is to put the first text in front o f he llo t he re and the seco nd text after it. In o rder to do this, let's
create a variable called he re where we can sto re sco t t as a pare nt No de . Then we can use the
inse rt Be f o re metho d to place the element befo re the p tag, and the appe ndChild metho d to place the
element after the p tag.

No te that the insertBefore() metho d takes o ne o r two parameters. The first parameter is WHAT we are
appending, and the seco nd parameter is WHERE we are appending it.

Try playing aro und with this script and see if yo u can place the text in different places using the abo ve co de.
There are several o ther metho ds yo u might want to familiarize yo urself with to manipulate no des: clo neNo de,
replaceChild, remo veChild, createAttribute, and insertData.

Check here fo r a bro wser co mpatiblity chart.


Working with tables
One o f the best uses o f wo rking with No des and children is with tables. Yo u might want to change so mething
in a table o r maybe yo u'd like to add cells o r ro ws dynamically witho ut having to rebuild an entire table.
Manipulating No des is great when it co mes to tables. Try the fo llo wing co de:

Type the fo llo wing into Co deRunner:


<html>
<body>

<table border="1">
<tr id="example">
<td>TD One</td>
<td>TD Two</td>
<td>TD Three</td>
</tr>
</table>

<script type="text/javascript">
<!--
var Counter = 0

function insertTD(){

var newTD = document.createElement("td")


var newText = document.createTextNode("A New Cell " + (Counter++))
newTD.appendChild(newText)

var tdplace = document.getElementById("example").childNodes[2]


document.getElementById("example").insertBefore(newTD,tdplace)

}
//-->
</script>

<a href="javascript:insertTD()">Click here</a>

</body>
</html>

Okay, no w Preview it. When yo u click o n the link, it sho uld insert a cell into the table. In this case we are using
the same metho ds as we did earlier in the lesso n. We used createElement to create a new td element, then
we used createTextNode to create a new text no de and then appendChild to append it to the td element.
Finally, we set its lo catio n by cho o sing the childNodes[2] o f the "example" tr element, which is the third td o f
the table in its first and o nly ro w.

If yo u are using the Firefo x bro wser yo u will have to use:

var tdplace = do cument.getElementById("example").childNo de s[4 ]


Note
This is because Firefo x will co unt whitespace as a no de. Alternatively yo u co uld use:

<tr id="example"><td>TDOne</td><td>TDTwo </td><td>TDThree</td></tr>

Here's ano ther way to do the exact same thing:


Type the fo llo wing into Co deRunner:
<html>
<body>

<table border="1">
<tr id="example">
<td>TD One</td>
<td>TD Two</td>
<td>TD Three</td>
</tr>
</table>

<script type="text/javascript">
<!--
var Counter = 0

function insertTD(){

var newTD = document.createElement("td")


var newText = document.createTextNode("A New Cell " + (Counter++))
newTD.appendChild(newText)

var trname = document.getElementById("example")


var tdplace = trname.getElementsByTagName("td").item(2)
trname.insertBefore(newTD,tdplace)
}
//-->
</script>

<a href="javascript:insertTD()">Click here</a>

</body>
</html>

Preview it. Yo u sho uld get the same thing as befo re. The o nly difference here is that we are using
getElementsByTagName("td"). This get's all o f the td elements and puts them in a co llectio n. We then can
access the third td element in the table by selecting the seco nd item, using item(2).

Here is yet ano ther way to do the same thing.


Change yo ur do cument to lo o k like this:
<html>
<body>

<table border="1">
<tr id="example">
<td>TD One</td>
<td>TD Two</td>
<td>TD Three</td>
</tr>
</table>

<script type="text/javascript">
<!--
var Counter = 0

function insertTD(){

var newText = document.createTextNode("A New Cell " + (Counter++))

NewCell = document.getElementById("example").insertCell(2)
NewCell.appendChild(newText)
}
//-->
</script>

<a href="javascript:insertTD()">Click here</a>

</body>
</html>

No w, Preview it. Again, it sho uld do the same thing as befo re. This time we are using the insertCell()
metho d. We do n't need to create a td element using createElement since insertCell() will do that fo r us.
Once we have the cell created (in the third po sitio n, same as befo re), we append the text no de using
appendChild().

Phew! I think that's eno ugh fo r this lesso n! Do the pro jects, pat yo urself o n the back, and it's o n to the next
o ne!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Creating Javascript Menus

Javascript Menus
Welco me to the final lesso n o f yo ur Javascript co urse! In this lesso n, we'll use what we have learned to create a
dro pdo wn menu. These menus will help yo u create o rganized and pro fessio nal paths to navigate thro ugh websites.
Have fun!

Our first step is to create a simple list o f items to navigate. I like do gs, so let's make a list o f different types o f do gs.

In HTML, type the fo llo wing into the Edito r belo w:


<html>

<body>

<ul id="surf">

<li>Hounds
<ul>
<li><a href="">Bloodhound</a></li>
<li><a href="">Basset</a></li>
<li><a href="">Beagle</a></li>
<li><a href="">Irish Wolfhound</a></li>
</ul>
</li>

<li>Shepherds
<ul>
<li><a href="">German Shepherd</a></li>
<li><a href="">Collie</a></li>
<li><a href="">Sheepdog</a></li>
</ul>
</li>

<li>Terriers
<ul>
<li><a href="">Airedale</a></li>
<li><a href="">Scottish</a></li>
<li><a href="">Jack Russell</a></li>
<li><a href="">Bull Terrier</a></li>
<li><a href="">Yorkshire</a></li>
</ul>
</li>

</ul>

</body>

</html>

Preview this co de. Yo u sho uld see a list o f three types o f do gs--Ho unds, Shepherds, and Terriers. Listed belo w each
o f these are specific breeds o f each type. The breed names sho uld be hyperlinks, altho ugh clicking o n the link will no t
take yo u to any specific lo catio n.

Because we are creating a dro pdo wn menu, we need to make it so that the three lists o f do g breeds are displayed
ho rizo ntally. While we're at it, let's eliminate the list bullets. We can do all o f this using stylesheets.
In HTML, type the fo llo wing into the Edito r belo w:

<html>

<head>
<style type="text/css">

ul {
padding: 0;
margin: 0;
list-style: none;
}

li {
float: left;
position: relative;
width: 10em;
}

</style>
</head>
<body>

<ul id="surf">

<li>Hounds
<ul>
<li><a href="">Bloodhound</a></li>
<li><a href="">Basset</a></li>
<li><a href="">Beagle</a></li>
<li><a href="">Irish Wolfhound</a></li>
</ul>
</li>

<li>Shepherds
<ul>
<li><a href="">German Shepherd</a></li>
<li><a href="">Collie</a></li>
<li><a href="">Sheepdog</a></li>
</ul>
</li>

<li>Terriers
<ul>
<li><a href="">Airedale</a></li>
<li><a href="">Scottish</a></li>
<li><a href="">Jack Russell</a></li>
<li><a href="">Bull Terrier</a></li>
<li><a href="">Yorkshire</a></li>
</ul>
</li>

</ul>

</body>

</html>

Preview this co de. The po sitio n and appearance o f the seco nd-level lists must also be co nsidered. That is, these lists
sho uld no t be displayed until the asso ciated to p-level menu item is selected, and they sho uld be displayed in a
lo catio n so as no t to interfere with the main menu.

Let's start by wo rking o n the po sitio ning.


In HTML, type the fo llo wing into the Edito r belo w:
<html>

<head>
<style type="text/css">

ul {
padding: 0;
margin: 0;
list-style: none;
}

li {
float: left;
position: relative;
width: 10em;
}

li ul {
display: block;
position: absolute;
top: 1em;
}

</style>
</head>
<body>

<ul id="surf">

<li>Hounds
<ul>
<li><a href="">Bloodhound</a></li>
<li><a href="">Basset</a></li>
<li><a href="">Beagle</a></li>
<li><a href="">Irish Wolfhound</a></li>
</ul>
</li>

<li>Shepherds
<ul>
<li><a href="">German Shepherd</a></li>
<li><a href="">Collie</a></li>
<li><a href="">Sheepdog</a></li>
</ul>
</li>

<li>Terriers
<ul>
<li><a href="">Airedale</a></li>
<li><a href="">Scottish</a></li>
<li><a href="">Jack Russell</a></li>
<li><a href="">Bull Terrier</a></li>
<li><a href="">Yorkshire</a></li>
</ul>
</li>

</ul>

</body>

</html>
Click Preview.

A dro pdo wn sho uld o nly sho w us the selectio ns when we mo useo ver o r click o n a menu item. We need to hide the
lists until we mo useo ver the items. Hiding the lists is easy. Simply change the display o f the list items fro m blo ck to
no ne as fo llo ws.
In HTML, type the fo llo wing into the Edito r belo w:
<html>

<head>
<style type="text/css">

ul {
padding: 0;
margin: 0;
list-style: none;
}

li {
float: left;
position: relative;
width: 10em;
}

li ul {
display: none;
position: absolute;
top: 1em;
}

</style>
</head>
<body>

<ul id="surf">

<li>Hounds
<ul>
<li><a href="">Bloodhound</a></li>
<li><a href="">Basset</a></li>
<li><a href="">Beagle</a></li>
<li><a href="">Irish Wolfhound</a></li>
</ul>
</li>

<li>Shepherds
<ul>
<li><a href="">German Shepherd</a></li>
<li><a href="">Collie</a></li>
<li><a href="">Sheepdog</a></li>
</ul>
</li>

<li>Terriers
<ul>
<li><a href="">Airedale</a></li>
<li><a href="">Scottish</a></li>
<li><a href="">Jack Russell</a></li>
<li><a href="">Bull Terrier</a></li>
<li><a href="">Yorkshire</a></li>
</ul>
</li>

</ul>

</body>

</html>
Preview this. The menu listings sho uld no w be hidden fro m sight.

T he Script
The next step is to make the listings appear when we mo ve o ur mo use o ver the menu items.
In HTML, type the fo llo wing into the Edito r belo w:
<html>

<head>
<style type="text/css">

ul {
padding: 0;
margin: 0;
list-style: none;
}

li {
float: left;
position: relative;
width: 10em;
}

li ul {
display: none;
position: absolute;
top: 1em;
}

li.dropdown ul { display: block; }

</style>

<script type="text/javascript">
<!--

function initializelist(){
topRoot = document.getElementById("surf");
for (i=0; i<topRoot.childNodes.length; i++) {
nodeAt = topRoot.childNodes[i];
if (nodeAt.nodeName=="LI") {
nodeAt.onmouseover=function() {
this.className ="dropdown";
}
nodeAt.onmouseout=function() {
this.className="";
}
}
}
}

window.onload=initializelist;

//-->
</script>

</head>
<body>

<ul id="surf">

<li>Hounds
<ul>
<li><a href="">Bloodhound</a></li>
<li><a href="">Basset</a></li>
<li><a href="">Beagle</a></li>
<li><a href="">Irish Wolfhound</a></li>
</ul>
</li>
<li>Shepherds
<ul>
<li><a href="">German Shepherd</a></li>
<li><a href="">Collie</a></li>
<li><a href="">Sheepdog</a></li>
</ul>
</li>

<li>Terriers
<ul>
<li><a href="">Airedale</a></li>
<li><a href="">Scottish</a></li>
<li><a href="">Jack Russell</a></li>
<li><a href="">Bull Terrier</a></li>
<li><a href="">Yorkshire</a></li>
</ul>
</li>

</ul>

</body>

</html>

Preview this. Be sure to mo ve yo ur mo use o ver each menu item. When yo u do , it sho uld display the do g
breeds belo nging to that particular gro up.

Let's take a clo ser lo o k at the init ialize list functio n. This functio n will examine all o f the childNo des inside o f
the element called surf . If the childNo de is an li element, its className will be set equal to dro pdo wn when
the mo use mo ves o ver it. When the mo use mo ves away, the className will be set equal to "" (a blank name
like it had in the beginning).

Observe:
function initializelist(){
topRoot = document.getElementById("surf");
for (i=0; i<topRoot.childNodes.length; i++) {
nodeAt = topRoot.childNodes[i];
if (nodeAt.nodeName=="LI") {
nodeAt.onmouseover=function() {
this.className ="dropdown";
}
nodeAt.onmouseout=function() {
this.className="";
}
}
}
}

The f o r statement navigates thro ugh each childNo de inside o f elements named surf , which are no w
referenced as t o pro o t . Each childNo de is assigned to a variable called no de At . If the childNo de is LI, the
classNam e s are changed acco rding to the mo use mo vement.

No tice that the style has also been changed:


li.dropdown ul { display: block; }

This causes list items to be displayed when the className o f list items embedded within uno rdered lists is
set equal to dro pdo wn via the fo r lo o p in the functio n.

This co de is co mmo nly used to create dro pdo wn menus. To find info rmatio n o n o ther ways to create dro pdo wn
menus, check this o ut. Have fun and experiment!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Potrebbero piacerti anche