JavaScript Handout
JavaScript Handout
JavaScript gives you the freedom to add interactivity and responsiveness to your web pages.
The aim of this tutorial is to provide you with a thorough, yet accessible introduction to JavaScript
using snappy explanations and practical tasks to try out right from the start.
No prior knowledge of JavaScript is assumed, but because JavaScript sits within and manipulates
web pages, in order to be able to follow along, you should already be familiar with HTML and CSS.
If you are new to either or both, you’re advised to step through our HTML and CSS tutorials first.
JavaScript is a lightweight, easy to learn, scripting language. It’s used on almost every website to
respond to user actions, validate web forms, detect browser support, and much more.
JavaScript is a web programming language, that is, a language that enables you, the designer of
your website, to control how a web page behaves. This makes JavaScript crucially different from
HTML, the language that gives structure to your web documents, and CSS, the language that
controls the appearance of web pages.
If you know other programming languages such as PHP, most programming concepts and basic
JavaScript syntax will sound quite familiar to you. However, if this is not the case, don’t worry:
by following along and experimenting with the code, at the end of this hands-on tutorial you’ll
be able to spruce up your static web pages with fun effects and fantastic responsiveness for the
joy of your website visitors.
If you need help along the way, don’t forget to turn to our forums. This is where you meet the real
experts who are willing and ready to offer tips, suggestions and advice.
What is needed?
To bring to life your web pages with JavaScript all you need is a text editor and an updated,
standard-compliant browser of your choice, such as Internet Explorer 9, Firefox, Chrome, Safari,
or Opera, to mention just the most popular ones.
Basic free text editors that ship with your operating system such as Notepad (on Windows) and
Text Edit (on Mac) will do just fine. However, text editors that offer programming languages
support, such as the free Notepad++ (for Windows users) and TextWrangler (for Mac users), might
be a great resource when ploughing through more than a few lines of code.
Ready to supercharge your web pages with JavaScript? Let’s get started!
1
Lesson 1: What is JavaScript?
The first thing that creates some confusion about JavaScript is its name. In fact, one of the most
common questions students raise when approaching JavaScript is:
Clearing up this basic but important question is our first order of business in this lesson, but by no
means the only one. By the end of this lesson you will also know:
Java (developed by Sun Microsystems) is a powerful and much more complex programming
language in the same category as C and C++.
JavaScript was created by Brendan Eich at Netscape and was first introduced in December
1995 under the name of LiveScript. However, it was rather quickly renamed JavaScript, although
JavaScript’s official name is ECMAScript, which is developed and maintained by theECMA
(European Computer Manufacturer's Association) International organization.
The fact that the JavaScript interpreter is the browser engine itself accounts for some
inconsistencies in the way your JavaScript-powered page might behave in different browsers. But
don't worry: thankfully, well-established techniques and powerful JavaScript libraries such
as jQuery (which will be introduced in later lessons) are here to make things wonderfully easier
on us.
2
JavaScript runs in the client, that is, the brower. If you use an older browser without support for
JavaScript, or if you simply choose to disable JavaScript in your browser, then a JavaScript script
can't work.
Conclusion: unlike what happens with languages that run on the server, such as PHP, you never
fully know for sure the impact that the browser your website visitors are going to use will have on
your script, or whether your visitors will choose to turn JavaScript support off.
You can't access or affect resources from another internet domain with JavaScript.
This is called the Same Origin Policy. Well, how would you like it if all of a sudden all the nice
comments your visitors left on your website started to disappear, or to change place in your page
because of a naughty JavaScript script running on another website?
This is exactly the kind of nasty situation that the Same Origin Policy is designed to prevent.
Conclusion: your JavaScript script can only access resources in your website.
Because JavaScript is a client-side language, it's limited to what can be done in the client, that is,
usually in the browser environment. A JavaScript script cannot access server resources such as
databases.
3
Zillion things you can do with JavaScript
With JavaScript you can:
Say you want to display a nice thank you message to a user who has just submitted a comment
form on your website. Obviously, the message needs to be added after the user has submitted
the form.
You could let the server do that. However, if your website is very busy and your server processes
hundreds of forms a day, it might take a little while for your thank you message to appear to the
user.
Here's JavaScript to the rescue. Because JavaScript runs in the user's browser, the thank you
note can be added and displayed on the page almost instantaneously, making your website users
happy.
Web environments are dynamic, things happen all the time: the web page loads in the browser,
the user clicks a button or moves the mouse over a link, etc. These are called events (which will
be the topic of lesson 3).
With JavaScript you can make the page immediately react to these events the way you choose:
for example, by showing or hiding specific page elements, by changing the background color, etc.
You can use a JavaScript script to detect the visitor’s browser, or, even better, you can detect what
features a certain browser does or does not support. Depending on the browser and its capabilities,
you can choose to load a page specifically tailored to that kind of browser (lesson 14).
Create cookies.
A JavaScript script is great if you want to create cookies so that your visitors can enjoy a
personalized experience the next time they visit your website (lesson 15).
You can use a JavaScript script to validate form data before the form is submitted to a server. This
saves the server from extra processing (lesson 16).
Learning JavaScript will enable you to add cool animation effects to your web pages without using
an external Flash plug-in, use the newest features of HTML5 such as canvas (to draw directly on
4
your web page) and drag and drop capabilities, integrate your website with external web services
such as Facebook, Twitter, etc.
Summary
In this lesson you learned what JavaScript is, who invented it, and that the body responsible for
its maintenance and continuous development is ECMA. Now you know what you cannot do with
JavaScript, but also the great things that you can do with it.
"That's all well and good. I'm convinced, JavaScript is fantastic. But, how can I start using it in my
HTML page?"
The HTML
To insert a JavaScript script in an HTML page, you use the <script> ... </script> tag. Don't forget
the closing </script> tag! Now get ready to fire off your text editor of choice and let's get coding!
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
</body>
</html>
The JavaScript script is inserted either in the HTML page itself or in a separate file.
5
Embed JavaScript in the HTML page
The <script> tag and its type attribute tell the browser: "Hey, browser! There's a script coming up,
and it's a JavaScript script."
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript">
//JavaScript code goes here
</script>
</head>
<body>
</body>
</html>
Or or at the very bottom of the document just before the closing </body> tag, like so:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
<script type="text/javascript">
//JavaScript code goes here
</script>
</body>
</html>
If you're wondering whether it's best to place your <script> tag in the <head> or the <body> tag,
then you're not alone.
It mostly comes down to personal preference. However, because most of the times you'll want
your JavaScript code to run after the web page and all its resources, e.g., stylesheets, graphics,
videos, etc., have finished loading in the browser, I suggest you dump your JavaScript <script> tag
at the bottom of your page.
When a comment spans over more than one line, you use /* Comment goes here */ to delimit a
comment, just like you do in a stylesheet. Here's how it's done:
6
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
<script type="text/javascript">
/* JavaScript code
goes here */
</script>
</body>
</html>
When the JavaScript interpreter in your browser comes across either '//' or '/* */', it just ignores
whatever text is placed in between. Use comments in your code to remind your future self of what
your code is designed to do. One day you'll be happy to have done so, just take my word for it!
In fact, just like having your CSS all in one place, well away from HTML code, having your
JavaScript in its own file will give you the advantage of easily maintaining and reusing your scripts.
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript" src="yourjavascript.js"></script>
</head>
<body>
</body>
</html>
As you can see, the <script> tag references an external file, "yourjavascript.js" that has
the .js extension and contains the script that puts the magic into your web page.
7
Try out: embedded JavaScript in an HTML page
Between the <script> and </script> tags either in the <head> or the <body> of your HTML
document, add the following line of code, just after the comment:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
<script type="text/javascript">
//JavaScript code goes here
alert('Hello World!');
</script>
</body>
</html>
This is your first JavaScript statement, that is, you've just instructed your web page to do
something. Don't worry about the code just yet, we'll be coming back to the alert() command again
and again in the following lessons.
Just notice the semicolon ( ; ) at the end of the statement. This is important: it tells the JavaScript
interpreter that the statement is finished and whatever comes next is a different statement.
Now save your work and run the page in your favorite browser. You'll see an alert box popping up
on page load. This is how the page looks in Firefox:
If your alert box is not popping up, then check that you've typed the JavaScript command exactly
as it is in the sample code.
Make sure your <script>...</script> tags are there, that the text between the brackets
is surrounded by quotes (' '), and that there is a semicolon ( ; ) at the end of the statement.
Then try again.
8
Try out: JavaScript in a separate file
Create a new document in your text editor and save it as "helloworld.js". Important: the file
extension has to be .js (this is the appropriate JavaScript file extension).
In the new document, paste in the JavaScript command from the previous example (no need to
type the <script> ... </script> tags here):
alert('Hello World!');
Now, go back to the HTML page, delete the previous JavaScript code, and add the <script> ...
</script> tags in the <head> section of the page with a reference to the helloworld.js JavaScript
file, like so:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript" src="helloworld.js"></script>
</head>
<body>
</body>
</html>
Save all your documents and run the HTML page in the browser. You should view the same alert
box popping up as in the previous example.
If the code doesn't work, in your HTML document check that the filepath to the JavaScript file is
correct, the filename spelling is accurate, and double-check that you've added a closing </script>
tag. In helloworld.js make sure your JavaScript command is typed exactly the same as in the
sample code above, then try again.
Summary
You've actually learned a lot in this lesson. You know how and where to include JavaScript in
your web page, how to comment your JavaScript code and why this is a good idea, and finally
you've just seen your web page come alive with your first JavaScript script.
Admittedly, an alert box saying "Hello World!" looks a bit dumb, but even alerts can be useful to
quickly and easily test that JavaScript is enabled in your browser and your code is working.
It's time for a well deserved break. In lesson 3 you'll be tackling another core topic in your
JavaScript journey: events. Get ready!
9
Lesson 3: Events
The web is a dynamic environment where a lot of things happen. Most appropriately, they're
called events. Some of these events, like a user clicking a button or moving the mouse over a
link, are of great interest to a JavaScript coder.
For instance, if you're on a web page and click on a link, there are at least 3 important events being
triggered:
However, the most common events you're likely to deal with in your JavaScript are:
10
onLoad/onUnload;
onClick;
onSubmit (triggered by the user submitting a form);
onFocus / onBlur (triggered by a user as, for example, she clicks in a textbox or clicks
away from a textbox respectively);
onMouseOver / onMouseOut (triggered by the user moving the mouse over or away from
an HTML element respectively).
There are other events that might eventually be of interest to you as you write sophisticated
JavaScript scripts, such as scroll events (as users scroll up and down a web
page), onTextChanged events (as users type in a textbox or textarea), even touch events, which
are likely to gain interest in today's mobile and tablet-invaded world.
However, for the purposes of this tutorial, you're mostly going to come across the core events
listed above.
Once your script gets hold of the hook provided by the event, your script is boss. The jargon for
this is event-driven programming: an event happens and JavaScript handles it, for instance
by displaying an alert box with a message for the user.
Conclusion: events bend to JavaScript commands by means of event handlers. These are
statements in your JavaScript script that are appropriately attached to those events.
The alert() command is a command which is part of the JavaScript language. The JavaScript
interpreter in the browser translates it along these lines:
11
"Hey, browser, display an alert box that contains the message typed within the () enclosing
brackets"
(Notice: JavaScript is case sensitive. If you write Alert instead of alert, your script won't work!).
As you saw in the previous lesson, simply by writing a JavaScript statement between <script> ...
</script> tags achieves the execution of that statement as the onLoad event fires up.
However, your JavaScript scripts are capable of doing more interesting stuff when they handle
events in response to user actions, for example an onClick event. How do we do that?
The fun of being in charge, though, is not to let the browser do what it likes, but of letting
JavaScript do its job and decide what's to be done.
The simplest way to attach an event handler to an event is to insert the required JavaScript code
within the HTML element that produces the event. Let's have a go by simply preventing the browser
default action as the user clicks a link on the page. Fire off your text editor and let's get coding!
Prepare a new basic HTML document displaying a simple link like the one shown below:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 3: Events and Event Handlers</title>
</head>
<body>
<h1>Lesson 3: Events and Event Handlers</h1>
</body>
</html>
Run the page in the browser. If you click on the link now, you'll be landing straight to the HTML.net
website. This is the browser default action, as explained above.
Now go back to your HTML document and type the following JavaScript command within
the <a> tag, as follows:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 3: Events and Event Handlers</title>
</head>
<body>
12
<h1>Lesson 3: Events and Event Handlers</h1>
</body>
</html>
Go ahead, run the page in the browser, and ... you're stuck! JavaScript is in control!
You already know about the good old alert() command, so I'll skip over it. The return
false; command tells the JavaScript interpreter to return a value, in this case the value equals
false, which prevents the browser from performing its default action. You'll be using this little
command quite often in your JavaScript programming life.
You handle the other events listed above in the same way: just insert the JavaScript command as
the value of the onfocus, onblur, onmouseover, onmouseout and onsubmit attributes of an HTML
element.
Summary
That'll be all for this lesson. You learned what events are, why events are important in JavaScript
programming, and how to use event handlers to let JavaScript be in control of your web page
behavior.
But this is just a tiny taste of what JavaScript can do once it's in charge. Follow on to find out.
Get ready for the major topic of lesson 4: variables and constants.
The difference between a variable and a constant is this: once you give a value to a constant
the value is meant to be kept unchanged throughout the script. In all circumstances where you
reasonably foresee that the original value is modified through the script, by all means use
a variable as your storage room. In fact, you're going to use variables most of the times.
var amountDue
The variable declaration ends with a ( ; ) semicolon, which makes it a self-contained statement.
Also, because JavaScript is case sensitive, every time you refer to the amountDue variable, make
sure you keep the letter case exactly the same as the original declaration (this particular
notation is called camelCase because it looks like a camel's hunch).
const taxRate;
In the sample code above, you declare a taxRate constant. As you can see, the declaration is very
similar to the variable declaration, the only difference being the keyword used: var in the case of
a variable and const in the case of a constant.
Prepare a basic HTML document with the JavaScript code illustrated below:
14
<!DOCTYPE html>
<html>
<head>
<title>Lesson 4: Variables and Constants</title>
</head>
<body>
<h1>Lesson 4: Variables and Constants</h1>
<script type="text/javascript">
//Create a variable
var amountDue;
so for now it is 0 */
amountDue = 0;
var productPrice = 5;
var quantity = 2;
changed from 0 to 10 -
Notice: you do not use ' ' with var name in alert() */
alert(amountDue);
</script>
</body>
</html>
Did you see the good old alert box displaying the number 10 popping up? If you didn't, make sure
your code is typed exactly the same as in the snippet above (Notice: When tracing bugs (errors)
in your JavaScript code, look out for brackets, semicolons ( ; ), quotes (' '), and letter
casing).
That's great! Try experimenting with the code above. For example, change the value of quantity
and productPrice, or just come up with your own variables.
15
How to name variables (and constants)
Choose descriptive names for your variables (var amountDue; rather than var x;): this way your
code will be more readable and understandable.
While this can be called good programming practice (but also common sense), there are
also syntax rules (yes, just like any natural language) when it comes to naming variables, and
they must be obeyed, at least if you want your JavaScript script to work.
Keep an eye on the following simple rules when you name variables:
16
3) Spaces and special characters other than ( _ ) and $ are
not allowed anywhere:
Summary
Variables and constants are the building blocks of any programming language. In this lesson you
learned the part they play in JavaScript, how you declare and assign values to them, how to name
your variables correctly, and you also had a taste of using variables in JavaScript.
In the next lesson you're going to learn about JavaScript operators and do more and more
practice with variables.
In the previous lesson you already employed an assignment operator ( = ) and an arithmetic
operator, specifically the multiplication operator ( * ), to write a basic JavaScript shopping cart
script.
We can easily see that to do something useful with JavaScript, we need a way to manipulate data
and variables. We do this with operators.
arithmetic operators;
the + sign to concatenate text (concatenation operator);
17
comparison operators;
logical operators.
Also, you'll get plenty of opportunities to practice coding with variables. Let's get started!
Arithmetic operators
As you might have guessed, arithmetic operators are used to perform arithmetic operations
between values or variables. Here's a table for your reference.
Addition: + z=x+y z = 25
Subtraction: - z=x-y z = 15
Increment: ++ z = ++x z = 21
Decrement -- z = --x z = 19
I guess you're quite familiar with most arithmetical operators. The odd ones might be the ( % )
modulus, the ( ++ ) increment, and the ( -- ) decrement operators.
Time to get coding! Get your hands on the text editor and prepare a new HTML document like the
one below:
<script type="text/javascript">
18
//Create and initialize your variables
var result = 0;
var secondNum = 5;
//Addition: result = 25
document.write(result);
</script>
</body>
</html>
Nothing new here except for the JavaScript command document.write(). This command is
translated by the JavaScript interpreter as saying:
"Hey browser, get the value within brackets and print it on the HTML document!"
In our case the value is a variable, therefore no ( ' ' ) quotes are used to enclose it. If you want to
print some text instead, the command must be: document.write('some text.');. It's all very similar
to the alert() command you've been using so far.
Now experiment with the code sample above by trying out all the other arithmetic operators and
printing the result on the page.
Concatenation operator
If you want to add pieces of text together to form one long line of text, use the + sign. In Geeky talk
a piece of text is called string, and it appears enclosed either in (' ') quotes or (" ") double-quotes
(remember the 'Hello World' text you used in the alert() command? That is an instance of string).
<script type="text/javascript">
document.write(message);
</script>
</body>
</html>
If you typed your code correctly, you should see the famous Hello World! text smack on the web
page. Notice: you separate Hello and World! by concatenating quotes (' ') in-between each
piece of text or variable.
Comparison operators
Often you need to compare different values and make your JavaScript program take different
directions accordingly.
For example, you're coding a JavaScript script for a shopping cart application. At one point, your
script will have a statement saying something along these lines: if the total amount to be paid
is greater than or equal to $50 apply a 5% discount, if it's less than or equal to $50 do not apply
5% discount. Don't be impatient, you will learn how to code this kind of conditions in the next
lesson.
It's here that comparison operators, such as equal to, less than, etc. enter the scene. Here
below are listed all comparison operators for your reference.
If x = 10 we have:
== equal to x == 5 is false
x === 10 is true
=== exactly equal to value and type
x === "10" is false
20
> greater than x > 20 is false
Logical operators
You use logical operators when you need to determine the logic between certain values.
Going back to the shopping cart script example, you might want your script to apply a 5%
discount if the following 2 conditions are both true: a given product costs more than $20 and is
purchased before the 31st of December.
(x == 5 || y == 5) is true
|| or
at least 1 condition must be satisfied
1. When you talk about === , what do you mean by equality of value and type?
2. What's the difference between ( = ), ( == ), and ( === ) ?
21
Answer to question 1.
Values are the specific data, either directly in your JavaScript statements or contained in
JavaScript variables. For example:
var price = 5;
The type, or more precisely the data type, is the way JavaScript classifies data. You've come
across 2 data types, that is, number and string (text). A third data type is Boolean, that is, true
and false statements.
Therefore, when you compare 2 values using ( === ), the 2 values are compared on the basis
of both their value and their data type:
var firstNum = 4;
var secondNum = 4;
Answer to question 2.
The ( = ) operator is used to assign or give a value to a variable. It is not a sign for equality.
The ( == ) and ( === ) operators instead, do stand for equality. They do not assign values to
variables. ( == ) compares only values, ( === ) compares both values and data type.
Summary
You've made it all the way through this lesson, congratulations! Now your scripts are not limited to
just popping up messages. They start to be smart: they can make calculations, comparisons,
and set truth conditions to evaluate their data.
22
In the next lesson you keep adding intelligence to your JavaScript with if ...
else and switch statements.
Now that our JavaScript code can calculate, compare, and determine true and false
conditions, things start looking a lot more interesting.
The days of dumb message boxes popping up are long gone, the new era of smart message boxes
has begun.
In this lesson you're going to inject the power of choice into your scripts with conditional
statements. These statements enable your script to evaluate given conditions on the basis of
which to execute one or more actions. More specifically, you're going to learn how to use:
if statements;
if ... else statements;
if ... else if ... else statements;
switch statements.
In the process, you're also going to learn how to use shortcut assignment operators.
if Statement
The if keyword is used in JavaScript to perform a basic test for the truth or falsity of a given
condition and execute a piece of code accordingly. Here's its structure:
if (condition)
if (condition)
//otherwise
else
if (condition)
// do this stuff
else if (condition)
24
//if none of the above condition is true
else
// do this instead
switch statements
In alternative to an if ... else if ... else statement you can switch to a ... well a switch statement.
Here's its basic structure:
//condition to evaluate
switch(condition)
case 1:
break;
case 2:
break;
default:
It's time to put your new knowledge to work right away. In this try out you're going to check a
product price and decide whether to apply a discount. Prepare a new HTML document and get
coding!
25
Try out: check product price with if
<!DOCTYPE html>
<html>
<head>
<title>Lesson 6: Even Smarter Scripts with if…else and switch</title>
</head>
<body>
<h1>Lesson 6: if statements</h1>
<script type="text/javascript">
var applePrice = 2;
var quantity = 5;
var discountedTotal = 0;
26
var infoText = "You'll get your delicious apples at $" +
discountedTotal;
//you add more text to the same infoText var with a shortcut assignment
operator
document.write(infoText);
</script>
</body>
</html>
Save your work, run the page in the browser, and enjoy your discount!
Shortcut operators
When you add several values to a variable, a shortcut operator is very handy.
As you can see, the given value of x is taken as the starting point, 2 is added to it, and the resulting
value is reassigned to x. Using a shortcut operator spares you from having to retype x.
When applied to the code snippet above, the expression infoText += " instead of at $" is the
same as infoText = infoText + " instead of at $". If we simply use an ( = ) assignment operator
in this case, the text already stored in infoText will be wiped out by the new value. But this is not
what we want in this script.
-=
*=
/=
%=
27
Try out: check product price with if ... else
Just after the closing curly brace } from the previous example, add the following snippet.
else
document.write(infoText);
Change the value in the quantity variable to be less than 5, save your work and run the page in
the browser. Now, JavaScript should give you the not so good news that you're not entitled to a
discount.
Try out: check product price with if ... if else ... else
Still using the previous example, between the first if block and the last else block, insert the
following else if block.
else if (total == 8)
var infoText = "Be a sport, buy a bit more and pay a bit less";
document.write(infoText);
Change the quantity variable to be 4, save your work and run the page in the browser. Now you
should fall for the persuasive power of such a great discount.
Your code can detect if the purchase qualifies for a discount, if it almost qualifies for a
discount, and finally if the discount is inapplicable by a long shot. In each case, your code can
take appropriate action.
Have fun practicing with if ... else if ... else statements, and shortcut operators.
28
Try out: days of the week with switch
Now get a fresh HTML document ready and type the following code block:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 6: Even Smarter Scripts with if…else and switch</title>
</head>
<body>
<h1>Lesson 6: switch</h1>
<script type="text/javascript">
switch(today)
case "Saturday":
case "Sunday":
break;
case "Friday":
break;
default:
29
</script>
</body>
</html>
Save your work and run the page in the browser: a great Friday message should be there to greet
you. Keep changing weekday and make sure the alert box displays the appropriate message each
time.
Summary
Now you know how to write scripts that implement different actions on the basis of different
conditions. Well done!
Keep experimenting with all the tools you've learned so far. If you have doubts, drop a line in the
forum dedicated to this tutorial. When you're ready, move on to the next big topic: loops.
One really boring thing most of us would happily avoid doing is repetitive stuff. You might find it
hard to believe this, but JavaScript loves repetition. So much so that it has a special construct for
it: the loop.
Loops
At times you will have to repeat some piece of code a number of times:
30
for instance: a web page has 10 radio buttons and your script needs to find out which radio button
was checked by the user.
To do so, your script has to go over each single radio button and verify whether its checked
attribute is set to true or false. Does this mean having to write this kind of verification code 10
times?
Thankfully, it does not. You dump the code in a loop once, and it's going to execute any
number of times you set it to.
4. the increment
This is the part that moves the loop forward: the counter you initialize has to move up (or
down in case you opt for looping backwards). As long as the loop does not reach the end
value or the test condition is not satisfied, the counter is incremented (or decremented).
This is usually done using mathematical operators.
31
{
//code to be executed
With a while loop your code executes while a given condition is true; as soon as this condition
evaluates to false, the while loop stops.
//code to be executed
In the case of the while loop, if the test condition is false from the start, the code in the loop
will never be executed.
In the case of the do ... while loop, the test condition is evaluated after the loop has performed the
first cycle. Therefore, even if the test condition is false, the code in the loop will execute once.
do
//code to be executed
32
}
<!DOCTYPE html>
<html>
<head>
<title>Lesson 7: Leave Boring Repetitive Stuff to JavaScript with
Loops</title>
</head>
<body>
<h1>Lesson 7: for Loop</h1>
<div id="wrapper"></div>
<script type="text/javascript">
//just for testing purposes, lets alert the resulting random number
33
alert(numImages);
//code to be executed:
//create a var and store a string made of a new HTML img element
//Take note:make sure the img src corresponds to a real image file
//and use innerHTML to insert the string stored in the newImage var
container.innerHTML += newImage;
</script>
</body>
</html>
Show example
Prepare a graphic file and store it in the same directory as your document, save your work, run the
page in the browser and keep reloading it: the alert box will display a random number each time,
then an img element is dynamically added to the web page as many times as indicated by the
random number.
34
the document.getElementById(element Id) command. The JavaScript interpreter reads
it as follows:
"Hey browser, find the HTML element with the id name like the one in brackets."
Because JavaScript usually does something with the element, this gets conveniently stored
inside a variable. What you did in the sample code above was to grab hold of the div with
the id attribute named wrapper and store it in a variable named container.
Math.random() generates a random number between 0 and 1. Try it out on your own by
typing var randomNum = Math.random(); alert(randomNum); inside a <script> tag.
"Hey browser, take the number in brackets and round it down to the nearest integer
number."
There's more than one way to add new mark-up in your HTML document, but
using innerHTML makes it very easy and straightforward. The JavaScript interpreter reads
the command as follows:
"Hey browser, take the string to the right of the assignment operator and insert it into
the HTML mark-up."
What you did in the sample code above was to take the variable storing the wrapper div
element and applying innerHTML to it to insert an img tag inside the div.
35
Try out: add images to the page with a while loop
Use the same HTML document from the previous example, but delete all the JavaScript between
the <script> ... </script> tags. Now, type in the following JavaScript code:
<script type="text/javascript">
var numImages = 0;
//Take note:make sure the img src corresponds to a real image file
//and use innerHTML to insert the string stored in the newImage var
container.innerHTML += newImage;
numImages ++;
</script>
Show example
36
Make sure the image file is in place, save your work and run the page in the browser. You should
see something similar to the example page indicated in the link above.
Save your work, run the page and see what happens. If all works fine, nothing at all should happen:
the loop doesn't even get started.
<script type="text/javascript">
var numImages = 0;
do
container.innerHTML += newImage;
numImages ++;
</script>
Show example
37
Save your work and run the page in the browser. You should see something similar to the example
page indicated in the link above.
Save your work, run the page and see what happens. Unlike what happened with the while loop,
now you should see one image displayed on the web page: the loop has completed the first
cycle and only afterwards the test condition is evaluated. In this instance the condition is false
and the loop stops after the first iteration completes.
Summary
That's all for this lesson. Your JavaScript toolbox is getting richer and richer: you can write
repetitive code with loops, manipulate HTML content dynamically, and write scripts that generate
random numbers.
Pat yourself on the back and take a well deserved break before moving on to the next big
topic: functions.
38
Functions: what they are and what they are for
In previous lessons you used JavaScript functions to perform some actions quickly and easily like
generating random numbers, writing something on a web page, etc. In fact, JavaScript has a great
many built-in functions like write(), alert(), getElementById(), random(), floor(), and several
others. Wherever you spot a pair of round brackets there's likely a function in action.
JavaScript also gives you the option to craft your own functions.
A function is a way of packaging your JavaScript commands so you can easily reuse them
every time you need the same piece of functionality implemented in your website.
Declare a function
The basic structure of a JavaScript function looks like this:
function functionName()
Call a function
Once you put a block of code into a function, you can use it anywhere you need that functionality
in your website. What you need to do is just call the function.
You do this by typing the function name followed by brackets and the function will do its job - just
like you did with alert(). Here's how it's done:
39
//Type the function name (without the keyword function)
functionName();
That's all you need: whatever code you stuffed into your function gets executed at this point.
Let's see how this works in practice. Fire off your text editor: it's time to get coding!
<!DOCTYPE html>
<html>
<head>
<title>Lesson 8: Declare a function</title>
</head>
<body>
<h1>Lesson 8: Declare a function</h1>
<div>
<span id="calendar"></span>
</div>
<script type="text/javascript">
function showDate()
40
var today = new Date();
myCalendar.innerHTML = today.toDateString();
</script>
</body>
</html>
If you go back to lesson 3 for a moment, you remember that one way in which this can easily be
done is to put some JavaScript code as the value of the HTML element onclick attribute.
Just add an onclick attribute to the button element and plug your showDate() function right in there,
like so:
Show example
Save your work and run the page in the browser. Click the button and you should see today's date
displayed on the page and the button value attribute giving you an appropriate message.
41
Questions, questions, questions
I know, there's some new stuff in the code samples above. You might be wondering: 1) what's
this new Date() business? And 2) What does toDateString() do to the date? Let's tackle each
question in turn.
The important thing you need to know now is that once you've created an instance of the
Date object, you've got all sorts of useful functions (called the object's methods) at your
fingertips to manipulate date and time.
"Hey browser, take the date you've been attached to and make it a bit more human-
friendly!"
This is what I mean. Type the following inside enclosing <script> tags of an HTML page: var
myDate = new Date(); document.write(myDate);
Save the page and run it in the browser: your date should be displayed in a format like the
one below (obviously I expect the date to be different):
Ugly! Luckily, the Date object has its own beauty remedy. Rewrite the previous code
snippet as follows: var myDate = new Date(); document.write(myDate.toDateString());
And here's what the date above looks like after its beauty treatment with toDateString():
Much better, less scary, and far more readable for us humans.
You can also feed data to a function for manipulation. The way you do this is through arguments
(or parameters). An argument is placed inside the function's brackets when the function is
declared. You can place one or more arguments separated by commas( , ) inside a function.
42
Here's what the basic structure looks like:
The function argument is like a placeholder for the value that gets fed when the function is
called. This will appear clearer in the example below.
Finally, one useful thing functions can do with data, once it's been manipulated, is to return it.
For example, take the floor(number) function that you already know from the previous lesson.
This function takes in a number argument and returns an integer number.
If your script does something with the returned value then it needs to assign the function to a
variable when calling the function.
Let's put this knowledge into practice right away. Create a function and then call it to use its return
value in your document.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 8: Function Arguments and Return Values</title>
</head>
<body>
<h1>Lesson 8: Function Arguments and Return Values</h1>
<script type="text/javascript">
}
43
</script>
</body>
</html>
document.write(total);
Save your work and run the page in the browser. If all goes well, the sum of the numbers you
inserted as arguments of your addNumbers() function should be displayed on the web page.
Function arguments are not limited to a specific data type. You can also use strings and booleans,
and even other functions. However, we don't want to be too involved at this stage.
Simply put, a variable having local scope means that it's visible, or accessible, only within
the function in which it lives. No other portion of your code can see a local variable.
On the other hand, a variable having global scope means that it's accessible, that is, it can be
used, anywhere in your script.. Let's see this in practice. Get your text editor ready and type the
following snippet between opening and closing <script> tags in an HTML page:
44
//having the same name as the first global variable
function getMessage()
alert(message);
alert(otherGlobalVariable);
getMessage();
alert(message);
Save your work and preview the page in your browser. As you can see, the alert() function
outside the variable doesn't have access to the message variable inside the function. On
the other hand, the function can have access both to its local variable and to any variable in
the global space.
This might seem a bit confusing at first, but it's all a matter of practicing your coding skills as often
as you can. The important thing to remember is that, if at times the variables seem not to have the
values you expect, it might be a scope-related bug.
Summary
That's all for this lesson. You can now package your JavaScript code into reusable and
manageable functions, input and output data via a function, use the Date object to retrieve and
display the current date, change the value of an HTML button element on-the-fly, and distinguish
between local and global variables. You've accomplished a great deal, congratulations!
Take a break and get ready for the next big topic, a core feature of contemporary programming
languages, objects.
45
Lesson 9: A Gentle Introduction to Objects
Object Oriented Programming (OOP) is a programming model used by most contemporary
programming languages. JavaScript offers significant object oriented capabilities, has its own built-
in objects, and offers you the option of creating your own custom objects.
This is a wide and complex subject and we're only going to scratch the surface in this tutorial
series. However, because as soon as you start coding in JavaScript you can't avoid dealing with
objects, it's important that you get familiar with some core concepts of OOP.
This short lesson is introductory to the more detailed and practical lessons on specific JavaScript
objects that follow.
What most computer programs do is manipulate, manage, and reuse data of various kinds.
Therefore, using the real world object metaphor, contemporary programming languages like
JavaScript deal with their virtual environment by populating it with packaged data modelled after
the concept of an object.
Everything in JavaScript is an object and you've already used plenty of objects without realizing it.
In fact, you're already familiar with:
the Document object that you used to print your JavaScript messages on the web page;
the Math object, that you used to generate random numbers and round off decimals;
HTML elements like the button object that you used to manipulate its value attribute;
the Date object that you used to retrieve the current date.
The answer is: not much differently from the way we humans manipulate real world objects. We
do this by interacting with the qualities and capabilities that belong to individual objects.
Let's take a ball as our example. We interact with the ball by means of some of its qualities (its
roundness, its hardness, its size, etc.). Also, we interact with the ball on the bais of what we expect
46
the ball's behavior to be like (we expect that we can launch the ball without breaking it, that we can
throw it against a wall and it bounces back, etc.).
Similarly, a JavaScript script interacts with its object-modelled data by means of the objects'
qualities and behavior. These are called properties and methods.
Properties are values associated with an object. For example, an HTML element object has a
value property (like the button object you're familiar with), and an innerHTML property, that you
used to add new mark-up to the web page.
Methods represent what an object can do, its behavior, and are very much like functions.
You use the object.property and object.method syntax to interact with JavaScript objects.
Math.random();
document.write();
myStringText.length;
Summary
This lesson has been a short introduction to the concept of JavaScript objects, their properties
and methods.
In the next lesson you will learn about the most widely used properties and methods of the String
object.
47
Lesson 10: JavaScript Objects - Strings
In the previous lesson you were introduced to the concept of Object Oriented Programming
(OOP). You're now familiar with the use of objects and their properties and methods in JavaScript
programming.
Starting from this lesson and for the next 3 lessons, we will be getting up close and personal with
some of the most common properties and methods of widely used JavaScript objects: String,
Date, Math, and Array. However, because JavaScript as a programming language is mostly made
of objects, you will keep learning to use more objects and related properties and methods
throughout the rest of this tutorial.
In this lesson you will learn how to use the following properties and methods of the string object:
length property;
toLowerCase()/toUpperCase();
match();
replace();
indexOf().
In the process, you will also practice putting your JavaScript code into an external file.
The beauty of Object Oriented Programming is that we can use all that JavaScript goodness to
achieve our script's goals without needing to have any clue whatsoever of the inner workings of
those properties and methods. All we need to know is what a property or method can do for us,
not how it does it.
For example, if we need to know the length of a piece of text, just using pieceOfText.length will
achieve this. This is accomplished without us knowing anything of the programming virtuosity
responsible for the power of the length property of the string object.
48
//create and initialize a string variable
document.write(myString.length);
Try out for yourself: insert the code above between enclosing <script> tags and have fun
experimenting with it.
document.write(myString.toUpperCase());
Have a try: insert the code above between enclosing <script> tags and switch uppercase into
lowercase.
49
//apply the match() method to the string.
document.write(myString.match("JavaScript"));
Experiment on your own: insert the code above between enclosing <script> tags and try matching
different string values.
//replace(valueToReplace, newValue)
document.write(myString.replace("JavaScript", "World"));
Have a go: insert the code above between enclosing <script> tags and try replacing different string
values.
50
//indexOf() takes in the value to look for in the string as argument
//indexOf(valueToFind)
document.write(myString.indexOf("Java"));
Have a go on your own: insert the code above between enclosing <script> tags and print the index
position of different letters inside the string.
Your JavaScript code will be placed in its own external file and referenced from the HTML
document. Separation of concerns, that is, separation between structure (HTML mark-up),
appearance (CSS), and behavior (JavaScript), reflects contemporary best practices in web
design.
Let's start with the HTML document. This is a simple web page with a textbox, a button, and a div
where the JavaScript result will be displayed:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 10: JavaScript Objects - Strings</title>
<script type="text/javascript" src="lesson10.js"></script>
</head>
<body>
<h1>Lesson 10: JavaScript Objects - Strings</h1>
<p id="message"></p>
</body>
</html>
51
Pay attention to the enclosing <head> tags. These contain a reference to an external JavaScript
file named lesson10.js located in the same directory as the HTML file (you're free to place the
JavaScript file in its own directory, if you prefer. However, make sure this is reflected in the src
value of your <script> tag in the HTML document).
Also, take note of the fact that the elements that are going to play a role in our script all have
an id attribute. This gives JavaScript a hook on those elements and the data they will
eventually contain.
Now open the JavaScript file lesson10.js and type the following code:
function init()
//and runs after the user clicks the button on the page.
myButton.onclick = getAnswer;
//this event fires when the HTML page is loaded in the browser.
onload = init;
function getAnswer()
52
{
//Given that users might type the answer either in upper or lower case,
//ensures that only the content and not also the letter case plays a
role in the comparison.
//Get a reference to the HTML paragraph that will display your result
//and respond to: if the user clicks the button but did not
if(nameLower.length <= 0)
//If the user gets right the first half but not the latter half of the
name:
53
//Take note of the use of the logical operator &&
//If the secret name and the name entered by the user match:
else if(nameLower.match(secretNameLower))
else
alert("Wrong!");
Show example
Save all your files and run the HTML page in the browser. You should see something similar to the
example page indicated in the link above.
If you click the button without entering any value in the textbox, an alert will pop up inviting you
to enter an answer.
If you get right the first half ("Harry") - indexOf() returns 0 ("Harry" is at position 0, which is
the start of the index) - but not the latter half ("Potter") - indexOf() returns -1 (it finds no
54
corresponding value inside the string), you get an alert letting you know that your answer is
almost right.
Finally, if your answer is totally wrong, your application will say so and give you the correct
answer.
The above code sample employs all the JavaScript tools you learned in this lesson and most of
those you encountered in previous lessons. Experiment with it as much as you can. If you have
doubts, leave a message in our JavaScript forum.
The really new stuff in the guessing game application is the way JavaScript functions work from
an external file. This is the technique I'm going to use for our Try out exercises in most of the
remaining part of this tutorial - at least until jQuery makes its appearance. This means that you'll
be getting plenty of practice with it.
Summary
In this lesson you started to have a taste of the power of objects. You also started to use an external
JavaScript file for your Try out exercise, thereby conforming to best practice in contemporary web
design techniques. Now have a break and get yourself ready for the next topic: the Date object.
Here we continue to explore the power of JavaScript objects: we will be looking into the magical
virtues of the Date object.
The Date object exposes plenty of methods to manipulate dates and times, some of which we're
going to examine here.
55
I recommend you try out all the demos below by inserting the code snippets between enclosing
<script> tags in an HTML page (for such short demos we can get away with not using an external
JavaScript file ). Also, feel free to experiment with each demo as much as possible before
moving on to the next example.
//First way:
//Second way:
//new Date(milliseconds)
//Third way:
//new Date(dateString)
Fourth way:
56
//the others are optional arguments and
After a Date object is created, you can use its methods to get and set dates and times.
document.write(myDate.getDate());
document.write(myTime.getTime());
57
Get Date object components
Once you have a Date object, one interesting thing you can do with it is to get its various
components. JavaScript offers some interesting methods to do just that.
document.write(myDate.getFullYear());
document.write(myDate.getMonth());
document.write(myDate.getDay());
58
Use getHours() and getMinutes() to extract time
components
//Create a Date object containing the current date and time
document.write(timeString);
//14 : 44
Set dates
You can also set dates and times as easily as calling the appropriate methods. Here are a few
examples.
59
var mySetDate = myDate.setFullYear(2011, 9, 31);
switch (mySetDay)
case 0:
mySetDay = "Sunday";
break;
case 1:
mySetDay = "Monday";
break;
case 2:
mySetDay = "Tuesday";
break;
case 3:
mySetDay = "Wednesday";
break;
case 4:
mySetDay = "Thursday";
break;
case 5:
mySetDay = "Friday";
break;
case 6:
mySetDay = "Saturday";
break;
Compare 2 dates
In this demo you will compare 2 Date objects.
//if the set date is smaller than today's date, it's in the past
else
Summary
In this lesson you looked into some of the methods of the Date object and had the chance to
experiment with them.
In the next lesson you will be exploring JavaScript mathematical wizardry: get ready for the Math
object.
61
Lesson 12: JavaScript Objects - Math Object
By Maria Antonietta Perna
We continue on our journey through JavaScript built-in objects by offering a quick overview of
the Math object.
You already had occasion to taste the power of the Math object back in lesson 7, where you used
its random() method to generate a random number between 0 and 1, and its floor() method to
round down the resulting random number.
The Math object allows you to write scripts that perform complex mathematical tasks in the blink
of an eye.
Math.PI
This property stores the value of PI, a mathematical constant that amounts to approximately
3.14159.
Let's quickly refresh our school math. Here are some definitions:
Circle
A circle is a shape with all points the same distance from the center:
62
the round border surrounding the shape (the color blue in the graphic above), is the
circle circumference;
the line cutting the circle horizontally in half (the color red in the graphic above) is the
circle diameter;
each half of the diameter represents a radius.
If you need this value in your JavaScript program, use Math.PI. Just try this one out between
enclosing <script> tags of an HTML page:
var pi = Math.PI;
document.write(pi);
Keeping in mind that the radius is half the diameter, and that the formula to calculate the
circumference is PI * diameter, our JavaScript statement to calculate the circumference given the
radius will be: 2 * (Math.PI * radius).
<!DOCTYPE html>
<html>
<head>
<title>Lesson 12: JavaScript Objects - Math Object</title>
<script type="text/javascript"
src="lesson12_tryout1.js"></script>
</head>
<body>
<h1>Lesson 12: Circumference calculator</h1>
<p id="result"></p>
</body>
</html>
63
The HTML page above references an external JavaScript file, lesson12_tryout1.js, and contains
an inputbox, a button, and a paragraph where the result of the calculation will be displayed. Make
sure these 3 crucial elements have an id value so your JavaScript script will have an easy to reach
hook on those elements.
Now create a JavaScript document and name it lesson12_tryout1.js. This file will contain 3
functions:
1. init() initializes the script by binding the processAnswer() function to its appropriate event,
that is, the btnSubmit onclick event;
2. processAnswer() checks the answer submitted by the user, calls the function that
performs the calculation, and displays the result;
3. getCircumference(rad) gets passed the radius value as argument, performs the actual
calculation, and returns the circumference.
function init()
myButton.onclick = processAnswer;
/*********************************************/
onload = init;
/*********************************************/
function processAnswer()
64
//calculations can only be performed with numbers,
//a value as input and returns true if the value is not a number,
if (isNaN(radius))
else
result.innerHTML = resultString;
65
/*********************************************/
function getCircumference(rad)
return circumference;
Show example
Save all your files and run the HTML page in the browser. You should see something like the page
indicated by following the example link above.
If you click the button without entering any value in the inputbox, or if you enter a letter rather than
a number, the program asks you to enter a number value.
As you click the button, the calculation is performed and the result is displayed on the page.
Math.sqrt()
Math.sqrt(number) takes a number as argument and returns the square root of that number.
If a negative number is entered as argument, for instance Math.sqrt(-5), the function returns NaN,
that is, a value that JavaScript does not treat as a number.
Brushing up on our school math, the square root of 25, for example, is that number that multiplied
by itself yields 25 as a result, that is, 5.
The formula is: square of n = n * n. JavaScript performs this calculation automatically. Here's a
quick demo: type the following code between enclosing <script> tags of an HTML page:
66
Try out: square root calculator
You will build a simple square root calculator. Here are the requirements for this little application:
Create a fresh HTML page with an inputbox, 1 button, and a paragraph where the result will be
displayed. These HTML elements contain id attributes that will provide a handy hook for our
JavaScript code.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 12: JavaScript Objects - Math Object</title>
<script type="text/javascript"
src="lesson12_tryout2.js"></script>
</head>
<body>
<h1>Lesson 12: Square root calculator</h1>
<p id="result"></p>
</body>
</html>
Now create the lesson12_tryout2.js file. This file will contain 3 functions:
1. init() initializes the script by binding the displaySquare() function to its appropriate event,
that is, the btnSubmit onclick event;
2. displaySquare() checks the answer submitted by the user, calls the function that performs
the calculation, and displays the result;
3. calculateSquare(input) gets passed the number value entered by the user as argument,
performs the actual calculation, and returns the the square root.
function init()
67
var myButton = document.getElementById("btnSubmit");
myButton.onclick = displaySquare;
/**************************************************/
onload = init;
/**************************************************/
function displaySquare()
//in its own var and then use it to extract its value property
var inputVal =
parseInt(document.getElementById("txtNumber").value);
68
//we create the var that stores the result message
if (isNaN(inputVal))
else
if (squareVal)
else
69
result.innerHTML = resultMessage;
/**************************************************/
function calculateSquare(input)
return squareVal;
Show example
Save all files and preview your work in a browser. You should see something similar to the example
indicated by following the link above.
Enter a number into the inputbox and click the button. If you enter anything but a number into the
inputbox (or if you leave the inputbox empty), you'll be alerted by a popup box asking you to enter
a number. If all goes well, the square root of the number you enter in the inputbox will be displayed
on the page.
If the application is not working, check your typing, especially letter casing, brackets, and semi-
colons ( ; ). If you have any doubts, just drop us a line in the forum dedicated to this tutorial.
Summary
You've made it to the bottom of the page, congratulations! After this lesson you've added new tools
to your JavaScript toolbox: the PI property and sqrt() method of the Math object. You also know
how to convert a string (text) to a number data type with parseInt() and parseFloat(), so that you
can use the value to perform calculations. Finally, you learned how to check user input
with isNaN().
It's time for your break before the next big topic: the Array object.
In the process, you will learn how to use the for ... in loop to access data inside an array.
From the perspective of data storage, an array works a bit like a variable. The difference is that
you are not limited to one piece of data, as it's the case with common variables. You can stuff
several items at once inside an array and retrieve whichever you need at the right time in your
program.
Imagine if you had to have a storage place for each pair of socks. This would be a nightmare!
Having a drawer to store all your socks in one place makes much more sense. In this respect,
arrays are a bit like drawers, but much more powerful.
From the point of view of data manipulation, the Array object offers a wealth of properties and
methods, some of which you will examine in this lesson.
colors[0] = "green";
colors[1] = "red";
71
var colors = new Array("green", "red");
All 3 approaches illustrated above, create an array object called colors containing 2 string values,
"green" and "red" - but arrays can store all other data types: numbers, booleans, even other arrays!
The items in our array occupy position 0 and 1 respectively.
As you might have guessed, you count the index position of an item inside an array starting
at 0.
But, is this index position important? Well, yes it is, at least if you want to use the items inside the
array, which is most likely the case.
document.write(red);
Enter the code snippet above between enclosing <script> tags in an HTML page, save your work,
and run the page in the browser. You should see the word red displayed on the page.
What you did was to access the second value in the colors array by using its index position within
the array starting to count at 0.
72
Access all items in the array with a loop
You might have probably guessed this, but loops and arrays go together like cookies and milk.
Here's how you would access all values inside an array by looping over each of them:
//that contains the size of the array: you can use it in the for
loop
Save your file and preview the page in a browser. You should see the color names displayed on
the page.
There's also a special type of for loop that you can use with the Array object, the for ... in loop.
Here's how it works:
Run the HTML document containing the code snippet above inside <script> tags in a browser. The
web page should look the same as it did in the previous example.
73
Once you access a value inside an array you can simply retrieve it, as you did in the previous
example, or you can modify it, as follows:
colors[2] = "pink";
//with "pink"
document.write(colors);
You sort array elements with a fantastic method most appropriately called sort(). Here it is in
action:
document.write(ascendingColors);
If you want to sort numerical values inside an array, either in ascending or descending order,
you need to build a simple custom function and pass this function as argument to the sort()
method. It sounds a bit harder than it actually is. Here's how it's done:
74
//build your custom function: this is a simple formula
function sortAscending(a, b)
return a - b;
document.write(sortedAscending);
colors.push("pink");
document.write(colors);
75
//This should print:
//green,red,yellow,orange,blue,pink
Just replace push() with unshift() in the previous example, save your work and run the page in a
browser. The page should display the color name "pink" at the very start, like so:
pink,green,red,yellow,orange,blue.
colors.pop();
document.write(colors);
colors.shift();
Have fun experimenting with the examples above and come back to our try out challenge as soon
as you're ready.
the user can enter a Username in the inputbox, and click a button to register;
if the Username already exists, the program informs the user;
if the Username is not already stored in the program, the new Username is added, the user
is informed, and all stored Usernames are displayed on the page in alphabetical order.
76
A real registration program would ask for more information, the data would be permanently stored
in a database, and existing Usernames would never be printed out for everybody to see.
However, this is a mock application: our Usernames are stored in a global array. This ensures
that the values inside will be accessible from any function in the script, and the newly added
Usernames will be preserved for as long as the program runs. Displaying the Usernames on the
page will show the workings of the global variable (see Lesson 4 for a refresher on global
variables) as well as of the array methods push() and sort().
Enough talking, let's get coding! Prepare an HTML page with an inputbox, a button, and a
paragraph to display messages to the user. Make sure each element has an id value so that your
code can have an easy handle on them.
<p id="result"></p>
</body>
</html>
/*******************************/
//init() function
function init()
77
{
myButton.onclick = registerName;
onload = init;
/********************************************/
function registerName()
var newName =
document.getElementById("txtName").value.toLowerCase();
//If the user clicks the button but the inputbox is empty
if (newName == "")
78
return false;
if (userNames[i] == newName)
result.innerHTML = message;
//set the success flag to false so the rest of the program knows
success = false;
return false;
else
result.innerHTML = message;
success = true;
}
79
}
if (success)
userNames.push(newName);
Show example
Save all your files and run the HTML document in a browser. You should see something similar to
the example page indicated by following the link above.
Try clicking the button without entering anything in the inputbox, then enter a Username already
present in the array - for example, supercoder - and try to register; finally, enter a new name and
see it getting added to the array. As you enter new names, these get added to the array and
displayed alphabetically.
Summary
You've worked really hard in this lesson, well done! You're now familiar with the Array, a powerful
JavaScript object, and some of its fantastic methods. You can also use a for in loop to access
array values, and you've built a challenging little demo application.
Take your well-deserved break, the next topic awaits you: get ready for an exploration of the very
environment that makes JavaScript possible, the browser.
80
Lesson 14: JavaScript Living Space - the
Browser Environment
As we have seen, the JavaScript language is made up of objects, their properties and methods.
Your JavaScript code is interpreted and executed by a web browser. Therefore, JavaScript lives
and comes alive in the browser environment.
This environment, in its turn, is also present in the JavaScript language, and obviously it is so in
object form. Better yet, in the form of several objects, their properties and methods.
In this lesson you will be presented with a quick overview of the main objects making up the
browser environment.
The window object is global to the extent that it represents the very host environment of all other
JavaScript objects. It's so fundamental, that you've already used it without needing to invoke it
explicitly.
In fact, you already used alert() and onload. You didn't need explicitly to
write window.alert() because the global window object was already presupposed.
Also, you could think about the window object as being at the top of a tree-like hierarchy of other
objects, its descendants, or children. In fact, it's quite common for programming languages to
use family-related metaphors to refer to objects representing their environment.
You will have occasion to work further with the window object through the rest of this tutorial. For
now, let's move on to the Document Object Model (DOM).
81
The DOM is an ever evolving standard defined by the World Wide Web Consortium
(W3C) implemented with varying degrees of consistency among different kinds of browsers. It
contains a wealth of properties and methods that enable you to access and manipulate anything
you can think of in an HTML document. So far you've used document.write() to write on the
HTML page, and document.getElementById() to get a hook on an HTML element. But there's
a lot more.
For example, here's all the info the document object can be made to yield when appropriately
nudged. Insert the following code inside enclosing <script> tags of an HTML page and preview its
content in a browser:
document.write(myInfoString);
That's so cool. Let's have a look at how the HTML page is represented in the DOM.
<html>
<head>
<title>Lesson 14: DOM</title>
</head>
<body>
82
</body>
</html>
The DOM representation of the elements in the HTML page above is as follows:
The DOM elements are also known as nodes. Family-related metaphors are also used to
represent the relationships and the position of each node with respect to the others. In connection
to the DOM tree graphic above, we find:
83
3. <title> and <p> nodes
The next level down is occupied by the <title> as child of the <head>, and 3 <p>
elements as children of the <body>. In our sample HTML page above, <title> and <p>
tags are siblings when considered with respect to each other;
4. Text nodes
The text inside the <p> tags, and the text inside the anchor tag are called text nodes.
In this case they're children of the <p> element and the <a> element respectively;
5. Anchor tag
The next level down is occupied by an anchor tag, which is child to one of the <p> tags.
alert(inputBox);
For example, in an HTML page containing a list and 3 list items, you can access each list item and
modify their color and background-color style properties by inserting the following code in enclosing
<script> tags:
84
//loop over each list item and access the style property
listElems[i].style.backgroundColor = "red";
listElems[i].style.color = "white";
Show example
Run your HTML page in the browser. You should see something like the page indicated by
following the example link above.
However, innerHTML, although widely used, has not been recognized as a standard by the W3C.
The DOM standard way to add new elements to an HTML page via JavaScript is done as follows.
Enter the code below in enclosing <script> tags inside an HTML page:
document.body.appendChild(newParagraph);
//Now create the text that goes inside the new <p> element
//with createTextNode():
newParagraph.appendChild(newTextPara);
You can also add attributes to the newly created DOM nodes with setAttribute(attrType,
attrName), and later retrieve them with getAttribute(attrType). Using the code snippet above,
you can add an id called newParagraph to the newly created paragraph like so:
85
var newParagraph = document.createElement("p");
newParagraph.setAttribute("id", "newParagraph");
document.body.appendChild(newParagraph);
newParagraph.appendChild(newTextPara);
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above.
As you can see, there are at least 2 steps you need to take to insert fresh stuff inside an HTML
page with JavaScript:
1. create the new content: to do this you use either createElement(element) in case of an
HTML tag, or createTextNode(text) in case of new text content;
2. append the newly created DOM node to the appropriate location in the HTML document.
I know, it's a bit more involved than the straightforward innerHTML, but it's standard-compliant.
Prepare a simple HTML document with a <p> element and an input button like so:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 14: Delete DOM Element</title>
</head>
<body>
<h1>Lesson 14: Delete DOM element</h1>
86
<input type="button" value="Delete paragraph"
onclick="deleteParagraph()" />
</body>
</html>
Note that the onclick attribute of the button element contains a call to
the deleteParagraph() function. Let's write this function inside enclosing <script> tags in the
<body> of our HTML page:
function deleteParagraph()
document.body.removeChild(remove);
Show example
Save your work, run it in a browser, and click the button. You should see something like the page
indicated by following the example link above: after you click the button the paragraph should be
removed from the page.
Summary
In this lesson you got introduced to the concepts of Browser Object Model (BOM) and Document
Object Model (DOM). You also learned a few methods of the document object to access, modify,
add, and delete HTML elements in a standard-compliant manner.
Well done! It's time to take a break and get ready for the next lesson where you tackle your first
real-world task: setting and retrieving cookies.
87
Lesson 15: Useful Tasks (I) – Setting and
Retrieving Cookies
By Maria Antonietta Perna
You've come a long way in this tutorial. You're ready to look more closely at how JavaScript
performs a real world task: setting and retrieving cookies.
In the process, you will have occasion to use the global escape() function, the split() method of
the String object, and the toGMTString() method of the Date object.
What's a cookie?
The values stored in JavaScript variables are destroyed as soon as the browser is closed or the
page is reloaded. Therefore, if you use an input box on your web page to store visitors' names in
a variable, that value is lost as soon as they leave the page.
A common feature present in most websites today is some sort of personalization mechanism
whereby web visitors are recognized. Some instances of this personal touch can be things like
greeting returning visitors by their name, indicating how long it's been since the last visit to the
website, showing some products that might be of interest to the user based on past purchases,
etc.
As you might have guessed, we're dealing with values, and if we want to use them in our JavaScript
program, we need a storage place for them. However, all storage places examined so far are
temporary. We need something that persists in between visits to our web page.
Cookies are strings of text containing small pieces of data about your website visitors. They are
stored by the browser in your visitors' computers. Each cookie has a name and an expiration date,
and is separated from other cookies by a semicolon ( ; ). The fact that cookies are all stored in the
same place, retrieving a specific cookie out of the collection to read its values calls for some little
work on our part.
However, before we can retrieve a cookie, we need to write one and store it in the visitor's browser.
88
How do I set cookies with JavaScript?
Cookie data is stored in the document object's cookie property. The data is stored
as "name=value" pairs, in which the values may not contain any whitespace, commas ( , ) and
semicolons ( ; ). This is why we use the escape() method, which enables us to encode the string
in Unicode format (e.g., a space is represented as %20).
By default the lifespan of cookies is limited to the current browser session. However, by setting an
expiry date in the form of an "expires=date" pair, we can prolong the cookie's life (unless the user
decides to delete the cookies stored on her machine). The date value is a GMT string, which can
be obtained by using the Date object and its toGMTString() method.
If you insert the code snippet below inside enclosing <script> tags of an HTML page, you set a
cookie named "myCookie" on your visitor's computer, that expires after a minute starting from
the time of its creation:
if (! document.cookie)
That's all set. The browser running a page containing the code snippet above, will store a cookie
by the name "myCookie" with a value of "Test Cookie", that expires after 1 minute.
89
How do I retrieve and use cookies in my web page?
Retrieving cookies to read their values requires the use of a couple of methods. First, you need
to unescape the name value that you previously escaped. This means that, if your name value
contained a space, it was escaped by replacing the space with %20. Now that you're reading the
value back from the cookie name, you need to replace %20 with a space character. This is easily
done with the unescape() method.
Secondly, you need to extract each name-value pair separately from the cookie string. You do this
with the split() method of the String object.
split() is used to split a string into an array of comma ( , ) separated substrings. It takes an optional
argument called separator. This specifies the character to use for splitting the string.
The code snippet below will check if cookies are present in the cookie property of the document
object. If they are, the script extracts and displays the values of the "myCookie" cookie.
else
90
//item 2 (index 1) is the value, which is what we need:
Summary
Setting and retrieving cookies to make your website visitors feel welcome is a widely used practice
on the web, therefore it's a great new skill to add to your JavaScript toolbox.
Our next useful JavaScript task is how to make sure your website visitors submit a validly filled out
form. This is the topic of our next lesson: form validation.
A web form is a staple feature of almost any website today. Nothing can be more frustrating for
your visitors than filling out all form fields, clicking the submit button, and have the entire form come
back, emptied of all their carefully entered values, and displaying a cryptic error message expecting
them to start all over again.
Any data that comes from users must be validated. This means that programs must check that
no empty values are submitted, that submitted values are of the right type and length, etc.
However, such checks are necessarily performed after the user has filled out and submitted the
form to the server.
If the server is busy and takes a while before alerting the user that the form could not be accepted
due to errors, users might get quite annoyed and decide not to come back to your otherwise
fantastic website.
91
Thankfully, this rarely happens nowadays, thanks to JavaScript. In fact, although it's crucial that
checking user input must be done on the server (e.g., php, .net, ruby, etc.), client-side JavaScript
can do a lot to make the experience less painful and time consuming.
JavaScript runs in the user's browser, therefore it executes immediately. There's no need for the
form to be submitted to the server before alerting the user that, for example, she has left one of
the required fields empty.
Prepare an HTML document with a form and a button, like the one below:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 16: Form validation</title>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<fieldset>
</p>
</fieldset>
</form>
<script type="text/javascript">
</script>
</body>
</html>
92
In between <script> tags write the validate() function as follows:
function validate()
if (userName.length == 0)
return false;
else
Save your work and run the page in a browser. Try submitting the form leaving the inputbox empty,
and see what happens. Can you post the form? I hope not.
More detailed patterns of email addresses, as well as of domain names, zip codes, telephone
numbers, etc., can be validated using a powerful feature called regular expression. A treatment
of regular expressions is beyond the scope of this tutorial. However, if you're interested the web
offers a wealth of material on the subject.
In our code snippet we use some string manipulation methods to make sure the value entered by
the user has an @ character and a dot.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 16: Form validation</title>
93
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<fieldset>
<p><label for="txtEmail">Email:</label>
</p>
</fieldset>
</form>
<script type="text/javascript">
</script>
</body>
</html>
function validate()
if (email.length == 0)
return false;
94
alert("Please, enter a valid email address");
return false;
else
alert("Thank you");
Save your work and preview the page in a browser. Now, enter an email address with no @
character or no dot charachter. Is your form submitting the value to the server? Hopefully, it isn't.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 16: Form validation</title>
<script type="text/javascript" src="lesson16.js"></script>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<fieldset>
<p><label for="txtName">Name:</label>
<p><label for="txtEmail">Email:</label>
</p>
</fieldset>
</form>
95
<p id="result"></p>
</body>
</html>
1. init() binds the main function, validate(), to the form's onsubmit event;
2. validate() examines the results returned by functions validating required fields and email
format and displays an appropriate message;
3. validateRequired(input) checks the input box has a value. It returns true if it has and false
if it hasn't;
4. validateEmail(email) checks the email is valid and returns true if it is, false if it isn't;
5. writeMessage(text) displays a message to users when something goes wrong. It would
be annoying to have alerts popping up every time an error occurs.
function init()
myForm.onsubmit = validate;
/********************************/
onload = init;
/******************************************/
function validate()
96
//validateRequired() and validateEmail()
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
//if the name field is empty, write message to user and stop
submission:
else if (! isRequiredNameSet)
writeMessage(message);
return false;
//If the email field is empty, write message to user and stop
submission:
else if (! isRequiredEmailSet)
writeMessage(message);
return false;
97
}
else if (! isEmailValid)
writeMessage(message);
return false;
alert(message);
/***********************************************/
function validateRequired(input)
if (input.length == 0)
isValid = false;
else
isValid = true;
}
98
return isValid;
/**********************************************/
function validateEmail(email)
isValid = false;
else
isValid = true;
return isValid;
/**********************************************/
function writeMessage(text)
if (paragraph.firstChild)
paragraph.removeChild(paragraph.firstChild);
paragraph.appendChild(document.createTextNode(text));
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above.
Try clicking the submit button without filling out the form properly. If all goes as expected, you
should not be able to submit your form unless it's values are complete and appropriate.
Obviously, your script can't verify an email address, but it can validate its format. Finally, keep in
mind that for a detailed check of the email pattern, the best tool for the job is a regular expression.
Summary
You've come a long way in your JavaScript journey, well done!
Now get ready for the next lesson: time to start exploring the world of JavaScript animation with
the timing functions.
The global window object offers a few little functions that are great if you want to create the effect
of movement or of passing time on the web.
setTimeout();
clearTimeout();
setInterval();
100
clearInterval().
In the process, you will also learn how to preload images with JavaScript and how to build a
simple photo gallery application.
Let's see it in action. In this simple example, we will call up an alertbox 2 seconds after page load.
Type the code below in enclosing <script> tags on a simple HTML page:
function sayHello()
alert("Hello");
function timeGreeting()
timeGreeting();
101
Save your work and run it in a browser. After 2 seconds, an alertbox should pop up to greet you.
To see it in action in its most annoying manifestation, just replace setTimeout with setInterval in
the previous example and you're done.
Now you should see an alertbox greeting you every 2 seconds! That's enough, just close that
window in your browser and let's modify our script so that we can put a stop to that nuisance.
Next, rewrite the preceding JavaScript code and then add the new function as follows:
var greeting;
function sayHello()
alert("Hello");
function timeGreeting()
102
{
timeGreeting();
function stopTimer()
clearInterval(greeting);
Save your work and preview it in a browser. Just click the button and the annyoing alertbox
disappears: that's much better, great! I leave you to experiment with clearTimeout() on your own.
It's easy to find a number of sophisticated photo gallery widgets on the web, that you can download
and readily plug into your own web page.
However, it's still nice to be able to build a simple prototype, just to really challenge yourself with
your newly gained knowledge. In any case, your application can be considered a work in progress,
something that evolves and grows as your JavaScript programming skills evolve and grow.
At this stage, your photo gallery will consist of a photo container and 2 buttons: one button to stop
the gallery, and one button to restart the gallery. As soon as the page loads, the gallery
automatically displays its images one at a time every 2 seconds.
You will also need a few images, possibly all of the same size. For this demo, I prepared four
620px X 378px graphics and saved them in their own images folder.
103
Let's start from the HTML page. This is made of a <div>, an <img> tag, and 2 <input> tags. Also
included are: 1) a small style declaration in the <head> of the document to the effect that the
<div> element that contains the gallery will be centered and sized to the same width and height as
the gallery graphics; and 2) a reference to an external JavaScript file at the bottom of the
<body> element of the HTML page. This location is the most appropriate one because we need
to make sure the HTML page and, most importantly, the image referenced by the <img> tag, are
fully loaded before the script kicks in.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 17: JavaScript Timing Events</title>
<style type="text/css">
#gallery
{
width:620px;
height:378px;
margin: 0 auto;
border:2px solid #ccc;
}
</style>
</head>
<body>
<h1>Lesson 17: My Photo Gallery</h1>
<div id="gallery">
</div>
</body>
</html>
Now prepare the lesson17.js file. Your JavaScript code consists of 3 functions:
1. init() contains initialization routines: it preloads the photo gallery images so that they will
be ready for display as soon as the script calls them. In addition, it binds event handlers to
the 2 button elements to stop and restart the gallery;
2. startGallery() displays each graphic in the gallery every 2 seconds;
3. stopGallery() stops the gallery so that the photo that comes next with respect to the current
photo is not displayed.
Furthermore, the code contains a few global variables at the top that need to be accessed by all
the functions in the script. Let's get started.
104
//Global variables: a reference to the
var galleryStarter;
var counter = 0;
/**************************************/
function init()
preloadedImgs[i].src = images[i];
btnStart.onclick = startGallery;
btnStop.onclick = stopGallery;
if (isGalleryOn)
startGallery();
/*********************************************/
onload = init;
/***********************************************/
function startGallery()
curImage.src = preloadedImgs[counter].src;
counter ++;
if (counter == preloadedImgs.length)
counter = 0;
isGalleryOn = true;
/**************************************************/
function stopGallery()
clearTimeout(galleryStarter);
107
//signal that the gallery has stopped to the
isGalleryOn = false;
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above. Try stopping and restarting your gallery.
When an HTML page is first loaded, all the resources needed by the page, including external CSS
files, scripts, images, videos, etc., are downloaded as well.
In the case of inserting a resource, such as an image, dynamically into an HTML page after the
page has fully loaded in the browser, as it's the case with our photo gallery, the following issue
might arise: the requested image has to be sent to the client browser by the server, and this might
take a few seconds. Although this is not terrible, it might seriously spoil the magic JavaScript
effect we intend to create.
Here's where preloading the images in JavaScript comes to the rescue. By doing the preloading
routine, the image object is created on page load, and by assigning the image filepath as value to
the image object's src property, we make sure that the image we intend to add dynamically to the
page is ready to be grabbed by our script for immediate use.
myNewImage.src = "images/testimage.jpg";
108
Summary
You've made it to the end of the lesson, congratulations! You've learned a great deal: you can set
and stop timers with JavaScript, preload images for dynamic display, and build an automatic photo
gallery with JavaScript.
It's time for your break before tackling your next lesson's topic, a major feature of contemporary
web applications: AJAX.
Behind this amazing feat of human cleverness is the coming together of a few technologies
collectively known as AJAX.
I recommend you get access to a web server to carry out the example code illustrated in this
lesson. In fact, AJAX is all about client-server communication. In view of this, you can upload your
files to a hosted server or to a local server. The PHP tutorial on this website provides an excellent
guide on this topic.
In non-AJAX web applications, the interaction between servers and clients can be a tedious
business:
1. a user action from the client sends a request to the web server via HyperText Transfer
Protocol (HTTP);
109
2. the web server receives the request and processes it by invoking server-side scripts,
database data, etc., and sends a response back to the client via HTTP;
3. the client browser receives the response and loads the entire updated page.
Having to go from browser to server and back again each time a user requests some piece of data
from the server, in addition to undergoing an entire page refresh at each update, can be quite
stressful on servers and on users alike.
What this means in a few words, is that every time the user interacts with the web page, only those
bits that need updating are refreshed, not the entire page. Furthermore, the fact that AJAX
operations are performed asynchronously, means that during the time that it takes for the server
to respond, the page is not locked and the user can still interact with the website.
1. retrievalMethod: this can either be a GET (used to fetch data from the server), or
a POST (used to send data to the server);
2. url: this is the location where the data is made available. It can be a text file, an XML
document, or a server-side script that processes data coming from a database;
3. bool: this is a true/false value. If it's false the request is made synchronously, if it's true the
request is made asynchronously, which is what we usually want.
The XMLHttpRequest object has an onreadystatechange property that deals with the response
from the server. This proceeds over the following 5 stages:
Upon completion (stage 4), the XMLHttpRequest object's status property gets assigned an HTTP
status code that describes the result of the request as follows:
200: success!
401: unauthorized - authentication is required and was not provided;
403: forbidden - the server refuses to respond;
404: not found - the requested resource cannot be found.
This is a simple code snippet that translates what's just been said into practice:
110
//Global variable to store the XMLHttpRequest object
var myRequest;
function getData()
if (window.XMLHttpRequest)
else
myRequest.send(null);
myRequest.onreadystatechange = getData;
111
How do I handle the AJAX response?
If the client browser requests text data, the server response is automatically stored in
the responseText property.
If the client browser requests data in XML format, the server response is stored in
the responseXML property.
function getData()
if (myRequest.readyState ===4)
alert(text);
Let's tackle two examples that include both request and response using AJAX. The first example
will be dealing with a response in plain text format, the second example with a response in XML
format.
The page you're going to build allows the user to click a button to display some text stored in your
text file using AJAX.
112
Here's a simple HTML page with a <header> tag and a button element:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 18: Making AJAX Calls</title>
</head>
<body>
<h1>Lesson 18: Making AJAX Calls - Plain Text Response</h1>
<div>
</div>
<script type="text/javascript">
</script>
</body>
</html>
Here's the JavaScript code that goes in enclosing <script> tags in the HTML page above:
var myRequest;
function getText(url)
if (window.XMLHttpRequest)
else
113
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
myRequest.send(null);
myRequest.onreadystatechange = getData;
/**********************************************/
function getData()
if (myRequest.readyState ===4)
114
myHeader.firstChild.nodeValue = text;
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above.
Notice how the result is returned from the server with no page flashing, no change of URL, no
whole page refresh: that's the AJAX magic.
To follow along in this exercise, prepare a simple XML document and an HTML page.
<languages>
<language>PHP</language>
<language>Ruby On Rails</language>
<language>C#</language>
<language>JavaScript</language>
</languages>
Save the file above as lesson18_test.xml in the same location as your HTML page.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 18: Making AJAX Calls</title>
</head>
<body>
<h1>Lesson 18: Making AJAX Calls - XML Response</h1>
<div id="test">
</div>
<script type="text/javascript">
</script>
</body>
</html>
var myRequest;
function loadXML(url)
if (window.XMLHttpRequest)
else
myRequest.send(null);
myRequest.onreadystatechange = getData;
/******************************************/
function getData()
116
{
if (myRequest.readyState ===4)
var languages =
myRequest.responseXML.getElementsByTagName("language");
myDiv.appendChild(paragraph);
paragraph.appendChild(document.createTextNode(languages[i].firstChild.d
ata));
117
}
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above.
Notice how the result is returned from the server without a whole page refresh. That's terrific!
Summary
That's it for this lesson. You worked really hard, but now you can write JavaScript code that
retrieves data from the server without a whole page refresh using AJAX techniques.
You're not limited to text format files or to XML files, though. In fact, databases are the most
commonly used tools to permanently store data on a server. AJAX techniques are as easily applied
to deal with database retrieved information. However, you'll need PHP or a server-side
programming language to retrieve data from or post data to a database.
In any case, we will return to this topic in our last lesson and see how jQuery greatly simplifies the
whole Ajaxification process.
But first, we need to get some familiarity with the most popular library in the JavaScript
programming world today, jQuery, which is the topic of our next lesson.
You've come a long way in your JavaScript journey. Now it's time to get to the fun part.
This lesson, together with the next 2 lessons, will introduce you to jQuery, the fantastic JavaScript
library invented by John Resig.
However, this is a wide topic and these 3 lessons cannot but give you just a taste for what jQuery
can really do.
Therefore, I encourage you to visit the jQuery website after you finish this tutorial, and explore and
experiment with jQuery's numerous methods, events, effects, etc., for yourself.
118
Why should I use jQuery?
Here are some good reasons why using jQuery in your JavaScript projects is a great idea.
jQuery is:
extremely light-weight (just 31 kb in its latest minified and zipped production-ready version);
it's free and very easy to include in your projects: just download its latest version from the
jQuery website, or use an online Content Delivery Network;
it's continually upgraded, maintained and documented by a dedicated community of great
developers. This ensures high quality and support on the internet;
it helps overcoming inconsistencies in the way some JavaScript features are implemented
across different browsers;
and last but not least, it offers a wealth of ready-made animation effects that are a joy to
use.
1. go to the Download jQuery section of the download page and click on the minified version
of the latest release of jQuery. At the time of writing this is version 1.7;
2. copy and paste the code in a text file;
3. save the file in your web project directory (better if you save it in its own subfolder);
4. in your html page include the appropriate <script> tags in the following order:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 19: Introduction to jQuery</title>
<script type="text/javascript"
src="js/latestjquery.js"></script>
</head>
<body>
<h1>Lesson 19: Introduction to jQuery</h1>
</body>
</html>
119
The reference to jQuery comes before your own JavaScript code file. In fact, your code needs to
find jQuery already fully loaded to be able to use it.
1. go to the CDN Hosted jQuery section of the download page and pick one of the different
CDN services available;
2. copy the URL of your CDN of choice and paste it as the value of the <script> tag's src
attribute, like so:
<script type="text/javascript"
src"yourCDNUrlAddressjQueryFile.js"></script>
3. place a <script> tag with a reference to your own JavaScript file underneath the jQuery
<script> tag, like you did in the previous example.
$(document).ready(function()
alert("jQuery is working!");
});
Save all your files and run the HTML page in a browser. If you typed the code exactly like the
example above, you should be greeted by ... well, the good old alert box.
The $ sign is an alias for jQuery. You could replace it with the keyword jQuery and your jQuery-
powered JavaScript code would work just fine. However, less typing is jQuery's (and all coders')
motto, so using $ is the accepted convention.
120
is where most of your JavaScript code will be placed. This is jQuery's clever way of making sure
your code runs when the document is ready for it: that is, when the html is fully loaded.
$(document).ready(function()
});
The $ sign in front of ("#myDiv") can be translated like: "Hey, browser, get me the element with the
id of myDiv!"
As you can see, the id attribute is grabbed by using the # sign, the same as CSS.
$(document).ready(function)
});
121
Select html elements by class name
A quick way to target html elements that share the same class is as follows:
$(document).ready(function()
});
Now redElements contains an array of all the html elements on your page with a class of classRed.
Once again, notice how jQuery facilitates selection by using the same notation you use in your CSS
declarations to target classes: .className.
Filter Description
Returns all
elements containing the text x
:contains(x)
$(‘div:contains(foo)’) targets all divs with the text 'foo'.
122
A complete list of all selection methods and filters is available on the jQuery website. Have a look
and experiment with the available code samples to gain more familiarity with the new approach.
Both approaches are fine. However, the first one sins against the separation of concerns
principle. In fact, it mixes in JavaScript code with HTML code.
The second approach complies with the separation of concerns principles, but comes short in case
we want to attach more than a function to the same element.
There's actually a third approach that overcomes all shortcomings but one: it's implemented
differently in Internet Explorer browsers with respect to all other major browsers.
The good news is: jQuery is here to make event handling quick and easy. Here are a few jQuery
approaches to choose from.
Suppose you have an html element with an id of myElement, and a function called sayHello(). You
want sayHello() to kick in when the user clicks on the html element. This is how you achieve this
using bind():
$(document).ready(function()
function sayHello()
alert("Hello jQuery");
123
myElement.bind('click', sayHello);
});
Handler Description
change() Binds a handler to the onchange event (when the content of a field changes).
focus() Binds a handler to the onfocus event (when an element gets focus).
Assuming you have an html element with an id attribute of myElement, and a function
called sayHello() - as in the previous example - you can bind sayHello() to the onclick event of
myElement inside jQuery's ready() function like so:
myElement.click(sayHello);
The on() method is highly recommended by the jQuery team if you start a new project.
It can be used to attach handlers both to elements already present in the HTML page from the
start and on dynamically added elements (unlike bind()). Here's how it's used.
Using the same sayHello() function, inside jQuery's .ready() function simply write:
124
myElement.on('click', sayHello);
Anonymous functions
Code samples using jQuery often employ anonymous functions. These are functions without a
name, and can be quite handy, although I find names more helpful in terms of code readability. If
we replace the sayHello() function with an anonymous function, we have:
//Using bind():
myElement.bind('click', function()
alert("Hello jQuery");
});
/********************************/
myElement.click(function()
alert("Hello jQuery");
});
/**************************************/
myElement.on('click', function()
alert("Hello jQuery");
});
125
Add and remove DOM elements
Once grabbed by your JavaScript code, DOM elements can easily be manipulated with jQuery.
You've had a taste of standards-compliant DOM manipulation techniques in this tutorial. Therefore,
you will readily appreciate the jQuery way of performing the same tasks.
If you just need to add new text inside an html element, you can use jQuery's .text() method and
pass a string argument representing the text you intend to add. Like .html(), you can use .text()
without passing any arguments to retrieve text content from the HTML page.
To test .html() prepare an HTML page containing a <div> tag with an id of myElement, a <p> tag
and some text. First we retrieve the existing paragraph element, then we create a new paragraph.
$(document).ready(function()
alert(pageParagraph);
});
/**************************************************/
});
Save all your files and preview the result in a browser. The alert should display the original
paragraph's content, and the page should subsequently display the new paragraph's content.
126
The way you implement .text() is the same as .html(). I leave you to experiment with it on your
own. More details on .html() can be found on http://api.jquery.com/html/, and on .text() can be
found on http://api.jquery.com/text/.
Use the same HTML page from the previous example and add a button element with an id
of btnDelete.
$(document).ready(function()
$('#btnDelete').click(function()
$('p').remove();
});
});
Save all your files and preview the HTML page in a browser. Click the button and see the
paragraphs on the page disappear.
Summary
There's a lot to digest in this introduction to jQuery and you've done a great job coming as far as
you did.
jQuery is such a rich library that it can't be covered in a few lessons. Therefore, I invite you to
practice with all the code samples in this lesson and the following lessons as much as you can.
Also, it's crucial that you explore the jQuery website and experiment with the code samples
available in their documentation and tutorials. If you have doubts, don't hesitate to send us a line
in the forum dedicated to this tutorial.
More on jQuery coming up in the next lesson: get ready for some fabulous JQuery effects in just
a few lines of code!
127
Lesson 20: Cool Animation Effects with jQuery
jQuery is so rich with ready-made functions that adding fancy effects on your web page is a breeze.
It's hard not to get carried away with it.
Here, we are going to explore the most commonly used jQuery effects. Once again, my
recommendation is that of integrating this lesson with a visit to the jQuery website for more code
samples and detailed explanations.
In the process, you will build a simple sliding menu and get more practice with the new jQuery
approach.
Because $.css() would sprinkle your HTML page with inline CSS style rules, we will focus on
applying and removing CSS classes with $.addClass(className), $.removeClass(className),
and $.toggleClass(className). This approach uses the CSS class declarations stored either in
the <head> of your HTML page or in a separate file, therefore it's better suited to current best
practices in web design.
If you're curious about $.css(), by all means visit http://api.jquery.com/css/ for more details.
Suppose you want to replace the CSS class bigDiv with the CSS class smallDiv when the user
clicks inside the div element. This is how you could do the task with jQuery:
$(document).ready(function()
myDiv.click(function()
128
//Remove the existing CSS class and replace it with the new one.
myDiv.removeClass('bigDiv').addClass('smallDiv');
});
});
What about toggling between the CSS bigDiv and smallDiv classes by clicking inside the div?
That's easy: jQuery has this little handy method for you - $.toggleClass(). Assuming the CSS
class bigDiv is hard-coded in the class attribute of the div element, you can toggle the CSS
class smallDiv using jQuery, like so:
$(document).ready(function()
myDiv.click(function()
myDiv.toggleClass('smallDiv');
});
});
Now, keep clicking inside the div element, and you'll see it getting smaller and bigger at each click
of the mouse.
Let's say you have a paragraph element inside a div with an id of myDiv. You want the paragraph
to slowly disappear when the user clicks inside the div element. Here's how you could accomplish
this with jQuery hide().
$(document).ready(function()
129
var myDiv = $('#myDiv');
myDiv.click(function()
$('p').hide('slow');
});
});
Clicking inside the div element results in the paragraph slowly disappearing from view.
jQuery show() works the same way. I leave you to experiment with it on your own.
What if you wanted to toggle between show/hide transitions as the user clicks inside the div
element? No problem, jQuery offers the $.toggle() method. To see it in action, simply
replace hide() with toggle() in the previous example, like so.
$(document).ready(function()
myDiv.click(function()
$('p').toggle('slow');
});
});
Here's the paragraph from the previous code sample toggling between visible and hidden using
$.fadeToggle().
$(document).ready(function()
$('p').fadeToggle('slow');
});
});
For example, let's say you want to slide the paragraph element from the previous example up and
down as the user clicks inside the div element. Here's how you would accomplish this
with $.slideToggle().
$(document).ready(function()
myDiv.click(function()
$('p').slideToggle('slow');
});
});
Now keep clicking inside the div element and see the paragraph inside the div sliding up and down.
I recommend you experiment with the code samples above as much as you can before moving on
with the next challenge.
131
The user moves the mouse over a main menu item and a list of sub-menu items slides down. As
the user moves the mouse away from the menu item, its sub-menu items slide back up away from
view.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 20: jQuery Sliding Menu</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.min.js"></script>
</head>
<body>
<h1>Lesson 20: jQuery Sliding Menu</h1>
<div id="myDiv">
<ul class="outerList">
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2 ↓</a>
<div>
<ul class="innerList">
<li><a href="#">Sub-Menu Item 1</a></li>
<li><a href="#">Sub-Menu Item 2</a></li>
<li><a href="#">Sub-Menu Item 3</a></li>
</ul>
</div>
</li>
<li><a href="#">Menu Item 3</a></li>
</ul>
</div>
</body>
</html>
The HTML page above has a reference to a CDN-served copy of jQuery and to an external
JavaScript file in the <head> section.
The <body> section has a div element with an id of myDiv that contains a list with 3 main menu
items and 3 sub-menu items nested inside the second main menu item. The sub-menu items are
contained inside a div element.
Style your menu so that the main menu items are horizontally lined up and the nested sub-menu
items are vertically stacked under their parent li element (take a peek at the example page if you
like).
132
We want the div element that wraps the sub-menu items to slide down when the user moves the
mouse over its parent li element.
$(document).ready(function()
subItems.hide();
//menu items:
$(mainItems).hover(function()
subItems.slideToggle('fast');
});
});
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above, only reflecting your own CSS styles.
Move your mouse over the second menu item and if all goes as expected you'll see the sub-menu
sliding down. It's taken us just a few lines of code to accomplish an animation effect that in raw
JavaScript would have made us sweat quite a bit.
133
Summary
You've achieved a lot in this lesson. You know how to use several jQuery functions to manipulate
styles. Also, you know how to add fancy effects to your web pages with very little code. Finally,
you put your new knowledge to the test by building a core website component - a horizontal sliding
menu - using jQuery.
I still advise you to pop over to the jQuery website for a detailed coverage of everything this
fabulous library has to offer.
Our next lesson revisits a topic we covered back in lesson 18, get ready for AJAX done the jQuery
way.
Back in lesson 18 you used AJAX by dealing directly with the XMLHttpRequest object. You also
performed some feature testing for Internet Explorer browsers that didn't support the
XMLHttpRequest object.
jQuery provides wrapper methods that shield you from the inner mechanisms of an AJAX request.
To follow along with the examples in this lesson, you need to have access to a server, just as you
did back in lesson 18.
If you use $.load(htmlPageUrl) passing only the URL of the HTML document as argument, the
entire content of the HTML document is loaded into the calling page.
Instead, I like to use $.load(htmlPageUrl fragmentIdentifier), which exactly targets the bit of content
I intend to retrieve.
Prepare an HTML page containing a div element with an id of content and a paragraph element
with some dummy content. Save it as content.html (or anything you like), and upload it to your
server. This document provides the content to retrieve using AJAX.
134
Prepare a second HTML page containing a link element, a div element with an id of result, a
reference to the jQuery library in the <head> section, and enclosing <script> tags in the <body>
section for your own jQuery-powered JavaScript code.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 21: Easy AJAX Calls with jQuery</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.min.js"></script>
</head>
<body>
<h1>Lesson 21: Easy AJAX Calls with jQuery load()</h1>
<div id="result">
</div>
<script type="text/javascript">
</script>
</body>
</html>
For these simple demos, we're going to embed our JavaScript code inside the HTML page.
However, keep in mind that, if you write code for a website, it's highly recommended that you use
external JavaScript files.
When the user clicks on the link on your HTML page, an AJAX request will be made
to content.html targeting the text inside the div element with an id of content. This text is
dynamically inserted in the div with an id of result in the calling page.
To achieve this, enter the following code snippet inside the enclosing <script> tags:
$(document).ready(function()
$('a').click(function()
135
//and load the content from the specified url
$('#result').load('content.html #content');
});
});
Show example
Save your work and preview it in a browser. You should see something like the page indicated by
following the example link above.
Click the link, and if all goes well, the dummy text from content.html is loaded inside the div element
on the page. The operation takes place asynchronously without a full page refresh.
You can use $.get() to load data from the server with a GET HTTP request - that is, via a query
string (see Lesson 10: Passing variables in a URL in the PHP tutorial on HTML.net for a great
introduction to query strings).
Let's see how to use jQuery .get() to retrieve the XML document you used back in lesson 18.
The HTML page that makes the AJAX request remains unchanged from the previous example.
Rewrite the JavaScript code as follows:
$(document).ready(function()
/*************************************/
136
//Package the result-handling code
function processData(data)
$(items).each(function(i)
$('#result').html(resultStr);
});
/****************************************/
137
//request is sent to the server:
$('a').click(function()
//as arguments:
$.get(url, processData);
});
});
Show example
Save all your files on the server and click on the link. If all goes well, you should see a list of
programming languages being displayed on the page without a full page refresh.
In the example above, you came across jQuery .find() and jQuery .each().
$.find() is used to find a DOM element's descendants or children. In the example above, you used
it to find all children called language of the root XML element contained in the variable called data.
Further details on $.find() can be accessed on http://api.jquery.com/find/.
$.each(index) is a for ... loop done the jQuery way. It's extremely concise and efficient. Notice the
use of $(this) inside the $.each() function block. This is a snappy way of referring to the item the
loop is currently processing: in our example above $(this) refers to one of the language items in
the items array.
Unlike GET requests, POST requests don't use a query string to send data. If you intend to send
more than a few bits of data to the sever, or if you intend to send sensitive data, it's recommended
you use an HTTP POST request.
The way you implement $.post() is very similar to the way you implemented $.get() in the previous
example. I invite you to experiment with it on your own and to
visit http://api.jquery.com/jQuery.post/ for more code samples and useful details.
138
For instance, let's say you want to retrieve a list of programming languages from the XML
document you used in the previous example. You might want to specify the following options:
Use the HTML page and the XML document from the previous example. Also, keep the url variable
and the processData() function from the previous exercise - you will use both as the url and the
success arguments respectively inside the $.ajax() function. Delete everything else inside the
document.ready() function. Just below the processData() function, write the following code:
/*************************************/
$('a').click(function()
$.ajax(
type: "GET",
cache: false,
url: url,
139
dataType: "xml",
contentType: "text/html",
success: processData,
error: errorAlert
Save your work and preview it in a browser. The result should be similar to the previous example.
If an error occurs, you'll be presented with an alert box. The errorAlert() function has an e argument
that represents the type of error, and an jqxhr argument that represents the request as a jQuery
object.
In case an error occurs, details about the error are automatically contained in the arguments
provided and will be displayed in the alert box.
Do you want to test the error catching function? Simply replace dataType: "xml" in the $.ajax()
function with dataType: "text/xml". Save all your files and run the HTML page. Now, when you
click the link, an alert box should pop up displaying a parser error message.
Summary
You got to the end of the lesson, and also to the end of this JavaScript tutorial. Congratulations!
Now you're familiar with the core JavaScript syntax and objects. You know how to include
the jQuery library in your projects to add flair to your web pages and make AJAX calls easily
and efficiently.
I encourage you to keep experimenting with code samples and to be an active participant in
JavaScript forums. Why not starting from the forums on HTML.net? It's easy to register and meet
with the real experts in your programming language of choice.
As you might have already guessed, the best way to learn coding is to keep coding ... a lot.
The only thing left is for me to wish you hours of fun with your new friends, JavaScript and jQuery.
140