JavaScript Course Notes PDF
JavaScript Course Notes PDF
JavaScript Course Notes PDF
Course notes
A Tour of JavaScript...............................................................................................................13
Key Points ....................................................................................................................................................... 13
Project.............................................................................................................................................................. 13
12 Comparisons...........................................................................................................................40
Key Points ....................................................................................................................................................... 40
Project.............................................................................................................................................................. 41
13 Conditionals ............................................................................................................................42
Key Points ....................................................................................................................................................... 42
Project.............................................................................................................................................................. 45
Project 2........................................................................................................................................................... 46
14 Looping....................................................................................................................................48
Key Points ....................................................................................................................................................... 48
Project.............................................................................................................................................................. 50
15 Arrays ......................................................................................................................................53
Key points ........................................................................................................................................................ 53
Project.............................................................................................................................................................. 55
18 String Manipulation.................................................................................................................61
Key Points ....................................................................................................................................................... 61
Project.............................................................................................................................................................. 65
Key Points
o A programming language is a set of codes that we can use to
give a computer instructions to follow.
o Popular and well-known programming languages include Java,
C++, COBOL, BASIC, LISP and more. Most popular
programming languages consist of words and phrases that are
similar in form to the English language.
o A well-written program will be easily readable by anyone with
a little programming experience, regardless of whether they
have any direct experience of the language in question. This is
because modern programming languages share a large number
of common concepts. In particular, they all have a notion of
variables, arrays, loops, conditionals, and functions. We will
meet these concepts again in more depth later in the course.
o Traditionally, programming languages have been used to write
(for the most part) stand-alone applications. Things like
Microsoft Word, Mozilla Firefox and Lotus Notes are all
examples of such applications. Once installed on a PC, these
applications run without necessarily requiring any other
software to be installed alongside them.
o Web Applications differ from these traditional applications in
many respects, but the most striking is that they all run inside
your web browser. Examples of popular web applications are
things like Google, Hotmail, Flickr, GMail and any of the vast
array of weblogging systems.
Key Points
o The World Wide Web is built on a number of different
technologies.
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.
o Consider a client who has decided to visit the web site at
www.google.com. The first thing that happens is that the client
will make a request to Googles web server for the default
page of that web site.
o The web server is an application running on a computer
owned by Google. 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
computers 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.
10
About JavaScript
Key Points
o JavaScript is an interpreted, client-side, event-based, objectoriented scripting language that you can use to add dynamic
interactivity to your web pages.
o JavaScript scripts are written in plain text, like HTML, XML,
Java, PHP and just about any other modern computer code. In
this code, we will use Windows NotePad to create and edit
our JavaScript code, but there are a large number of
alternatives available. NotePad is chosen to demonstrate
JavaScripts immediacy and simplicity.
o You can use JavaScript to achieve any of the following:
11
12
13
A Tour of JavaScript
Key Points
o Lets start with a quick tour of the major features of
JavaScript. This chapter is intended to be a showcase of what
JavaScript can do, not an in depth investigation into the
deeper concepts, so dont worry too much if you get lost or
dont understand the code youre typing in!
Project
o Our JavaScript is all going to be written using NotePad.
Open NotePad and save the resulting empty document in your
user drive as chapter_4.html.
o
o Save your new webpage, and view it in your web browser. For
the moment, use Internet Explorer to view this page. To do
this, find your saved file on your user drive, and double-click
on it. This will open the file in Internet Explorer by default,
and let you see the header youve just created.
o So far, we havent done anything beyond the scope of HTML.
Lets add some JavaScript to the page.
o There are (generally speaking) three places in a web page
where we can add JavaScript. The first of these is between a
new set of HTML tags. These script tags take the following
form:
<script language=JavaScript
type=text/JavaScript>
code
</script>
14
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!);
o Save your changes, and again refresh your page in the browser
window. Welcome to the world of JavaScript!
o Go back to notepad and remove the window.alert line you
just added. Now add the following, slightly more complex
code:
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 chapters, this is an example of a conditional
statement, where we ask JavaScript 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.
o Now, both of these bits of JavaScript have run uncontrollably
when the page has loaded into the browser. In most cases, we
will want to have more control over when our JavaScript does
what we ask it to.
o This control is the domain of events. In a browser, every
element of an 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.
o Modify the previous lines of JavaScript in your script
element to match the following:
function go_to_google() {
if ( confirm(Go to Google?) )
document.location =
http://www.google.com/;
}
}
o Save and refresh, and then click on the link. This is an example
of an event handler. When the link is clicked (onclick), our
browser says the magic words go_to_google(), and our
function is invoked.
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>Heres another
header!</h2>);
</script>
16
o Save the page and refresh the browser. Note that we now have
a new line of text on the page another header! Weve used
JavaScript to create HTML and tell the browser to display it
appropriately. In this example, JavaScript has done nothing
that we couldnt 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.
17
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.
o Note from the above that an objects properties can be
properties themselves. So we have the case where a piano lid is
a property of the piano, but is also an object in its own right,
with its own set of properties for example, the lid has a
colour, a length, and even a state of either open or closed.
o If objects are the nouns of a programming language and
properties are 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 properties or methods. In general, they are
hierarchical, and an objects relationship with its properties
and methods, as well as with other objects, can often be easily
seen from the programming notation.
o In JavaScript, we use a dot notation to represent objects and
their properties and methods. For example, we would refer to
our pianos colour in the following way:
piano.colour;
19
20
21
Key Points
o While objects and methods allow us to do things on a page,
such as alter the content or pop up dialogue boxes to interact
with the user, in many cases we will want to alter the value of
one of an objects properties directly. These cases are akin to
painting our piano green.
o Given our discussion on methods so far, we might expect to be
able to alter our objects properties by using a method for
example, the following would seem logical:
piano.paint(green);
green;
22
a new title;
Function
x=y
x += y
x -= y
x *=y
x /=y
o Not all assignment operators work with all types of values. But
the addition assignment operator works with both numbers and
text. When dealing with numbers, the result will be the sum of
the two numbers. When dealing with text (technically called
strings), the result will be the concatenation of the two
strings:
document.title += !;
Project
o Open your previous project file, and save it under the name
chapter_6.html.
o Remove any existing JavaScript from your script tags, but
leave the tags in place ready for some new JavaScript.
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:
<title>With a little help from</title>
o Reload the page in your browser and note the title bar of the
window.
o If the display looks odd, consider your use of spaces
o All we have so far is an example that does nothing more than
HTML could manage. Lets introduce a new method of the
window object to help us to add a little more dynamism and
interaction to the script. Change the value of the title tag as
follows:
<title>Chapter 6: Assigning Values to
Properties</title>
23
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.
24
25
About Comments
Key Points
o Repeat after me : Comments are important. Comments are
important. Comments are important.
o Adding comments to your code is always good practice. As the
complexity of your scripts grows, comments help you (and
others) understand their structure when you come to view the
code at a later date.
o A lot of code created quickly is said to be write only code, as
it suffers from an inherent lack of structure or commenting.
Debugging such code, or reusing it months later, becomes
maddeningly impossible as you try to remember what a certain
line was supposed to do, or why using certain values seems to
stop your code from working.
o Comments are completely ignored by JavaScript and have no
effect on the speed at which your scripts run, provided they are
properly formed.
o Comments can slow the loading of your page, however many
coders keep a development copy of their code fully
commented for editing, and remove all comments from their
code when they finally publish it.
o There are two types of comment in JavaScript single line
comments, and multi-line comments.
o Single line comments begin with two forward-slash characters
(//), and end with a new line:
// this is a comment
alert(hello); // so is this
o Note two things: firstly, this use of the HTML comment format
does not require a closing --> tag. Secondly, this is only a one
line comment, unlike its use in HTML, which comments all
lines until the closing comment tag.
o You can add multiple-line comments by enclosing the
comment block between /* and */. For example:
/* all of this text is going to be
ignored by JavaScript. This allows us to
write larger comments without worrying about
having to individually comment out each
line */
alert(Hello World);
/* a one line, mult-line comment */
o This can be very useful if you are trying to track down an error
in your code you can comment out each suspect line in
turn until you manage to get your code working again.
Project
o Open your previous project file, and save it under the name
chapter_7.html.
o Add the single line comment
This is my first comment
26
27
28
Key Points
o Very old browsers dont understand JavaScript. There are very
few such browsers in use today, but two factors force us to
continue to consider environments that may not be able to cope
with our JavaScript code.
o Firstly, all modern browsers allow users to control whether
JavaScript code will be run. In many cases, users will not have
any say over their company policy, and may not even know
that their work machine has had JavaScript disabled.
o Secondly, not all of your visitors will be using browsers that
can make any use of JavaScript. Braille displays, screen
readers and other non-visual browsers have little use for many
JavaScript tricks. In addition, search engines like Google will
ignore any JavaScript you use on your pages, potentially
hiding important content and causing your pages to remain unindexed.
o Browsers that dont support JavaScript are supposed to ignore
anything between the opening and closing script tags.
However, many break this rule and will attempt to render 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 JavaScript-savvy browser, but
ignored as commented-out HTML by anything else:
<script>
<!-- hide
your code
// stop hiding code -->
</script>
Project
o Open your previous project file, and save it under the name
chapter_8.html.
o Add two lines to your code to ensure that it will not confuse
older browsers or browsers where the user has disabled
JavaScript.
30
31
Key Points
o We have already briefly seen the use of browser redirection in
chapter 4.
o To formulate the idea more completely, in order to redirect the
user to a different page, you set the location property of the
document objects.
o
Project
o Open your previous project file, and save it under the name
chapter_9_redirect.html.
o Save another copy of the file, this time called
chapter_9.html.
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.
o Now, add a single statement to this script that will
automatically redirect the user to the page
chapter_9_redirect.html as soon as the page is loaded
into a browser.
32
10
33
Key Points
o So far, we have seen brief examples of alert, prompt and
confirm dialogue boxes to request a response from the user,
and to pause all code in the background until the request is
satisfied.
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.
o Because of this ubiquity, its presence is assumed even if it is
omitted. Thus, where we technically should write:
window.document.write();
Project
o Open your previous project file, and save it under the name
chapter_10.html.
o Clear the previous redirection code, and ensure that the script
tags have been returned to the head section of the document.
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.
34
11
35
Key Points
o We have been introduced to the concepts of objects and their
various properties and methods. These inter-related concepts
allow any web page to be broken down into little snippets of
information or data, which can then be accessed by JavaScript
and, in many cases, changed.
o However, what if we want to create our own storage space for
information that doesnt necessarily have a page-based
counterpart? For example, what if we wanted to store the
previous value of a documents title property before changing
it, so it could be retrieved later, or if we wished to store the
date time that the page was loaded into the browser for
reproduction in several places on the page, and didnt want to
have to recalculate the time on each occasion?
o Variables are named containers for values within JavaScript.
They are similar to object properties in many ways, but differ
importantly:
o In a practical sense, variables have no parent object with
which they are associated.
o Variables can be created (declared) by you as a developer,
and can be given any arbitrary name (within certain rules)
object properties, however, are restricted by the definition of
the parent object. It would make no sense, for example, for our
piano object in the previous chapters to have a propeller
property!
36
37
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.
o Once a variable has been created and a value stored within, we
will want to be able to access it and perhaps manipulate it. In a
similar manner to object properties, we access our variables
simply by calling them:
Message = Hello World!;
alert(Message);
o
= 12;
= 13;
= a + b; // c is now 25
+= a; // c is now 37
= b + Hello!; // c is now 13 Hello!
38
Function
x+y
xy
x*y
Multiplies x and y
x/y
Divides x by y
x%y
-x
x++
++x
x--
--x
Project
o Open your previous project file, and save it under the name
chapter_11.html.
o Clear the previous JavaScript code, and ensure that the script
tags are contained in the body section of the document.
o
Now, modify your code to produce the same result but without
requiring a third variable.
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.
o
In this case, the value of var_3 is false. Note that the Boolean
value of false is not the same as the text string false:
var_4 = false; // Boolean value
var_5 = false; // Text string
Function
X == y
X != y
X>y
41
X >= y
X<y
X <= y
both of these are equivalent, but one may make more semantic
sense in a given context than the other.
Project
o Open your previous project file, and save it under the name
chapter_12.html.
o Ensure that your two variables both have numerical values in
them and not strings.
o Use an alert box to display the result of a comparison of your
two variables for each of the comparison operators listed
above.
o Substitute one of the numerical values for a text string and
repeat the procedure. Note the differences.
42
13
Conditionals
Key Points
o Up until now, our JavaScript projects have been unable to alter
their behaviour spontaneously. When a page loads with our
JavaScript embedded within, it is unable to do anything other
than what we expect, time and again.
o The only difference we have seen is in the use of a prompt box
to alter what is shown on a page. However, the page essentially
does the same thing with the text provided, regardless of what
text is typed in.
o What would be really handy would be to give JavaScript a
mechanism to make decisions. For example, if we provided a
prompt box asking the visitor for their name, it might be nice
to have a list of known names that could be greeted
differently from any other visitors to the site.
o Conditional statements give us that ability, and are key to
working with JavaScript.
o A conditional statement consists of three parts:
o A test (often with a comparison operator, or comparator) to
see if a given condition is true or false.
o A block of code that is performed if and only if the condition is
true.
o An optional block of code that is performed if and only if the
condition is false.
}
else
{
JavaScript statement;
JavaScript statement;
JavaScript statement;
43
44
)
1 is greater);
)
2 is greater);
Project
o Open your previous project file, and save it under the name
chapter_13.html.
o Clear all JavaScript code from your script tags.
o Create two variables and assign numerical values to them.
45
Project 2
o In many cases, the brevity of your conditional statements will
rely on your ability to formulate the right questions to
consider when performing your tests. Try to make your
solution to the following problem as concise as possible.
o Clear all of your current code from the script tags.
o Ensure that your script tags are currently situated in the body
section of the page.
o Create a variable called exam_result and store a numerical
value of between 0 and 100 in it.
46
47
Result Message
90 or more
Between 70 and 89
Between 55 and 69
Just passed.
54 or below
48
14
Looping
Key Points
o The letters i, j and k are traditionally used by programmers to
name variables that are used as counters. For example, at
different stages of the program, i may contain the numbers 1,
2, 3 etc.
o
49
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(11!)
50
will always perform the script in the braces, and will probably
cause errors in the browser.
o Note too that it is very common to start counting at zero in
JavaScript. The reason for this is that it is often desirable to
count how many times an operation has been performed.
Consider the following:
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
o Open your previous project file, and save it under the name
chapter_14.html.
o Clear all JavaScript code from your script tags.
51
52
53
15
Arrays
Key points
o In many cases, variables will completely satisfy our data
storage needs in JavaScript. However, in a large number of
cases, we may wish to group variables into a collection of
related items.
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, Mondays Tasks.
o In JavaScript, to achieve this we would store each task in a
separate variable, and then group those variables together into
an array.
o An array is a special type of JavaScript object that can store
multiple data values unlike a variable, which can only store
one data value at a time.
o It could be helpful to think of an array as a row of mail boxes
in an office, just as you might think of a variable as a single,
solitary mail box.
o The boxes in an array are numbered upwards, starting at box
number 0 note that counting begins at 0 here, just as we
discussed in the previous chapter. The number assigned to each
box is known as its index.
54
Note the lack of quotes around the 0 here. This line of code is
equivalent to:
alert(Monday);
Not only can we access the value of an array element using this
notation, but we can also assign the value as well:
arrDays[2] = Tuesday;
arrDays[3] = Wednesday;
Project
o Open your previous project file, and save it under the name
chapter_15.html.
55
56
16
57
Key Points
o
Project
o Open your previous project file, and save it under the name
chapter_16.html.
o Clear all JavaScript code from your script tags.
o Write a new script which creates a new, seven element
associative array called Week:
o Use the days of the week as indexes for each element of the
array.
o Assign a task to each day of the week as each associative
element is created.
o Use a for loop to display a calendar on the page, as follows:
Monday: task
Tuesday: task
etc
o Modify your code to use a prompt box to ask the visitor to
choose a day, and display on the page the task allotted to that
day.
58
17
59
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 can be thought of as a series
of these rows of mailboxes, stacked on top of each other.
o In reality, a two dimensional array is simply an array in
which each element is itself an array. Each sub array of a
two dimensional array can be of a different length in other
words, the two dimensional array doesnt have to be square.
o
You can access the contents of each sub array by using two
pairs of square brackets instead of just one. An example will
illustrate this best:
array_1 = [element, element 2];
array_2 = [another element, 2, 98, true];
array_3 = [array_1, array_2];
alert(array_3[1][3]);
// displays 98
Project
o Open your previous project file, and save it under the name
chapter_17.html.
o Building on your previous project, create a number of new,
seven element associative arrays to represent 4 separate weeks.
o Combine these 4 weeks into a four element array to represent a
month.
o Modify your previous code to take a week number and print
out all that weeks activities to the page.
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 can extend arrays to
be n-dimensional, where n is more or less arbitrary.
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.
60
61
18
String Manipulation
Key Points
o Throughout your use of JavaScript in a production
environment, you will often use it to read values from
variables, and alter a behaviour based on what it finds.
o We have already seen some basic string reading in the section
on comparisons where we test for equality. However, this allor-nothing approach is often not subtle enough for our
purposes.
o Take the case where we want to check a users name against a
list of known users. If the user enters their name as Karen,
for example, that will be fine if and only if they spell the name
precisely as we have it recorded, including capitalisation etc. If
the user decides to type in her full name, say Karen
Aaronofsky, the code will not recognise her.
o In this case, we want to see if the text Karen appears at all in
the string. We call this substring searching, and it can be
incredibly useful.
o One of the simplest substring searches is done by using the
indexOf method. Every string-type variable has this method
associated with it. Consider this code:
var_1 = Karen Aaronofsky;
var_2 = var_1.indexOf(Karen);
62
Behaviour
String.indexOf(str)
String.charAt(x)
63
String.toLowerCase()
String.toUpperCase()
String.match(/exp/)
64
o There are a few problems with this code at the moment for
example, it will pass the string [email protected] quite happily, which is
clearly wrong. We will look at ways around this later on in the
course.
Project
o Open your previous project file, and save it under the name
chapter_18.html.
o Clear all JavaScript code from your script tags.
o Use a prompt box to capture some user input to a variable
called check_string.
o Use a document.write statement to output the results of each of
the various string methods when applied to the user input.
o Check the user input to see if its an email address, and alter
your output accordingly to either Thats an email address or
That doesnt look like an email address to me!
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.
65
66
19
Using Functions
Key Points
o A function is a named set of JavaScript statements that
perform a task and appear inside the standard <script> tags.
The task can be simple or complex, and the name of the
function is up to you, within similar constraints to the naming
of variables.
o
or
var_1 = prompt(Name?, );
greet_user(var_1);
67
68
The above function may not seem like a great saving. After all,
we are using four lines of code to define a function that
performs only one line of code. Compare:
function check_email( address )
{
return address.match(/^.+@.+\..+$);
}
if ( check_email(address) )
{
do some email things
}
with:
if ( address.match(/^.+@.+\..+$/) )
{
do some email things
}
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 function definition, and the
upgrade will be effective throughout your code without you
having to update each occurrence.
Project
o Open your previous project file, and save it under the name
chapter_19.html.
o Clear all JavaScript code from your script tags.
o Ensure that you have a script element in the head area of your
document, and one in the body area.
o In the head area, define a function called show_message. This
function should take one argument, called message, and
should use an alert box to display the contents of the argument.
o In the body area, call the function with various messages as
arguments.
69
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 ask the user for a message
via a prompt box.
o
70
71
20
Logical Operators
Key Points
o
> val_1 )
something
> val_2 )
something else
72
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.
( 100 > 10 || 9 < 8 )
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:
( ( 100 > 200 && 100 > 300 ) || 100 > 2 )
in this case, the and condition evaluates to false, but since
either that or the last condition has to be true to return true, the
overall condition returns true as 100 is indeed greater than 2.
o This sort of complex logic can take a while to comprehend,
and will not form a set part of the course. However, it is useful
to be aware of it.
73
Project
o Open your previous project file, and save it under the name
chapter_20.html.
o Clear all JavaScript code from your script tags.
o Ensure that you have a script element in the head area of your
document, and one in the body area.
o Copy the file available_plugins.js from the network
drive (your tutor will demonstrate this), and open it using
NotePads File > Open command.
o Copy and paste the entire contents of
available_plugins.js into your current project file, into
the script element in the head area of your page.
o Have a read through the code. Note that it defines a large, two
dimensional array. The array has a list of various components
that can be present in web browsers (such as Flash or
Quicktime)
o Add a function to the head area script element, called
flash_exists(). This function should use a for loop to
check each of the elements of the available_plugins array
and establish if Flash is present.
o Add a further function to the head area script element, called
quicktime_exists(). This function should also use a for
loop to check each element of the array, this time returning
true if Quicktime is present.
o Finally, add a function to the head area script element called
both_quicktime_and_flash_exist(). This function
should call both of the previous functions, store their results in
a variable, and produce an alert box containing the message:
o Both Quicktime and Flash if both functions returned true; or:
o One of Quicktime or Flash is missing if either of the
functions return false.
o Call the final function from the body area script element.
o Check your results in your browser.
74
75
21
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 our page loading into the browser window.
o Most of the time, however, you will want your code to respond
specifically to user activities. You will want to define
functions, and have them spring into action only when the user
does something. Enter event handlers.
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 over or out of a given
element (such as an image or a paragraph), a user tabbing to a
new part of an HTML form, the user leaving the page, the user
submitting a form and so on.
o An event handler is a bit of JavaScript code that allows us to
capture each event as it happens, and respond to it by running
some JavaScript code.
o In general, we attach event handlers to specific HTML tags, so
a mouse click on one element of the page might be captured by
an event handler, but clicking somewhere else might do
something completely different, or indeed nothing at all.
o Some common event handlers are in the table below:
Event Handler
Occurs When
onload
76
onunload
onmouseover
onmouseout
onclick
onmousedown
onmouseup
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 elements area. For
example, if you click on an area of the page, that registers the
areas mousedown event. If you then hold the mouse down and
move to another area before releasing, it will register the other
areas mouseup event. The browsers click event, however,
will remain unregistered.
o In theory, we can add most of these event handlers to just
about any HTML tag we want. In practise, many browsers
restrict what we can interact with.
o We will mostly be attaching event handlers to <img>, <a> and
<body> tags.
o
o Note the potential issue with quote marks here if you use
double quotes around your event handler, you need to use
single quotes within and vice versa.
Project
o Open your previous project file, and save it under the name
chapter_21.html.
o Clear all JavaScript code from your script tags.
o Ensure that you have a script element in the head area of your
document, and none in the body area.
o
When called, this function will set the text displayed in the
browsers 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 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 programming technique that allows us to define
functions of specific cases using more general functions.
o
Now, add the following HTML to the body area of your page.
Remember, were adding HTML here, not JavaScript, so do
not be tempted to use script tags for this part of the project:
<a href=#
onmouseover=set_status(hello);
onmouseout=clear_status();>testing</a>
77
78
79
22
Key Points
o
Project
o Copy the folder called images from the network drive to your
project folder.
o Open your previous project file, and save it under the name
chapter_22.html.
o Clear all JavaScript code from your script tags.
o Ensure that you have a script element in the head area of your
document, and none in the body area.
o Within the body area of your page, create an image element
that loads an image from the images folder. Give the element
an appropriate id attribute.
o In the head area script element, define a function called
describe_image() that will pop up an alert box containing the
following information about your image:
the image file used
the image width
the image height
o
To have each bit of text appear on a separate line, you can add
the following character to your alert text:
\n
for example
alert(line one\nLine two);
o
80
81
23
Key Points
o A simple image rollover is an effect which happens when the
mouse appears over an image (usually a linked button) on the
page. The original image is replaced by another of equal size,
usually giving the effect that the button is highlighted in some
way.
o With what we have learned so far, we already have the ability
to create a simple image rollover effect. All that remains is to
clarify the particulars of the process:
o The page is loaded and the original image appears on the page
as specified by the <img> tags src attribute.
o The mouse moves offer the image and the alternative image is
loaded into place.
o The mouse leaves the image and the original image is loaded
back.
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 change that value, the image will be changed.
o In other words, the id attribute of the <img> tag is naming the
space, not the image.
We can directly insert this code into the images event handler:
<img src=old.jpg id=button
onmouseover=
document.getElementById(button).src
= new.jpg;>
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;
}
82
Project
o Copy the folder called buttons from the network drive to
your project folder.
o Open your previous project file, and save it under the name
chapter_23.html.
o Clear all JavaScript code from your script tags.
o Ensure that you have a script element in the head area of your
document, and none in the body area.
83
contacts.jpg
home.jpg
people.jpg
products.jpg
quotes.jpg
whatsnew.jpg
84
24
85
Key Points
o So far we have seen a very simple example of an image
rollover. It is functional and works as desired, but it is lacking
in a few finer details.
o Specifically, when we use JavaScript to change the src
attribute of an <img> 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 users computer,
ready to be swapped in and out instantly.
o To do this, we need to look at object variables and object
instantiation (or creation). In particular, we need to look at
the Image object.
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 However, we can create Image objects directly in JavaScript,
without the need for a corresponding <img> tag on the page.
When we create such an object, and set its src property, the
browser will load the appropriate file into memory, but will not
display the image on the page.
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 variable is
an Object Variable, since it contains an object.
o
Project
o Open your previous project file, and save it under the name
chapter_24.html.
o Starting with your previous code, create a new function called
preload_images in the head area script element of your page.
o Use this function to create seven new image objects, and use
each objects corresponding object variable to preload your
over image variations.
o Check your work in your browser to ensure that the image
swapping still works as expected.
o
86
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.
87
25
88
Key Points
o
o As we can see from the above prototype, there are only three
arguments that this method can take. However, the
parameters argument is actually more complex than we
might assume:
param1,param2,param3,param4
89
we can use the object variable win to alter the new window
through JavaScript.
o
Value
Function
location
Yes/no
menubar
Yes/no
status
Yes/no
width
Pixels
height
Pixels
resizable
Yes/no
scrollbars
Yes/no
is equivalent to:
<a href=http://www.bbc.co.uk/ target=bbc>
90
Project
o Open your previous project file, and save it under the name
chapter_25.html.
o Remove all functions and HTML from your previous file,
leaving only the logo image and the link.
o Create a function in the head area script element called
view_new_logo. This function should:
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.
o Once you have verified that a window pops up as required
when the link is clicked, test each parameter from the table
above in the function.
91
26
Key Points
o The screen object provides you with access to properties of the
users computer display screen within your JavaScript
applications.
o Some of the available properties are:
Property
Description
availHeight
availWidth
colorDepth
height
width
Project
o Open your previous project file, and save it under the name
chapter_26.html.
o Modify your existing code to ensure that the logo appears
centred on the users screen. If possible, do not modify your
original function by doing anything more than two new
functions get_win_left( width ) and
get_win_top( height ).
92
93
27
Key Points
o
94
Project
o Open your previous project file, and save it under the name
chapter_27.html.
o Modify your function to open another window as well as the
original one, with the following features:
28
95
Key Points
o Its quite easy to create a new page on demand using
JavaScript. In this context, we are talking about creating a
completely new page in a window without loading any file into
that window.
o
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.
96
29
97
Key Points
o The window objects close() method enables you to close a
window. If you have an object variable in the current window
referring to the window you wish to close, you can simply use:
new_window.close();
98
Project
o Open your previous project file, and save it under the name
chapter_29.html.
o Modify your existing script to achieve the following:
30
99
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 for a relatively large amount of content.
o However, we can do better. As it is, if we have one function
that will generate a year drop down menu for a forms 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. In addition, if we change or
improve our function, we have to ensure that we update that
function in every page that has it included.
o HTML allows us to solve this problem by providing a
mechanism to load an external text file into the HTML page
and treat its contents as JavaScript code. Since it is a separate
file, once it has been downloaded once, the browser will not
download further copies of the file if it is requested by another
page. In other words, we can load all our JavaScript code into
one file, and any changes there will instantly be reflected
across the entire site.
o
100
Project
o Open your previous project file, and save it under the name
chapter_30.html.
o Move all your JavaScript function definitions, and any other
code in the head section script element to a new file called
script.js.
o Modify your head section script element to load code from the
new file.
o Check that your page still works as expected.
o NOTE: the .js file extension is just a naming convention.
<script> tags will load JavaScript from any text file (hence
the need to include the type and language attributes). However,
it is a widely used convention, and it is worth sticking to in
order to keep your code easily understood by anyone who may
work on your code in the future.
101
31
Key Points
o Without JavaScript, the server handles all validating and
processing of information submitted via a form. Using
JavaScript on the client side of the equation saves time for the
user and creates a more efficient process.
o Some processing can be handled by JavaScript (for example,
mathematical computations) and JavaScript can ensure that
only correct data is sent to the server for processing.
o JavaScript is used in conjunction with server-side processing
it is not a substitute for it.
o
o There are two ways of sending form data to the server. Using
the method attribute, you can specify either the GET or the
POST methods:
<form id =enquiryform method=GET
or
<form id =enquiryform method=POST
102
103
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 processing_31.html, and put
an <h1> element in the body area saying success!.
o Now, close your processing_31.html page and create a
form on your original chapter_31.html page using HTML
if you have difficulty with this, the tutor will provide an
example to duplicate. Your form should:
have an id of jsCourseForm.
104
o If the user enters the correct name, however, the form should
submit without interruption.
o Check your work in your browser.
32
105
Key Points
o Each form object (e.g. text, button etc) has a set of properties
associated with it. This is different for each form element.
The value property is common to most form elements and is
one of the most useful properties.
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
o Form objects also have methods associated with them. The set
of available methods is different for each form object.
o Below is a list of commonly used methods for the text object:
Method
blur()
focus()
select()
Description
Removes the focus from the text box
Gives the focus to the text box
Selects the text box
Description
Removes the focus from the button
Gives the focus to the button
Calls the buttons onclick event handler
106
Project
o Open your previous project file, and save it under the name
chapter_32.html.
o Modify your form in the following way:
107
108
33
Key Points
o The Math object is a pre-defined JavaScript object containing
properties and methods which you can use for mathematical
computation.
o Below is a selection of some useful Math methods:
Method
Math.cell()
Returns
The smallest integer greater than or equal to a number.
That is, it rounds up any number to the next integer.
Math.cell(2.6) returns 3 and so does
Math.cell(2.2).
Math.floor()
Math.max(n1,n2)
Math.min(n1,n2)
Math.random()
Math.round()
Math.sqrt()
109
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 Remove all content from the body section of the page.
o Copy the file max_wins.html from the network, and open it
using NotePads File > Open command.
o Remove all JavaScript code from the script element in the head
section of the page.
110
34
111
Key Points
o Referring to objects can be a lengthy process. Consider the
Player 1 text box in the previous example. You refer to it in
full as follows:
document.getElementById(MaxWins).Player1
Once assigned, you can use the object variable in any situation
where you would use the specific object itself. Using the object
variables from the previous paragraph:
oPlayer1.value
112
o Bear in mind that you assign objects to object variables. You would
assign a text box or a button or an image etc to an object variable and
then refer to that objects properties as shown above
(oPlayer1.value). You dont assign text or string values to object
variables. So:
oPlayer1 =
document.getElementById(MaxWins).Player1.value
Project
o Open your previous project file, and save it under the name
chapter_34.html.
o Modify the function in the head area script element in the
following way:
All specific object which are referred to more than once are
each assigned their own object variable at the start of the
function.
35
113
Key Points
o
114
o As you would expect, the select option has methods and event
handlers associated with it:
The blur() method removes the focus from the select box.
o The available event handlers for the select object are given
below:
Event handler
onblur
onfocus
onchange
o
Project
o Open your previous project file, and save it under the name
chapter_35.html.
o Clear the head section script element of JavaScript, and
remove all content from the body area of the page.
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
following values and labels eg:
<select name=menu>
<option value=value>label</option>
</select>
Value
http://www.bbc.co.uk/
http://www.google.com/
http://www.hotmail.com/
Label
The BBC
Google
Hotmail
115
http://www.ed.ac.uk/
http://www.apple.com/
http://www.microsoft.com/
o
36
116
Key Points
o Form data may be invalid if it is sent to the server without
certain information for example, if the user has omitted to
select an item from a menu. Better not to bother processing,
than to waste the time of the user and server by trying to
process the invalid information.
o In the case of a selection box, one way of validating is to
include a null value for the default option. In the previous
project, the default value of the selection box (always the first
option unless specified otherwise) was . If the user doesnt
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 whether it was
being ordered as a photographic print or as a slide.
o Lets say the id of the order form is OrderForm and the name
of each radio button is Format. (Remember that in HTML,
radio buttons in a set are related to each other by their name
that must be the same for each related radio button).
o The radio object is an array where each element of the array
stores information relating to each of the radio button objects
(remember, counting starts at 0).
o As the name is identical for each radio button in the set, you
cant access an individual radio button by using its name. But
you can access it using the standard array notation:
oOrderForm.Format[i]
117
Finally, to reset all form objects to their initial state, use the
reset() method:
oFormObject.reset()
Project
o Open your previous project file, and save it under the name
chapter_36.html.
o Remove all content from the body section of the page.
o Copy the file order_form.html from the network, and open
it using NotePads File > Open command.
o Remove all JavaScript code from the script element in the head
section of the page.
118
119
Return false
Return false
120
After all checks have been made, if we have caught any errors, the
value of error will no longer be . Thus, we can use the
following code to report all errors at once:
if ( error != )
{
alert(The following errors were found: \n\n
+ error);
return false;
}
else
{
return true;
}
121
37
Key Points
o The date object stores all aspects of a date and time from year
to milliseconds.
o
You can specify your own parameters for the date object when
you create it:
theDate = new Date(
year, month, day, hours,
minutes, seconds, mseconds
);
o The first three parameters are mandatory, while the rest are
optional:
theDate = new Date(2004,6,17);
is a valid date.
Project
o Open your previous project file, and save it under the name
chapter_37.html.
o Remove all content from the body section of the page.
o Create a function in a head section script element that displays
an alert box containing the current date and time. Have this
function called from a body section script element.
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.
o Finally, using the string approach in the date object, add a new
line to your script which will display midnight on 31st
December 1999 on a separate line under the existing
information and in standard date and time format.
122
123
38
Key Points
o Below is a selection of some useful methods which enable you
to retrieve some useful information from date objects:
Method
Returns
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
124
o For example:
dtNow = new Date();
document.write(dtNow.getTime());
Project
o Open your previous project file, and save it under the name
chapter_38.html.
o Clear any JavaScript from the pages script elements.
o Create a function in the head section script element that
performs the following:
Use a new date object, along with the arrays and the
appropriate date methods to write todays date to the page
in the following format:
Today it is: dayName, month, dayNumber.
for example:
Today it is Tuesday, October 17.
125
Below the time, write the number of days since the start of
the millennium in the following format:
It is n days since the start of the millennium.
o Finally, call your function from the body area script element
on your page, and check your work in your browser.
39
126
Key Points
o setTimeout() is a method of the window object. In its
common form, it enables you to run any JavaScript function
after an allotted time (in milliseconds) has passed. For
example:
window.setTimeout(functionName(), 1000)
changing to:
11:0:0 am
127
as we might expect.
o We can use a shortened form of the if conditional to make this
simple. For example:
s = theDate.getSeconds;
s = ( s < 10 ) ? 0 + s : s;
o What is happening here? First, we get the current value of the
seconds and store that in a variable called s. Next, we reset
the value of s depending on the condition in the brackets. The
prototype of this form of the if conditional is:
var = ( condition )
? value if true
: value if false;
Project
o Open your previous project file, and save it under the name
chapter_39.html.
o Remove all content from the body section of the page.
o In the body section, create a form input element with the id
clockBox, and two form input buttons labelled Start and Stop.
o In the head section scrip element, create two empty functions
start_clock() and stop_clock().
o Before the two function definitions, as the first statement of the
script element, create a variable called timer, and assign it a
value of null.
128
129
130