(Bookflare - Net) - Javascript Basics and Advanced
(Bookflare - Net) - Javascript Basics and Advanced
By R.Dharani
Contents
1 JavaScript Basics
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
Syntax Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Basic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
Operations on Numbers & Strings . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conditional Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7
Conditional Variable Assignment with The Ternary Operator . . . . . . . . . . . .
Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9
Breaking and continuing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Reserved Words . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . 11 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . 11 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Using
. . . . . . . . . . . . . . . 13 Testing Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Closures . . . . .
........................................
1 JavaScript Basics
1 JavaScript Basics
Overview
JavaScript is a rich and expressive language in its own right. This section covers
the basic concepts of JavaScript, as well as some frequent pitfalls for people
who have not used JavaScript before. While it will be of particular value to
people with no programming experience, even people who have used other
programming languages may benefit from learning about some of the
peculiarities of JavaScript.
Syntax Basics
var foo =
’ hello world ’;
2 * 3 + 5;
2 * (3 + 5);
Basic Operators
Concatenation
2 * 3;
2 / 3;
var i = 1;
var j = ++ i ;
// pre - increment :
j equals 2; i equals 2
var k = i ++;
1 JavaScript Basics
var foo = 1;
var bar = ’2 ’;
// 12. uh oh
var foo = 1;
var bar = ’2 ’;
Logical Operators
Logical operators allow you to evaluate a series of operands using AND and
OR operations.
var foo = 1;
var bar = 0;
var baz = 2;
foo || bar ;
// returns 1 , which
is true bar || foo ;
// returns 1 , which
is true foo && bar ;
// returns 0 , which is
false foo && baz ;
// returns 2 , which
is true baz && foo ;
Be sure to consult the section called “Truthy and Falsy Things” for more
details on which values evaluate to true and which evaluate to false.
Note
You’ll sometimes see developers use these logical operators for flow
control instead of using if statements. For example:
// value of createBar ()
1 JavaScript Basics
This style is quite elegant and pleasantly terse; that said, it can be really hard
to read, especially for beginners. I bring it up here so you’ll recognize it in
code you read, but I don’t recommend using it until you’re extremely
comfortable with what it means and how you can expect it to behave.
Comparison Operators
Comparison operators
var foo = 1;
var bar = 0;
var baz = ’1 ’;
var bim = 2;
foo == bar ;
// returns
// returns
// returns
// returns true
// returns
// returns
// returns
// returns true
Conditional Code
Sometimes you only want to run a block of code under certain conditions.
Flow control — via if and else blocks — lets you run code only under
certain conditions.
Flow control
if ( bar ) {
if ( bar ) {
if ( foo ) {
} else {
// this code would run if foo and bar were both false
Note
1 JavaScript Basics
’0 ’;
’ any string
’; [];
// an empty
array {};
// an empty
object 1;
0;
’ ’;
// an empty string
null ;
undefined ;
// otherwise , set
foo to 0 var foo = bar ?
1 : 0;
While the ternary operator can be used without assigning the return value to
a variable, this is generally discouraged.
Switch Statements
Rather than using a series of if/else if/else blocks, sometimes it can be useful
to use a switch statement instead. [Definition: Switch statements look at the
value of a variable or expression, and run different blocks of code depending
on the value.]
A switch statement
switch ( foo ) {
case ’bar ’:
break ;
case ’baz ’:
break ;
default :
}
7
1 JavaScript Basics
’bar ’ : function () {
},
’baz ’ : function () {
},
’ default ’ : function () {
};
if ( stuffToDo [ foo ]) {
} else {
Loops
Note that in Loops even though we use the keyword var before the variable
name i , this does not “scope” the variable i to the loop block. We’ll discuss
scope in depth later in this chapter.
A for loop is made up of four statements and has the following structure:
[ loopBody ]
The initialisation statement is executed only once, before the loop starts. It
gives you an opportunity to prepare or declare any variables.
The conditional statement is executed before each iteration, and its return
value decides whether or not the loop is to continue. If the conditional
statement evaluates to a falsey value then the loop stops.
The iteration statement is executed at the end of each iteration and gives you
an opportunity to change the state of important variables. Typically, this will
involve incrementing or decrementing a counter and thus bringing the loop
ever closer to its end.
1 JavaScript Basics
var i = 0;
}
You’ll notice that we’re having to increment the counter within the loop’s body.
var i = -1;
Notice that we’re starting at -1 and using the prefix incrementer (++i).
This is almost exactly the same as the while loop, except for the fact that
the loop’s body is executed at least once before the condition is tested.
A do-while loop
do {
} while ( false );
These types of loops are quite rare since only few situations require a loop
that blindly executes at least once. Regardless, it’s good to be aware of it.
JavaScript Basics
Breaking and continuing
Usually, a loop’s termination will result from the conditional statement not
evaluating to true, but it is possible to stop a loop in its tracks from within
the loop’s body with the break statement.
Stopping a loop
if ( something ) {
break ;
You may also want to continue the loop without executing more of the
loop’s body. This is done using the continue statement.
if ( something ) {
continue ;
}
Reserved Words
JavaScript has a number of “reserved words,” or words that have
special meaning in the language. You should avoid using these words in
your code except when using them with their intended meaning.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
typeof
var
void
volatile
while
with
10
1 JavaScript Basics
Arrays
Arrays are zero-indexed lists of values. They are a handy way to store a set
of related items of the same type (such as strings), though in reality, an
array can include multiple types of items, including other arrays.
A simple array
// logs 2
var myArray = [ ’h ’ , ’e ’ , ’l ’ , ’l ’ , ’o ’
// [ ’h ’ , ’e ’ , ’l ’ , ’l ’ , ’o ’ ]
Objects
Objects contain one or more key-value pairs. The key portion can be any
string. The value portion can be any type of value: a number, a string, an
array, a function, or even another object.
var myObject = {
sayHello : function () {
},
myName : ’ Rebecca ’
};
// logs ’ hello ’
1 JavaScript Basics
Note When creating object literals, you should note that the key portion of
each key-value pair can be written as any valid JavaScript identifier, a string
(wrapped in quotes) or a number:
var myObject = {
validIdentifier : 123 ,
Functions
Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more
arguments, and can optionally return a value.
Function Declaration
Using Functions
A simple function
return text ;
};
};
greeting ();
12
1 JavaScript Basics
( function (){
})();
// undefined !
Functions as Arguments
};
};
myFn ( myOtherFn );
Testing Type
JavaScript offers a way to test the “type” of a variable. However, the result
can be confusing — for example, the type of an Array is “object”.
It’s common practice to use the typeof operator when trying to determining
the type of a specific value.
};
var myObject = {
foo : ’bar ’
};
var myArray = [ ’a ’ , ’b ’ , ’c ’ ];
13
1 JavaScript Basics
// returns ’
function ’ typeof
myObject ;
// returns ’
object ’ typeof
myArray ;
// returns ’ object ’ --
careful ! typeof myString ;
// returns ’ string ’;
typeof myNumber ;
// returns ’
number ’ typeof
null ;
// probably an array
}
if ( Object . prototype . toString . call ( myArray ) === ’[ object Array ] ’) {
// Definitely an array !
}
jQuery offers utility methods to help you determine the type of an
arbitrary value. These will be covered later.
2. If the function being invoked was created using Function.bind, this will be the first argument that was
passed to bind at the time the function was created.
var myObject = {
sayHello : function () {
},
myName : ’ Rebecca ’
};
var secondObject = {
myName : ’ Colin ’
};
1 JavaScript Basics
sayHello = function () {
myObject = {
myName : ’ Rebecca ’
};
},
myObject = {
myName : ’ Rebecca ’
},
secondObject = {
myName : ’ Colin ’
};
sayHello ();
// logs ’ Hi ! My name is
Rebecca ’ secondObject .
sayHello ();
Note
myObject : {
sayHello : function () {
myName : ’ Rebecca ’
};
15
1 JavaScript Basics
var myNamespace = {
myObject : {
sayHello : function () {
};
Scope
Furthermore, variables that are declared inside a function without the var
keyword are not local to the function — JavaScript will traverse the scope
chain all the way up to the window scope to find where the variable was
previously defined. If the variable wasn’t previously defined, it will be
defined in the global scope, which can have extremely unexpected
consequences;
};
sayHello ();
// logs ’ hello ’
console . log ( foo );
Code outside the scope in which a variable was defined does not have
access to the variable var sayHello = function () {
};
sayHello ();
// logs ’ hello ’
Variables with the same name can exist in different scopes with
different values
};
sayHello ();
// logs ’ hello ’
16
1 JavaScript Basics
};
foo = ’ world ’;
return myFn ;
};
f ();
// logs ’ world ’ -- uh oh
Scope insanity
var baz = 1;
bim ();
Closures
$ ( ’ <p > click me </ p > ’). appendTo ( ’ body ’). click ( function
() { alert ( i );
});
1 JavaScript Basics
};
Closures can also be used to resolve issues with the this keyword,
which is unique to each scope: Using a closure to access inner and
outer object instances simultaneously
var outerObj = {
myName : ’ outer ’ ,
outerFunction : function () {
// provide a reference to outerObj
// through innerFunction ’ s
closure var self = this ;
};
};
.......................................................................................5
Key Points
..................................................................................................................................
.......................................................................................................7
Key Points
..................................................................................................................................
About JavaScript
....................................................................................................................10
Key Points
..................................................................................................................................
10
4
A Tour of
JavaScript...............................................................................................................
Key Points
..................................................................................................................................
13
Project.......................................................................................................................
13
5
..........................................................................................18
Key Points
..................................................................................................................................
18
.............................................................................................21
Key Points
..................................................................................................................................
21
Project.......................................................................................................................
22
About Comments
....................................................................................................................25
Key Points
..................................................................................................................................
25
Project.......................................................................................................................
26
......................................................................................28
Key Points
..................................................................................................................................
28
Project.......................................................................................................................
29
.......................................................................................31
Key Points
..................................................................................................................................
31
Project.......................................................................................................................
31
.....................................................................................................33
Key Points
..................................................................................................................................
33
Project.......................................................................................................................
34
........................................................................................................35
Key Points
..................................................................................................................................
35
Project.......................................................................................................................
38
12
Comparisons.............................................................................................................
Key Points
..................................................................................................................................
40
Project.......................................................................................................................
41
13 Conditionals
............................................................................................................................42
Key Points
..................................................................................................................................
42
Project.......................................................................................................................
45
Project
2................................................................................................................................
46
14
Looping....................................................................................................................
Key Points
..................................................................................................................................
48
Project.......................................................................................................................
50
15 Arrays
..................................................................................................................................
Key points
..................................................................................................................................
53
Project.......................................................................................................................
55
.............................................................................................57
Key Points
..................................................................................................................................
57
Project.......................................................................................................................
58
........................................................................................................59
Key Points
..................................................................................................................................
59
Project.......................................................................................................................
60
18 String
Manipulation............................................................................................................
Key Points
..................................................................................................................................
61
Project.......................................................................................................................
65
19 Using Functions
......................................................................................................................66
Key Points
..................................................................................................................................
66
Project.......................................................................................................................
69
20 Logical Operators
...................................................................................................................71
Key Points
..................................................................................................................................
71
Project.......................................................................................................................
74
............................................................................................................75
Key Points
..................................................................................................................................
75
Project.......................................................................................................................
77
..............................................................................................................79
Key Points
..................................................................................................................................
79
Project.......................................................................................................................
80
.........................................................................................................81
Key Points
..................................................................................................................................
81
Project.......................................................................................................................
83
.............................................................................85
Key Points
..................................................................................................................................
85
Project.......................................................................................................................
86
............................................................................................88
Key Points
..................................................................................................................................
88
Project.......................................................................................................................
90
...............................................................................................91
Key Points
..................................................................................................................................
91
Project.......................................................................................................................
92
27 Focus and
Blur........................................................................................................................
Key Points
..................................................................................................................................
93
Project.......................................................................................................................
94
................................................................................................95
Key Points
..................................................................................................................................
95
Project.......................................................................................................................
95
.............................................................................................97
Key Points
..................................................................................................................................
97
Project.......................................................................................................................
98
Key Points
..................................................................................................................................
99
Project.......................................................................................................................
100
31 Javascript and
Forms........................................................................................................... 101
Key Points
..................................................................................................................................
101
Project.......................................................................................................................
103
....................................................................................105
Key Points
..................................................................................................................................
105
Project.......................................................................................................................
106
33 JavaScript and
Maths........................................................................................................... 108
Key Points
..................................................................................................................................
108
Project.......................................................................................................................
109
Key Points
..................................................................................................................................
111
Project.......................................................................................................................
112
Key Points
..................................................................................................................................
113
Project.......................................................................................................................
114
Key Points
..................................................................................................................................
116
Project.......................................................................................................................
118
..............................................................................................................121
Key Points
..................................................................................................................................
121
Project.......................................................................................................................
122
123
Project.......................................................................................................................
124
Key Points
..................................................................................................................................
126
Project.......................................................................................................................
128
Key Points
7
2 Server-side vs. Client-side
Key Points
o For most users, the web starts and ends with their choice
of web browser. The browser is said to define the client-
side of the web, with the browser, the computer it is running
on, and the user surfing the web being collectively referred
to as the client.
Like the client, the server application and the computer on which it runs define
the server-side of the web, and are collectively referred to as the server.
o When the server receives the request from the client for a
particular page, its job is to retrieve the page from the
computer’s files and serve it back to the client. In many
cases, this operation is a very simple procedure involving
little or no work on the part of the server.
o However, using a programming language like PHP, Perl or
Java, we can cause the server to either modify the page it
finds before it passes it back to the client, or even to
generate the page entirely from scratch. This is referred to as
a server-side application. The page passed back to the client
looks (to the client) exactly the same as any other page that
has not been modified.
o Server-side applications allow the developer to keep her code secure and secret,
thus allowing for more powerful applications to be created. In addition, since the
server running the code is always a known quantity, applications that run
successfully in one browser will run successfully in all browsers. However, despite
all this power, there is no direct way for a server-side application to alter a page
without
having to force the client-side to load another page. This
makes it completely impractical for things like drop-down
menus, pre-submission form checking, timers, warning
alerts and so forth.
10
3 About JavaScript
Key Points
Create special effects with images that give the impression that a button
Create custom pages “on the fly” without the need for
a server-side language like PHP.
11
JavaScript itself to detect the capabilities of the browser in which it finds itself, and
alter its
operation depending on the result.
12
13
4 A Tour of JavaScript
Key Points
<html>
<head>
<title>Chapter 4: A Tour of ↵
JavaScript</title>
</head>
<body>
</body>
</html>
o As a convention, when the notes intend that you should enter code all on one
line, they will use an arrow as above ↵ to indicate that you should not take a
new line at that point. With HTML, this is rarely important, but with
JavaScript, a new line in the wrong place can stop your code from working.
JavaScript for Beginners
14
<script language=”JavaScript” ↵
type=”text/JavaScript”>
… code …
</script>
o The script element above can be placed virtually anywhere you could place
any element in an HTML page – in other words, in either the head element or
the body element. It is most commonly placed in the former, though this is usually
so
that all your code can be easily found on the page.
<html>
<head>
<title> … </title>
<script language=”JavaScript” ↵
type=”text/JavaScript”>
</script>
</head>
15
o Save the file, and then try refreshing your page in the
browser window. Note that nothing has happened. This is
what we expected – all we have done so far is to set up an
area of the page to hold our JavaScript.
o Go back to NotePad and enter the following text between
the opening and closing script tags:
window.alert(“Hello world!”);
if ( confirm(“Go to Google?”) ) {
document.location = ↵
“http://www.google.com/”;
o Again, save your changes and refresh the page. For those with an eye to future
to check the condition of something (in this case, our response to a question) and
then to alter its behaviour based on what it finds.
HTML document has associated with it a number of events that can happen to
it. Links can be clicked, forms can be submitted, pages can be loaded and so
on.
function go_to_google() {
if ( confirm(“Go to Google?”) ) {
document.location = ↵
“http://www.google.com/”;
16
o Save and refresh, and note that nothing happens this time. This is because we have
enclosed the previous action (popping up a question and acting on the response)
within a function. A function is a block of code that is given a name – in this case,
the name is go_to_google() – and is only run when that name is “called”. It can be
o Save and refresh, and check that the link appears on the
page, and that it goes nowhere when clicked.
o For our final trick, add the following code to the body
section of the page, after the paragraph containing the link:
<body>
…
<script language=”JavaScript” ↵
type=”text/JavaScript”>
document.write(“<h2>Here’s another ↵
header!</h2>”);
</script>
17
o Save the page and refresh the browser. Note that we now
have a new line of text on the page – another header! We’ve
used JavaScript to create HTML and tell the browser to
display it appropriately. In this example, JavaScript has done
nothing that we couldn’t have done with a line of HTML, but
in future chapters we will see how we can use this to write
the current date and more.
18
Key Points
o Generally speaking, objects are “things”. For example, a piano
is an object.
o Properties are terms that can describe and define a
particular object. Our piano, for example, has a colour, a
weight, a height, pedals, a keyboard and a lid.
the adjectives, then methods are the verbs. Methods are actions that can be
performed on (or by) a particular object. To continue our piano example, you
could play a piano, open its lid, or press the sustain pedal.
o Many programming languages have similar ways of referring to objects and their
relationship with its properties and methods, as well as with other objects, can
19
piano.play();
piano.lid.open();
piano.pedals.sustain.press();
o Note that in some of the examples above, we have brackets () after each set of
words, and in some we don’t. This has to do with making sure that JavaScript can
understand what we say. o JavaScript works with objects throughout its existence
document.write(…);
document.location;
o In these examples, document is an object, while write is
a method and location is a property.
document.write(“Hello World”);
20
statement. All statements should end in a single semi-colon (;). JavaScript will
often ignore missed semi-colons
at the end of lines, and insert the semi-colon for you.
However, this can cause some unexpected results. Consider
the following:
document.write(“<h1>
Hello World!
</h1>”);
document.write(“<h1>;
Hello World!;
</h1>”);
Key Points
piano.paint(“green”);
piano.colour = “green”;
o Here we are no longer using a method to perform an action, we
are using what is known as an operator. In this case, the
operator has the symbol “=”, and is known as the
assignment operator.
22
Assignment
Function
x=y
x -= y
x *=y
x /=y
document.title += “!”;
Project
o Remove any existing JavaScript from your script tags, but leave the tags in
place ready for some new JavaScript.
JavaScript for Beginners
23
o Use your text editor to change the value of the title element
of the page as follows, then load your page into a browser
and view the result:
o Reload the page in your browser and note the title bar of
the window.
Properties</title>
o Now, remove your previous JavaScript statement and insert
the following:
document.title = ↵
window.alert(“message”);
24
o So, we can see that the first argument defines the text that appears as the
question in the prompt dialogue box. The
second argument is a little less clear. Try your code with different values and see
what difference your changes make. o Finally, we note that this prompt method
somehow takes the information typed into the box and passes it to our JavaScript
assignment. Say someone typed “Hello World” into the box. It would have been
25
7 About Comments
Key Points
26
alert(“hello”);
alert(“Hello World”);
// alert(“Hello World”);
alert(“Hello everyone!”);
Project
27
Key Points
your
code as HTML, with potentially embarrassing consequences.
29
o However, we can use the fact that <!-- denotes a single line comment in
JavaScript but a multi-line comment in HTML to ensure that our code is seen by a
… your code
// stop hiding
code --> </script>
o This prevents older browsers from displaying the code, but what if we want to
replace this with some comment. For example, let’s say we had a bit of code that
displayed the time of day and greeted our user by name. Without JavaScript and
using the method above, there would simply be a blank on the page where the
o We can use the <noscript> tag to cause our code to “fail gracefully”
For example:
<noscript>
</noscript>
<script>
… code to customise
header // stop hiding code -
-> </script>
Project
30
31
Key Points
Project
o Make sure both files are saved in the same folder, and that
you have chapter_9.html open in your editor.
o Remove all script from between the script tags, except for
your browser hiding lines. Make sure that the script tags are
still in the head section of the page.
into a browser.
32
33
Key Points
o All of these boxes are the result of methods of the window object. This object is
the highest level object that JavaScript can deal with in a browser. As such, all
other objects on a page (with a few exceptions) are actually properties of the
window
object.
window.document.write(“…”);
document.write(“…”);
window.alert(“…”);
alert(“…”);
34
window.alert( message );
window.confirm( message );
Project
o Clear the previous redirection code, and ensure that the script tags have been
o Add a new statement to the script on the page that will display the following
message before the rest of the page is shown:
Welcome to my website! Click OK to continue.
document.write(alert(“hello world”));
Make sure that you place this particular snippet of code in script tags within
the body area of the page, as we are generating text output to be rendered
by the browser. Also, note the use (or not) of quotes here. More next
chapter!
JavaScript for Beginners
35
Key Points
36
o Variable name rules are straightforward – no spaces, names must start with a
BrowserName
page_name
Message1
MESSAGE1
o In many browsers, JavaScript is case-sensitive, which means that the last two
variables in the example above are distinct variables. It is a good idea to pick a
particular naming style for your variables, and to stick to it within your projects.
o Strings
o Boolean Values
1+2 = 3
numBrowserVersion = 5.5;
numTotal += 33;
Message = “Hello!”;
Message = “Goodbye”;
Message = 3;
o Note that the last three examples show that variable values
can be altered after their initial assignment, and also that the
type of value stored in a variable can be altered in a similar
manner.
alert(Message);
alert(“Message”);
o As well as using variables for storage and access, we can combine and
a = 12;
b = 13;
c = a + b; // c is now 25
c += a; // c is now 37
string and got a string as a result. JavaScript is smart enough to realise that a
Operator
Function
x+y
x–y
x*y
Multiplies x and y
x/ y
Divides x by y
x% y
x++
assignment
++x
Adds 1 to x BEFORE any associated
assignment
x--
assignment
--x
Project
39
40
12 Comparisons
Key Points
o Comparison operators compare two values with each other. Most commonly,
they are used to compare the contents of two variables – for example we might
want to check if the value of var_1 was numerically greater than that of var_2.
var_1 = 4;
var_2 = 10;
In this case, the value of var_3 is false. Note that the Boolean value of false is
Comparison
Function
X == y
Returns true if x and y are equivalent, false
otherwise
X != y
false otherwise
X>y
41
X >= y
x, false otherwise
X <= y
Project
13 Conditionals
Key Points
43
o These three parts are represented in JavaScript as follows:
if ( conditional_test )
JavaScript statement;
JavaScript statement;
JavaScript statement;
else
JavaScript statement;
JavaScript statement;
JavaScript statement;
o Everything from the first closing curly bracket (or brace) is optional, so the
following is also a valid conditional prototype:
if ( conditional_test )
JavaScript statement;
JavaScript statement;
JavaScript statement;
alert(“Variable 1 is greater”);
else
alert(“Variable 2 is greater”);
44
o Note that the above condition is not necessarily always correct.
Consider the case where var_1 is equal to var_2. In that
alert(“Variable 1 is greater”);
else
alert(“Variable 2 is greater”);
alert(“Variable 1 is greater”);
}
else
alert(“Variable 2 is greater”);
else
45
if ( var_1 > 4 )
var_2 = var_1;
else
var_2 = 4;
var_2 = 4;
var_2 = var_1;
}
o However, an even more compact way of writing this could be
Project
46
figure out how. Hint – how might you use a variable called
greeting?
Project 2
Exam Result
Result Message
90 or more
Between 70 and 89
Between 55 and 69
Just passed.
54 or below
Key Points
i = i + 1;
i = i - 1;
i = i + 35;
incr = 10
i = i + incr;
o To keep things concise, we can use the following shortcuts:
i++; // equivalent to i = i + 1;
i--; // equivalent to i = i + 1;
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
8
(9)
10
(11!)
o In JavaScript, we say almost the same thing. The following code will display
the numbers 1 to 100 on the page:
for
( i = 1; i <= 100; i++ )
document.write(“<p>” + i “ </p>”);
JavaScript for
Beginners 50
o The for statement tells the browser that we are about to perform a loop. The
layout here is very similar to a conditional statement, but in this case we have
much more information in the brackets. Where our conditional had one JavaScript
o An incrementer – this defines the action to be performed at the end of each loop.
conditional and a for loop is that the condition is constantly being changed and re-
for
for
o In this case, the loop will run once, but the value of i will be
2, as after the first run, i will be incremented to 2, and will
then fail the test and so the loop will exit. If we use the
following:
for
Then the loop will run once, and the value of i afterwards
will be 1, as we might hope.
Project
name chapter_14.html.
o Clear all JavaScript code from your script tags.
JavaScript for Beginners
51
15 Arrays
Key points
o Take, for example, days of the week. In each day we perform a number of tasks,
so we could want to record each task as a separate item under a group called, say,
Monday’s Tasks.
This modification creates an array with 7 empty boxes. However, arrays will
expand and contract to the required size in JavaScript, so the cases where you will
o The most often-used way of creating an array is to use “square bracket” notation.
Square brackets play a large role in the use of arrays, so this is often the easiest
method to remember:
arrDays = [“Monday”,”Tuesday”];
alert(arrDays[0]);
Note the lack of quotes around the 0 here. This line of code
is equivalent to:
alert(“Monday”);
arrDays[2] = “Tuesday”;
arrDays[3] = “Wednesday”;
how_many_days = arrDays.length;
o As well as properties, arrays have very useful methods. If you
arrDays.sort();
Note that the sort method works on the actual array itself, over-
writing the current values. So, if you had an array with
each day of the week as an element, calling its sort method
would mean that arrDays[0] was then equal to “Friday”,
not “Monday”.
Project
o Open your previous project file, and save it under the name
chapter_15.html.
o Use a for loop to iterate through each array element in turn, and print the value
of the element to the screen (hint, consider the use of array[i], where i is the for
loop’s counter).
o The above method (the use of a for loop to iterate through a series of array
Key Points
alert(arrDays[“Wednesday”]);
o This looks a lot like our previous discussion of objects and properties. In fact,
since an array is actually an object, we can access its elements as though they
were properties:
remind you of Wednesday’s task alert(arrDays.Wedensday);
o Note a subtle difference here – in our previous, numeric array examples, the
names of the week days were the values of our array elements. Here, the names
Monday: task
Tuesday: task
etc…
Key Points
o Referring back to our mailbox analogy, where our array could be pictured as a
row of mailboxes, each with its own contents and label, a two dimensional array
other.
array_3[“firstArray”] = array_1;
array_3[“secondArray”] = array_2;
alert(array_3[“secondArray”][3]);
alert(array_3.secondArray[3]);
Project
o Open your previous project file, and save it under the name
chapter_17.html.
o Modify one of your week arrays to consist not of single elements, but of arrays
of hours from 8am to 5pm. This then represents a three dimensional array. We
o Finally, alter your code to prompt the user for three values – a week, a day and
an hour. Store these values in three separate variables, and use those variables to
display the requested task, or else to display an error message if a task cannot be
found.
18 String Manipulation
Key Points
var_2 = var_1.indexOf(“Karen”);
var_2 = var_1.indexOf(“Aaronofsky”);
real_name = “Karen”;
real_name.toLowerCase(); try_name =
try_name.toLowerCase(); if (
try_name.indexOf(real_name) > -1 )
{
alert(“Hello Karen!”);
else
alert(“Welcome “ + name);
Method
Behaviour
String.indexOf(“str”)
counterparts
String.toUpperCase()
counterparts
String.match(/exp/)
JavaScript for a
browser to use? Regular expressions allow us to do just that.
/^.+@.+\..+$/
if ( var_1.match(/^.+@.+\..+$/) )
else
o There are a few problems with this code at the moment – for example, it will
Project
o Use a document.write statement to output the results of each of the various string
o In the latter case, output the failed string as well so that the user can see their
input and modify it next time, if appropriate.
19 Using Functions
Key Points
function name_of_function( )
JavaScript can live, but must be called after the function has
been declared. For example, if you declare a function in the
body of a document and then call it from the head of the
document, you may find that the browser returns an error
message. For this reason, most JavaScript programmers
define any functions they are going to use between <script>
tags in the head section of their pages to ensure that they are
all defined before they are used.
o Functions are to object methods as variables are to object
properties – they are also called in a similar manner. To run
the code contained in the name_of_function function above,
we would use the following line of code:
name_of_function();
alert(message);
}
o Whenever the function is called, it will greet the user named.
greet_user(“Anisa”);
or
var_1 = prompt(“Name?”, “”);
greet_user(var_1);
var_1 = false;
if ( address.match(/^.+@.+\..+$/) )
var_1 = true;
if ( check_email(address) )
var_1 = false;
if ( address.match(/^.+@.+\..+$/) )
var_1 = true;
return var_1;
}
o Since var_1 is either true or false, the returned value will
be Boolean. We can even skip the use of the variable here
and be more direct:
if ( address.match(/^.+@.+\..+$/) )
return true;
return false;
return address.match(/^.+@.+\..+$);
o The above function may not seem like a great saving. After
return address.match(/^.+@.+\..+$);
if ( check_email(address) )
with:
if ( address.match(/^.+@.+\..+$/) )
o While the benefits here are not obvious, consider the case where, at some point
in the future, you discover a better method of checking for email addresses. In
the second case abov, you will have to search your code for each and every
instance of that method, and replace it with your new method, which may not be
one line of code. In the first case, you will just have to change the underlying
Project
o Now use a variable in the body area to store the return value
of a prompt asking the user for a message. Use this variable as
the argument to a single instance of show_message.
o Define a new function in the head area called get_message. It should take no
argument, but should replicate the function of your prompt in the body area and
message = get_message();
71
20 Logical Operators
Key Points
if ( x > some_value )
{
…expressions…
}
if ( x > val_1 )
…do something…
else
if ( x > val_2 )
o The above code achieves what we want – for the second branch, x must lie
between val_2 and val_1 (assuming val_1 is greater than val_2, of course).
However, it’s rather unwieldy, and does not scale elegantly to checking three
in this case, the result is false. Note here that only the first
condition is actually checked. Since and requires both
comparisons to be true, as soon as it finds a false one it
stops checking. This can be useful.
in this case, the result is true. Any one of the three being
true will provide this result.
o As we can see from the last example, this method of checking
scales to any number of conditions. We can also mix
and match the operators. For example:
Project
should call both of the previous functions, store their results in a variable, and
Key Points
o So far, our scripts have run as soon as the browser page has loaded. Even when
we have used functions to “package” our code, those functions have run as soon
as they have been called in the page, or not at all if no call was made. In other
words, the only event our scripts have so far responded to has been the event of
o Every time a user interacts with the page, the browser tells JavaScript about an
“event” happening. That event could be a mouse click, a mouse pointer moving
to a new part of an HTML form, the user leaving the page, the user
submitting a form and so on.
Event Handler
Occurs When…
onload
onunload
onmouseover
onclick
element
onmouseup
element
o The last three are related, but there are subtle differences – onclick is defined as
being when both mousedown and mouseup events happen in the given element’s
area. For example, if you click on an area of the page, that registers the area’s
mousedown event. If you then hold the mouse down and move to another area
before releasing, it will register the other area’s mouseup event. The browser’s
o We can use this method to attach any event handler listed above to the
elements of the page. In addition to calling functions (with any optional
arguments, of course), we can write JavaScript directly into our event
handlers:
Project
o Open your previous project file, and save it under the name
chapter_21.html.
window.status = msg;
o When called, this function will set the text displayed in the browser’s status bar
(the part of the window below the page content) to whatever is passed as an
argument. For example, to set the status bar to display “Welcome”, we would call:
set_status(“Welcome”);
o Now define the following function immediately below the last:
function clear_status( )
set_status(“”);
}
o When called, this function will clear the status bar. Notice that
we are using our previous function within the new one. This is a common
onmouseover=”set_status(‘hello’);” ↵
onmouseout=”clear_status();”>testing</a>
o Now, alter the code to have the link point at a real website
that you know of.
o Clicking on the link now will take you away from the page.
function confirm_link( )
return check;
onclick=”return confirm_link();”
o By using the word return in our event handler, the response of the function will
be used to decide whether the rest of the normal action is run. In this case, if
document.getElementById(“theLogo”)
our_logo = document.getElementById(“theLogo”);
our_logo.height
our_logo.width
our_logo.src
our_logo.src = “new_logo.gif”;
Project
o In the head area script element, define a function called describe_image() that
\n
for example
Key Points
o With what we have learned so far, we already have the ability to create a simple
o The mouse moves offer the image and the alternative image
is loaded into place.
o As you may have realised, we are going to use JavaScript to alter the src
attribute of the image tag. The best way to think of this is to picture the <img>
tag as simply a space on the page into which an image file can be loaded. The
src attribute tells the browser which image to load into the space, and so if we
document.getElementById(“button”);
button_img.src = “new_image.jpg”;
o We can directly insert this code into the image’s event handler:
onmouseover= ↵
”document.getElementById(‘button’).src ↵
= ’new.jpg’;”>
o Note that this code is suddenly very convoluted. There are two immediate potential
solutions. The first is to define a function:
function swap_image( id, new_image )
img = document.getElementById(id);
img.src = new_image;
onmouseover= ↵
”swap_image(‘button’, ‘new.jpg’);”>
o This is a much cleaner solution, and more importantly we can use this for any
onmouseover= ↵
”swap_image(‘button’, ‘new.jpg’);” ↵
onmouseout= ↵
”swap_image(‘button’, ‘old.jpg’);”>
img.src = new_image;
”swap_image(this, ‘new.jpg’);”>
o Note a couple of things. Firstly, this has no quotes around it
– we are using it like a variable name. Secondly, our function now uses the first
argument directly, instead of using it to get the relevant object from the page.
We can do that because
document.getElementById(‘button’), although
is obviously much shorter!
Project
o Open your previous project file, and save it under the name
chapter_23.html.
o contacts.jpg
o home.jpg
o people.jpg
o products.jpg
o quotes.jpg
o whatsnew.jpg
o Add a text link to a new paragraph between the two paragraphs. The link
should be a “dummy” link (ie use “#” as its href attribute value), but when the
mouse moves over it, the image above it should change to show rocollogo.gif.
o Moving the mouse away from the text link should return
the logo to its previous state.
Key Points
tag, the browser has to load this image from scratch. On our local machine, this
will not cause an appreciable delay, but when dealing with a remote server (as
we will be on the Internet), this delay can lead to a noticeable “lag”, which can
destroy the feeling of a dynamic interface. o Ideally, we would like to instruct the
browser to load any alternate images when it loads the page. This will allow us
to ensure that the new images are sitting on the user’s computer, ready to be
o Each <img> tag on the page has a corresponding Image object in JavaScript. We
have looked at ways of manipulating this directly, and have an idea of some of the
properties an Image
object can have.
o We have seen this sort of syntax before – the use of the new keyword when we
created our Arrays. new tells JavaScript that we are creating a new object. The
virtual_image part of the assignment is just a variable name. In this case, the
o To use this variable to preload our images, we take advantage of the fact that it
virtual_image.src = “contactsover.jpg”;
Project
<body onload=”preload_images();”>
o Once you have verified that the image swapping still works as
expected, expand your preload_images function to define an
array of images to preload, and then use a for loop to move
through the array and assign each image to the src property
of an object variable. Hint: an object variable can be
anything that can store information – for example an array
element. o Check your work in your browser.
Key Points
”param1,param2,param3,param4…”
window.open(“http://news.bbc.co.uk/”, ↵
“bbc”, “width=300,height=300”);
o Some available parameters are given in the table below:
Parameter
Value
Function
location
Yes/no
menubar
Yes/no
displayed
status
Yes/no
displayed
width
Pixels
height
Pixels
Specifies the height of the new window
resizable
Yes/no
scrollbars
Yes/no
window.open(“http://www.bbc.co.uk/”, ↵
“bbc”, “”);
is equivalent to:
window.open(“http://www.bbc.co.uk/”, ↵
“bbc”, “scrollbars=yes”);
Project
o Open your previous project file, and save it under the
name chapter_25.html.
Be called RocolLogo
o Remove all event handlers from the link, and add a new one
to run the function above when the link is clicked.
Property
Description
availHeight
Windows Taskbar)
availWidth
window.open(“index.html”, “window_name”, ↵
“width=200,height=200,left=”+var_left+ ↵
“top=”+var_top);
win_width = 200;
win_height = 200;
win_left = (screen.availWidth/2) ↵
- (win_width/2);
win_top = (screen.availHeight/2) ↵
- (win_height/2);
Project
Key Points
new_window.focus();
o It turns out that, within JavaScript, each object has an individual property for
onclick=”do_something();” />
<script>
document.getElementById(“test_img”).onclick= ↵
do_something();
</script>
use:
new_window.onfocus = some_function();
Project
images/rocollogo.gif.
Key Points
“params…”);
For example:
new_win.document.write(“<html><head>”);
new_win.document.write(“<title>demo</title>”):
new_win.document.write(“</head><body>”);
new_win.document.write(“<h1>Hello!</h1>”);
new_win.document.write(“</body></html>”);
Project
o Open your previous project file, and save it under the name
chapter_28.html.
o Modify your existing script to create a third window with
the following properties:
Key Points
referring to the window you wish to close, you can simply use:
new_window.close();
New Logo
the parent window’s object variable pointing to the appropriate new window. Its
close()
method should then be invoked.
Key Points
o JavaScript can easily save us from having to type lots of HTML. As we have
seen, we can use JavaScript to generate large form elements and tables using a
small amount of code. This is good news for us, as it makes our work easier. It is
also
good news for our visitors, as they only have to download a small amount of code
we have one function that will generate a year drop down menu for a form’s
date of birth section, we need to include that function in every page that requires
it. This means that our visitors are downloading identical content multiple times.
<script language=”JavaScript” ↵
type=”text/JavaScript” ↵
src=”s/script_file.js”></script>
The language and type attributes are essential here. The script tag
Project
Key Points
computations) and JavaScript can ensure that only correct data is sent to the
</form>
document.getElementById(‘testForm’);
objForm = document.getElementById(‘Enquiry’);
strValue = objForm.Name.value
or
→ action=”process.php”…
intervention, the form’s data is sent straight to the server for processing. But
you can intercept the data (so you can process it with JavaScript) before it is
sent, by including the onsubmit event handler in the <form> tag. This enables
→ action=”process.php”
→ onsubmit=”functionName()”>
o In the above example, when the user clicks on the
Submit button, the function functionName() is run first,
then the data is sent to the server.
onsubmit=”return functionName();”
Project
o Open your previous project file, and save it under the
name chapter_31.html.
o Clear any content from the body element of the page, and ensure that the
head area script element has no code in it. o Save a copy of this page as
“success!”.
have an id of jsCourseForm.
Sorry chum!
Try again.
Handlers
Key Points
o Each form object (e.g. text, button etc) has a set of properties associated with it.
o You can assign the data stored in a text box called Name
which is included in the form with id Enquiry, to a variable
like so:
variable = document.getElementById(‘Enquiry’).
→ Name.value
Method
Description
blur()
focus()
select()
Method
Description
blur()
focus()
click()
Event handler
onblur
onfocus
onselect
The user selects some of the text within
onchange
Event handler
onBlur
onFocus
onClick
document.getElementById(‘Enquiry’).submit();
Project
o Open your previous project file, and save it under the
name chapter_32.html.
If the user types in the name “Bugs Bunny”, the function submits the form
Key Points
Method
Returns
Math.cell()
Math.cell(2.2).
Math.floor()
Math.round()
Math.sqrt()
o If you are not sending the data to the server, there is no need
to include either the Action or Method attributes in the
<FORM> tag, though by default the Action will usually submit
to the current page, and the Method will be set to “get”.
Project
o Open your previous project file, and save it under the
name chapter_33.html.
o Copy and paste the entire contents of max_wins.html into your current
Generate two random numbers when the button is pressed. Display the
winner.
o When studying the code, note that the form has no valid
Find a way to use a Math method to compare the two entered integers.
Once compared, the function should then place the appropriate value of
Key Points
oPlayer1 =
→ document.getElementById(“MaxWins”).Player1
oPlayer1.value
document.getElementById(“MaxWins”).Player1.value
variables. So:
oPlayer1 =
→ document.getElementById(“MaxWins”).Player1.value
Project
Key Points
o The HTML <select> form tag enables you to create a menu
<form id=”menu”>
<select name=”Product”>
</select>
</form>
value of the select box. This is then used for further processing – either by
document.getElementById(“menu”).Product.value
Event handler
onblur
onfocus
The select box receives the focus
onchange
o The way to invoke action(s) when the user selects an option from a select box is
to prepare a JavaScript function which will be invoked using the select object’s
Project
o Create a form in the body area of the page. Give the form an
id of jumpMenu.
o In the form, place a select element. Give the select element the
<select name=”menu”>
</select>
Value
Label
http://www.bbc.co.uk/
The BBC
http://www.google.com/
http://www.hotmail.com/
Hotmail
http://www.ed.ac.uk/
http://www.apple.com/
Apple Computer
http://www.microsoft.com/
Microsoft Corporation
Selections
Key Points
specified otherwise) was “”. If the user doesn’t actively make another selection,
then you can check the value of the selection box before sending it to the server.
o Another example is the case of a set of radio buttons. Imagine that for an
imaginery company, an order form contained two form elements – a selection box
to specify which product was being ordered and two radio buttons to specify
o As the name is identical for each radio button in the set, you can’t access an
individual radio button by using its name. But you can access it using the standard
array notation:
oOrderForm.Format[i]
oOrderForm.Format[i].checked
FormatSelected = false;
oOrderForm =
→
document.getElementById(“OrderForm”);
for ( i=0; i < oOrderForm.Format.length; i++
)
{
if ( oOrderForm.Format[i].checked )
FormatSelected = true;
}
function SetFormat ()
oOrderForm =
→ document.getElementById(“OrderForm”); if (
oOrderForm.Product.value ==
→ “Greek Boat” )
oOrderForm.Format[0].checked = true;
name of the group of radio buttons and the value of the first
ratio button is Slide.
oFormObject.reset()
Project
o Copy and paste the entire contents of order_form.html into your current
o Add an event handler to the form element on your page that will invoke a
function called check_form() when the form is submitted. This function will
o Create the check_form() function in the head area script element. The
• Return false
• Return false
o The Greek Fishing Boat is only available in Slide format. Add an event
handler to the select element which will run a function called set_format()
when its value is changed. o Create the function set_format() in the head area
script
element. The function should check first what the value of
the menu is. If it is the Greek Fishing Boat, it should then
check to see if the Slide radio button is checked. If it is not,
then the function should correct this.
if ( error != “” )
+ error);
return false;
}
else
return true;
Key Points
o The date object stores all aspects of a date and time from
year to milliseconds.
o To use a new date object, you must create it and assign it to an object variable
o You can specify your own parameters for the date object
when you create it:
);
theDate =
is a valid date.
Project
o Now modify your script so that it also writes the date and
time 17th July 1955 1:00am to the page in standard date and
time format. Do this by entering the appropriate parameters
into the new Date() constructor.
o Now, using parameters once again, add a new line to your
script that will display midnight on 17th July 2004 on
a separate line under the existing date.
Date Objects
Key Points
Method
Returns
getDate()
getDay()
getFullYear()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
o For example:
minute, 60 minutes in an hour and 24 hours in a day, you can establish the number
of days (or hours or minutes etc) between two dates by subtracting on date in
millisecond format from the other in millisecond format. To achieve the units you
require, perform the appropriate division (so for the number of minutes, divide the
result of the subtraction first by 1000, then by 60), and then use Math.floor() on
Project
Use a new date object, along with the arrays and the
appropriate date methods to write today’s date to the
page in the following format:
Below the time, write the number of days since the start
of the millennium in the following format:
o Finally, call your function from the body area script element on your page, and
check your work in your browser.
39 Creating a JavaScript Clock
Key Points
window.setTimeout(“functionName()”, 1000)
firstTimeout =
window.setTimeout(“functionName()”, 1000)
window.setTimeout(“window.close()”, 5000);
window.clearTimeout(firstTimeout);
function annoy_me( )
window.alert(“BOO!”);
annoy_me();
timeout that doesn’t yet exist. So, you have to check first whether a timeout is in
operation. One way of doing this is to set a Boolean variable to true whenever the
clock is started. By checking this variable before you attempt to clear the timeout,
you know whether or not the clock is running and therefore can be stopped.
10:59:59 am
changing to:
11:0:0 am
11:00:00 am
as we might expect.
s = theDate.getSeconds;
s = ( s < 10 ) ? “0” + s : s;
var = ( condition )
? value if true :
value if false;
Note that this has been split over three lines to aid reading.
In practice (see above) we can place this on one line for
ease of use.
Project
o Open your previous project file, and save it under the name
chapter_39.html.
clockBox, and two form input buttons labelled Start and Stop.
o In the head section scrip element, create two empty functions –
Display the formatted time in the text field on the page. Create a timeout
false.
o While this should work (test your code!), you’ll notice that
the output is a little ugly. Displaying the time in a text field is
not the most unobtrusive way to show a clock on a page.
<span id=”clockBox”></span>
o <span> is an HTML tag that allows you to mark areas of content without any
o However, all content tags in HTML (like <p> , <h1> , <div> etc) have
a special property when they are returned as
o We can use this to alter the content of the tags. For example, if our previous input-
field solution had the following code:
clk = document.getElementById(“clockBox”);
clk.value = formatted_time;