IT – som værktøj
Bent Thomsen
Institut for Datalogi
Aalborg Universitet
Introduction to JavaScript
Bent Thomsen
What is a web script?
• A program embedded in an HTML document
– Scripts can be found multiple places in a document
• There are multiple scripting languages
– VBScript (Microsoft proprietary) interpreted only in IE
unless a plug-in is installed
– JavaScript – far more common and universally
interpreted in all browsers
• Scripts make HTML into DHTML (dynamic
What is JavaScript?
• A programming language to add
interactivity to your Web page.
In the beginning there was HTML, and the folks at Netscape
saw that it was good. But it was static; interactivity was
needed. People wanted to enter information and get answers
back. So the Netscape folks decided that HTML should have a
helpmate, JavaScript. Unlike other programming languages,
JavaScript was built into the browser and worked alongside
How does a script work?
• A browser is a very complex, multi-function
• Using HTML syntax, the browser locates
script statements inside the document
• It hands the statements to a script interpreter
that causes the browser to do what the
statements (commands) tell it to do.
What is JavaScript
It is NOT Java or a dialect. It is a completely different, interpreted language intended to
control the browser, typically to add dynamics and animation to HTML.
One of many programming languages executed (possibly simultaneously) in the browser!
Control /
Java Virtual
Machine (JVM)
HTML Interpreter
(display formatting)
Control /
JavaScript is Not Java
• Java is a full-featured programming
language developed by Sun Microsystems.
• Java's main use is to create applets, small
programs that download over the Internet
and run inside Web Browsers
– Java applets are embedded in your Web page
using the <APPLET> tag.
Identifying JavaScript in an
HTML page
• Scripts can be found multiple places in a document
• Scripts are placed between <SCRIPT>…</SCRIPT> tags.
• The <SCRIPT> tag can be attributed with language:
• Script containers <SCRIPT>…</SCRIPT> can be found:
– In the <HEAD> of the document in the <SCRIPT> </SCRIPT> container
– Anyplace in the <BODY> of the document in a script container
– In-line code in various tags throughout the document
• Usually associated with tags that support events such as <IMG> and form
• The code describes what to do for a given event
• Line(s) of script in quotes following the event name as an attribute of the tag
Hiding Your Script
• You can hide your JavaScript program from
browsers that cannot support them. Use this
<!---hide this script from browsers that don’t
support JavaScript
JavaScript commands…
//Stop hiding from other browsers --->
JavaScript Programs consists of
Control Flow operations
JavaScript recognizes:
– strings
– numbers (integer and decimal)
– boolean
Null value assigned using keyword null
x = 100
y = “200”
z = true
• A variable is a place in the computers
memory where information (values) are
• In programming languages, the storage
places have names.
• You access the value in the storage place by
its name.
• JavaScript variables are not explicitly defined
(loosely typed language).
barWidth = 50
• Conversions are done automatically.
• Variables must start with a letter or underscore.
• To use the value of a JavaScript variable as an
attribute in HTML, start with an ampersand (&)
and end with a semicolon (;)
<HR WIDTH="&{barWidth};%" ALIGN="LEFT">
<!--- Hide script from old browsers.
document.write("Hello World!");
barWidth = 50
// End the hiding here. -->
<HR WIDTH="&{barWidth};%" ALIGN="LEFT">
The result
JavaScript Variables
• JavaScript variable names must begin with a letter
and can’t contain unusual characters such as ‘&’
or ‘#’
• JavaScript variables are polymorphic – HUH? –
that is, they can contain any type of information
Object references (such as images!)
Variables in most other languages are more ‘strictly
JavaScript Variables
• Use ‘=‘ to place a value into a variable
• myNumber = 12
– (places the number 12 in the memory location named
• myString = “Hello World!”
– Strings are lines of characters delimited by single or
double quotes
• myObjAnImage = “C:/pics/tower.jpg”
Document.write myNumber  (prints ’12’ onscreen)
yourNumber = 10
myNumber = yourNumber
Document.write myNumber  (prints ’10’ onscreen)
Sending Output
• JavaScript provides two commands to
display text on a Web page: the
document.write() and document.writeln()
commands. Here is the syntax:
document.write(“text here”);
document.writeln(“text here”);
For example: document.write(“Hello World!”);
Simple Input/Output
alert(“Hello World”);
confirm(“Are you sure you want to delete?”);
prompt(“Enter your name?”, “”);
JavaScript Commands
• A ‘command’ in any computer language is a
reserved word – such as “write”
• or reserved symbol – such as ‘+’ or ‘=‘
• that tells the computer to do something
Change variable values
Direct the control flow
Manipulate I/O
Manipulate the O/S
JavaScript statements and code
• A statement is a syntactically correct
• A line is series of syntactically correct
statements separated by semicolons <;> and
ending in a line-feed/carriage return
• A code sequence is a series of lines which
are executed left to right, top to bottom
Test = (SomeVar == SomeOtherVar);
Document.write(“It is” + Test + “that “);
Document.write(“SomeVar is equal to SomeOtherVar”);
Flow Control
if (condition) {
code to be executed
else {
code to be executed
for (i = 0; i < 10; i++) {
code to be executed
while (condition) {
code to be executed
Selection (choosing alternatives)
• if (statement in brackets is true) then
– {Do stuff in curly braces}
• else if (statement in brackets is true) then
– {Do stuff in curly braces}
• else if . . .
• else
– {Do stuff in curly braces}
Note that the first ‘if’ has no ‘else’ and the last ‘else’ has
no ‘if’!
Selection – example
• A simple program specification calling for
conditionals and Boolean logic
• We’re going to input a salary figure
– if < 200K/yr then write “Poor sod!”
– if exactly equal 200K/yr write “Congratulations - you
are an exact Mr. Average ”
– if > 200K and <= 500K then write “High earner HUH!.”
– if > 500K/yr then write “Hello Rockefeller”
First, Comparison Operators
• Equality ==
• NOTE! JavaScript like ‘C’, ‘C++’ and
‘Java’ – to name only a few – uses double
equals to check for equality:
A single equal sign is the assignment
Comparison Operators
• Greater than (works for numbers and strings)
• Less than: <
• Combinations
– Greater than or equal to >=
– Less than or equal to <=
Logical (Boolean) Operators
• To do the complex comparison
– If > 200K and <= 500K then write “High earner
• Logical operators are required:
– AND (i.e. if A is true AND B is true)
• &&
– OR (i.e. if A is true OR B is true)
• ||
JavaScript code
if (f < 200000)
document.write("Poor sod!")
else if (f == 200000)
document.write("Congratulations - you are an exact Mr.
else if (f > 200000 && f <= 500000)
docuemnt.write("High earner - HUH!.")
else document.write("Hello Rockefeller")
Logical (Boolean) Operators (2)
• The last logical operator is NOT  !
– i.e. if salary plus bennies is not > 800K then I
don’t care.
– If !((salary + bennies) > 800000) then . . .
– Notice the ! comes first and applies to the entire
expression in parentheses – read it as: “if NOT
salary plus bennies greater than . . . “
Assignment Operator
Equality Operators
Other Operators
• A loop is a piece of code that repeats multiple
• It saves repetitive coding and all languages have
looping facilities.
• The alternative is called in-line code
While Loops
• the ‘while’ statement syntax is:
while (condition) {
code to be executed
• Example:
while (x < 10) {
document.writeln(“x is” + x);
x = x + 1;
//could have used x+=1 or X++
For Loops
• JavaScript uses (mostly) the ‘for’ statement.
• the ‘for’ statement syntax is:
for (initialization code;
loop test code;
loop increment code)
{code that gets repeated until the loop test is
• A variable is a space in memory in which to
store information
• An array is a group of variables all called by
the same name, but with different numbers
Images = new array
Images[1] = i1.url
Images[2] = 12.url
Document.write images[1]
Arrays (2)
• Arrays are numbered starting with 0
• Although you must specify an array dimension
initially, you can change the dimension by
storing something in a higher numbered
– myArray = new array(3)
– myArray = new array (“Tom”, “Dick”, “Harry”)
– myArray[4] = “Fred”
Loops and Arrays
• Arrays and loops are “made for each other”
• Arrays can be ‘loaded’ using loops
• Arrays can be searched using loops
for (i=0;i<4,i++){
if (myArray[i]==“Dick”)
document.writeln myArray[i]
• Functions are code sequences that “do something”
(perform a function) that you can call by name
from inside other code sequences.
• You can also give them different information to
work with (pass parameters) each time you call
• Syntax:
function fName(passedInfo)
{code to do the function}
Functions (2)
function fName(passedInfo)
{code to do the function}
• fName is any valid JavaScript name
• passedInfo can be a comma delimited list of
values: (valOne, valTwo, myString)
• Any values in passedInfo are available to
any code for the function – they DO NOT
need to be declared
JavaScript - example
function testsalary(f) {
if (f < 200000)
document.write("Poor sod!")
else if (f == 200000)
document.write("Congratulations - you are an exact Mr.
else if ((f > 200000) && (f <= 500000))
document.write("High earner - HUH!.")
else document.write("Hello Rockefeller")
f=prompt("Input your salary","");
Control flow and value passing
• When the browser starts to execute lines of
code in a function, the function is said to
have been called.
• We say “control has passed to the function”
• Functions can call other functions
• Functions can call themselves (recursion)
• Functions can be called by events (onClick)
Built in functions (or methods)
• JavaScript has a wide variety of “built in”
functions available:
• Date and Time functions
– GetTime()
JavaScript is an Object-Based
• The Objects JavaScript deal with are:
– Windows
– Forms
– Form Elements
• Buttons, and Radio Buttons
• Check Boxes
• Objects have their own Unique Names.
JavaScript enabled browsers have built-in objects which have
properties, events and methods which can be used by
JavaScript. For example:
Date Object
String Object
Math Object
Window Object
The Browser Object Model
• You want to use JavaScript to dynamically
change different properties of the browser,
such as link colors, border widths, etc.,
• How would you describe all the hundreds of
properties in a way that was understandable
and could be easily expressed in JavaScript?
• Its called the BROWSER OBJECT
JavaScript Objects have properties
• In JavaScript, a Window Object has a
Property called a Title.
• A Form Object's Property could be a Check
JavaScript Objects have Methods
• The things that Objects do are called
– Here a few Methods that JavaScripts Objects can
• buttons click()
• windows open()
• text can be selected()
– The parentheses are referring to a method rather than a
– Think of Objects and Properties as Nouns and Methods as
JavaScript Dot Syntax
• Place Objects, Properties and Methods
together to get a better description of an object
or process.
– In JavaScript, these are separated by periods
AKA, dots or dot syntax.
– window.status
Object & Properties
– document.write()
Object & Methods
Handling JavaScript Events
• Events are actions that the user performs
while visiting your page.
– Submitting a form and moving a mouse over
an image that has a roll-over.
JavaScript Event Handlers
• JavaScript deals with events with
commands called event handlers.
– In JavaScript, if the user clicks on a button,
the onClick() event handler will take note of
the action and perform whatever duties it was
• See the next slide for a listing of Event Handlers.
Event Handlers
W ha t it H a n d le s
W ha t it H a n d le s
o n A b o rt
U s e r a b o rte d
lo a d in g th e p a g e
o n B lu r
U s e r le ft th e o b je c t
o n M o u s e O v e r C u rs o r m o ve d
o ve r a n o b je c t
onM ouseO ut
C u rs o r m o ve d
o ff a n o b je c t
o n S e le c t
U s e r s e le c te d
th e c o n te n ts o f
a n o b je c t
o n S u b m it
U s e r s u b m itte d
a fo rm
o n U n lo a d
U s e r le ft th e
w in d o w
o n C h a n g e U s e r c h a n g e d th e
o b je c t
o n C lic k
U s e r c lic k e d o n a n
o b je c t
o n E rro r
S c rip t e n c o u n te re d
a n e rro r
U ser m ade an
o b je c t a c tive
O b je c t fin is h e d
lo a d in g
Event Example
• Some Web designers like to have special
messages pop-up in the Status Bar when a
mouse passes over a Hypertext link.
– We will use a onMouseOver trick for this
• Code is on the next slide.
onMouseOver Code inside the
<Body> Tag
• I'll use a Hyperlink to Hotbot and give it a
cool description for the status bar.
Note: You can't
have a Scrolling
Message and
this too!
Form Validation Introduction
• The creation of forms was covered in the
HTML lectures.
• Review of form elements – most based on
the <INPUT TYPE = .. > tag
Type = Text
Type = Checkbox
Type = Radio
The exception - the drop down selection box
Form Validation (2)
• With HTML alone, you have no control over what
the user enters – and no interactivity.
• What do you do if the user skips a required field?
• What do you do if the user chooses incompatible
• The answer is - you create JavaScript validation
code to check the form values.
• But – how do you “get at” the data that has been
Form Validation (3)
• Because an HTML form is part of the BOM, we
use dot notation to access the Form elements (the
Form is an object composed of Element objects ;-)
• The syntax for accessing text entries:
value is a keyword
document can be skipped
formName and elementName are the names you gave
your form and text input element
So – to get the value a user entered into a text field:
myTextVariable = formName.elementName.value
Form Validation (4)
• The value entered into <TEXTAREA> tag (a
textbox) is determined the same way.
myTextBoxVar = formName.textBoxName.value
– Where textBoxName is the name of the
TEXTAREA element on the form
• If you enter CR’s in a TEXTAREA, they are
retrieved. Otherwise multi-line (wrapped
around) entries are treated as a single long
string without line breaks (in IE) .
Calculator Example
<TITLE>Square Calculator Function</TITLE>
<!-- Hide script from old browsers
function square(number) {
return number * number
// End script hiding from old browsers -->
<H1>Square Calculator</H1><HR>
Enter a number <INPUT NAME="number1" TYPE="INT" VALUE="0">
<INPUT NAME="activate" VALUE="Calculate" TYPE="BUTTON"
OnClick="form.answer.value = square(form.number1.value)"><BR>
The square is
<INPUT NAME="answer" TYPE="INT" VALUE="0">
Tips for Writing JavaScript
• Use comments throughout to help you understand the
program. <!-- comments -->
• Use indented text to make your code easier to read
and follow.
• JavaScript is case-sensitive, be careful.
• Include HTML comment tag to hide JavaScript from
older browsers that don’t support the code.
• Test your JavaScript program with several browsers if
JavaScript programming
• There are many JavaScripts on the Web that you can
copy and/or modify quite easily to fit your needs
• JavaScript programming often consist of:
– Finding effects on a page that you want to duplicate
– Locating the code that performs the effect – use
View/Source in your browser
– Cutting the code from the original page and embedding it
in your page
– Getting it to work in the new environment
• The time honored name for that process is
Opgaver og kursusmateriale