File

advertisement
Lesson 3: Elements and tags
You are now ready to learn the essence of HTML: elements.
Elements give structure to a HTML document and tells the browser how you want your
website to be presented. Generally elements consists of a start tag, some content, and an
end tag.
"Tags"?
Tags are labels you use to mark up the begining and end of an element.
All tags have the same format: they begin with a less-than sign "<" and end with a greaterthan sign ">".
Generally speaking, there are two kinds of tags - opening tags: <html> and closing tags:
</html>. The only difference between an opening tag and a closing tag is the forward slash
"/". You label content by putting it between an opening tag and a closing tag.
HTML is all about elements. To learn HTML is to learn and use different tags.
Can you show me some examples?
Okay, the element em emphasis text. All text between the opening tag <em> and the closing
tag </em> is emphasised in the browser. ("em" is short for "emphasis".)
Example 1:
<em>Emphasised text.</em>
Will look like this in the browser:
Emphasised text.
The elements h1, h2, h3, h4, h5 and h6 is used to make headings (h stands for "heading"),
where h1 is the first level and normally the largest text, h2 is the second level and normally
slightly smaller text, and h6 is the sixth and last in the hierarchy of headings and normally the
smallest text.
Example 2:
<h1>This is a heading</h1>
<h2>This is a subheading</h2>
Will look like this in the browser:
This is a heading
This is a subheading
So, I always need an opening tag and a
closing tag?
As they say, there's an exception to every rule and in HTML the exception is that there are a
few elements which both open and close in the same tag. These so-called empty elements
are not connected to a specific passage in the text but rather are isolated labels, for
example, a line break which looks like this: <br />.
Should tags be typed in uppercase or
lowercase?
Most browsers might not care if you type your tags in upper, lower or mixed cases. <HTML>,
<html> or <HtMl> will normally give the same result. However, the correct way is to type
tags in lowercase. So get into the habit of writing your tags in lowercase.
Where do I put all these tags?
You type your tags in an HTML document. A website contains one or more HTML
documents. When you surf the Web, you merely open different HTML documents.
If you continue to the next lesson in 10 minutes you will have made your first website.
Lesson 3: Elements and tags
You are now ready to learn the essence of HTML: elements.
Elements give structure to a HTML document and tells the browser how you want your
website to be presented. Generally elements consists of a start tag, some content, and an
end tag.
"Tags"?
Tags are labels you use to mark up the begining and end of an element.
All tags have the same format: they begin with a less-than sign "<" and end with a greaterthan sign ">".
Generally speaking, there are two kinds of tags - opening tags: <html> and closing tags:
</html>. The only difference between an opening tag and a closing tag is the forward slash
"/". You label content by putting it between an opening tag and a closing tag.
HTML is all about elements. To learn HTML is to learn and use different tags.
Can you show me some examples?
Okay, the element em emphasis text. All text between the opening tag <em> and the closing
tag </em> is emphasised in the browser. ("em" is short for "emphasis".)
Example 1:
<em>Emphasised text.</em>
Will look like this in the browser:
Emphasised text.
The elements h1, h2, h3, h4, h5 and h6 is used to make headings (h stands for "heading"),
where h1 is the first level and normally the largest text, h2 is the second level and normally
slightly smaller text, and h6 is the sixth and last in the hierarchy of headings and normally the
smallest text.
Example 2:
<h1>This is a heading</h1>
<h2>This is a subheading</h2>
Will look like this in the browser:
This is a heading
This is a subheading
So, I always need an opening tag and a
closing tag?
As they say, there's an exception to every rule and in HTML the exception is that there are a
few elements which both open and close in the same tag. These so-called empty elements
are not connected to a specific passage in the text but rather are isolated labels, for
example, a line break which looks like this: <br />.
Should tags be typed in uppercase or
lowercase?
Most browsers might not care if you type your tags in upper, lower or mixed cases. <HTML>,
<html> or <HtMl> will normally give the same result. However, the correct way is to type
tags in lowercase. So get into the habit of writing your tags in lowercase.
Where do I put all these tags?
You type your tags in an HTML document. A website contains one or more HTML
documents. When you surf the Web, you merely open different HTML documents.
If you continue to the next lesson in 10 minutes you will have made your first website.
Lesson 5: What have you learned so
far?
Always start with the basic template we made in the previous lesson:
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
In the head section, always write a title: <title>The title of your page</title>. Notice
how the title will be shown in the upper left corner of your browser:
The title is especially important because it is used by search engines (such as Google) to
index your website and is shown in the search results.
In the body section, you write the actual content of the page. You already know some of the
most important elements:
<p>Is used for paragraphs.</p>
<em>Emphasis text.</em>
<h1>Heading</h1>
<h2>Subhead</h2>
<h3>Sub-subhead</h3>
Remember, the only way to learn HTML is by trial and error. But don't worry, there is no way
you can destroy your computer or the Internet. So keep experimenting - that is the best way
to gain experience.
What is that supposed to mean?
Nobody becomes a good website creator by learning the examples in this tutorial. What you
get in this tutorial is simply a basic understanding of the building blocks - to become good
you must use the building blocks in new and creative ways.
So, get out in the deep water and stand on your own two feet... Okay, maybe not. But give it
a go and experiment with what you have learned.
So what's next?
Try to create a few pages yourself. For instance, make a page with a title, a heading, some
text, a subhead and some more text. It is perfectly okay to look in the tutorial while you make
your first pages. But later, see if you can do it on your own - without looking.
Lesson 6: A few more elements
Did you manage to make a few pages on your own? If not, here is an example:
<html>
<head>
<title>My website</title>
</head>
<body>
<h1>A Heading</h1>
<p>text, text text, text</p>
<h2>Subhead</h2>
<p>text, text text, text</p>
</body>
</html>
Now what?
Now it is time to learn seven new elements.
In the same way you emphasise the text by putting it between the openning tag <em> and
the closing tag </em>, you can give stronger emphasis by using the openning
tag <strong> and the closing tag </strong>.
Example 1:
<strong>Stronger emphasis.</strong>
Will look like this in the browser:
Stronger emphasis.
Likewise, you can make your text smaller using small:
Example 2:
<small>This should be in small.</small>
Will look like this in the browser:
This should be in small.
Can I use several elements at the same time?
You can easily use several elements at the same time as long as you avoid overlapping
elements. This is best illustrated by an example:
Example 3:
If you want to emphasise small text, it must be done like this:
<em><small>Emphasised small text</small></em>
And NOT like this:
<em><small>Emphasise small text</em></small>
The difference is that in the first example, we closed the tag we first opened last. This way
we avoid confusing both ourselves and the browser.
More elements!
As mentioned in Lesson 3 there are elements which are opened and closed in the same
tag. These so-called empty elements are not connected to a specific passage in the text but
rather are isolated labels. An example of such a tag is <br /> which creates a forced line
break:
Example 4:
Some text<br /> and some more text in a new line
Will look like this in the browser:
Some text
and some more text in a new line
Notice that the tag is written as a contraction of an opening and closing tag with an empty
space and a forward slash at the end: <br />.
Another element that is opened and closed in the same tag is <hr /> which is used to draw
a horizontal line ("hr" stands for "horizontal rule"):
Example 5:
<hr />
Will look like this in the browser:
Examples of elements that needs both an opening tag and a closing tag - as most elements
do - is ul, ol and li. These elements are used when you want to make lists.
ul is short for "unordered list" and inserts bullets for each list item. ol is short for "ordered
list" and numbers each list item. To make items in the list use the li tag ("list item").
Confused? See the examples:
Example 7:
<ul>
<li>A list item</li>
<li>Another list item</li>
</ul>
will look like this in the browser:


A list item
Another list item
Example 8:
<ol>
<li>First list item</li>
<li>Second list item</li>
</ol>
will look like this in the browser:
1. First list item
2. Second list item
Phew! Is that all?
That is all for now. Again, experiment and make your own pages using some of the seven
new elements you learned in this lesson:
<strong>Stronger emphasis</strong>
<small>Small text</small>
<br /> Line shift
<hr /> Horizontal line
<ul>List</ul>
<ol>Ordered list</ol>
<li>List item</li>
Lesson 7: Attributes
You can add attributes to a number of elements.
What is an attribute?
As you probably remember, elements give structure to a HTML document and tells the
browser how you want your website to be presented (for example,<br /> informs the
browser to make a line break). In some elements you can add more information. Such
additional information is called an attribute.
Example 1:
<h2 style="background-color:#ff0000;">My friendship with
HTML</h2>
Attributes are always written within a start tag and are followed by an equals sign and the
attribute details written between inverted commas. The semicolon after the attribute is for
separating different style commands. We will get back to that later.
What is the catch?
There are many different attributes. The first one you will learn is style. With the style
attribute you can add layout to your website. For instance a background colour:
Example 2:
<html>
<head>
</head>
<body style="background-color:#ff0000;">
</body>
</html>
will show a completely red page in the browser - go ahead and see for yourself. We will
explain in greater detail how the colour system works in a few moments.
Note that some tags and attributes use US spelling i.e. color instead of colour. It is important
that you are careful to use the same spelling as we use in the examples in this tutorial otherwise, browsers will not be able to understand your codes. Also, don't forget to always
close the inverted commas (quotation marks) after an attribute.
How did the page become red?
In the above example, we asked for the background colour with the code "#ff0000". This is
the colour code for red using so called hexadecimal numbers (HEX). Each colour has its
own hexadecimal number. Here are some examples:
White: #ffffff
Black: #000000 (zeros)
Red: #ff0000
Blue: #0000ff
Green: #00ff00
Yellow: #ffff00
A hexadecimal colour code consists of # and six digits or letters. There are more than 1000
HEX codes and it is not easy to figure out which HEX code is tied to a specific colour. To
make it easier we have made a chart of the 216 most commonly used colours: 216 Web
Safe Colour Chart.
You can also use the English name for the most common colours (white, black, red, blue,
green and yellow).
Example 3:
<body style="background-color: red;">
Enough about colours. Let's get back to the attributes.
Which elements can use attributes?
Different attributes can be applied to most elements.
You will often use attributes in tags such as the body tag while you will rarely use attributes
in, for example, a br tag since a line break normally is a line break without any parameters to
adjust.
Just as there are many different elements, so there are many different attributes. Some
attributes are tailor made for one particular element while others can be used for many
different element. And vice versa: some elements can only contain one kind of attribute while
others can contain many.
It may sound a bit confusing but once you get acquainted with the different attributes it is
actually very logical and you will soon see how easy they are to use and how many
possibilities they provide.
This tutorial will introduce you to the most important attributes.
Exactly what parts does an element consist
of?
Generally an elements consist of a start tag with or without one or more attributes, some
content and an end tag. Simple as that. See the illustration below.
Lesson 8: Links
In this lesson, you will learn how to make links between pages.
What do I need to make a link?
To make links, you use what you always use when coding HTML: an element. A simple
element with one attribute and you will be able to link to anything and everything. Here
is an example of what a link to HTML.net could look like:
Example 1:
<a href="http://www.html.net/">Here is a link to HTML.net</a>
Would look like this in the browser:
Here is a link to HTML.net
The element a stands for "anchor". And the attribute href is short for "hypertext reference",
which specifies where the link leads to - typically an address on the internet or a file name.
In the above example the attribute href has the value "http://www.html.net", which is the full
address of HTML.net and is called a URL (Uniform Resource Locator). Note that "http://"
must always be included in URLs. The sentence "Here is a link to HTML.net" is the text that
is shown in the browser as the link. Remember to close the element with an </a>.
What about links between my own pages?
If you want to make a link between pages on the same website, you do not need to spell out
the entire address (URL) for the document. For example, if you have made two pages (let us
call them page1.htm and page2.htm) and saved them in the same folder you can make a link
from one page to the other by only typing the name of the file in the link. Under such
circumstances a link from page1.htm to page2.htm could look like this:
Example 2:
<a href="page2.htm">Click here to go to page 2</a>
If page 2 were placed in a subfolder (named "subfolder"), the link could look like this:
Example 3:
<a href="subfolder/page2.htm">Click here to go to page 2</a>
The other way around, a link from page 2 (in the subfolder) to page 1 would look like this:
Example 4:
<a href="../page1.htm">A link to page 1</a>
"../" points to the folder one level up from position of the file from which the link is made.
Following the same system, you can also point two (or more) folders up by writing "../../".
Did you understand the system? Alternatively, you can always type the complete address for
the file (URL).
What about internal links within a page?
You can also create internal links within a page - for example a table of contents at the top
with links to each chapter below. All you need to use is a very useful attribute
called id (identification) and the symbol "#".
Use the id attribute to mark the element to which you want to link. For example:
<h1 id="heading1">heading 1</h1>
You can now create a link to that element by using "#" in the link attribute. The "#" must be
followed by the id of the tag you want to link to. For example:
<a href="#heading1">Link to heading 1</a>
All will become clear with an example:
Example 5:
<html>
<head>
</head>
<body>
<p><a href="#heading1">Link to heading 1</a></p>
<p><a href="#heading2">Link to heading 2</a></p>
<h1 id="heading1">heading 1</h1>
<p>Text text text text</p>
<h1 id="heading2">heading 2</h1>
<p>Text text text text</p>
</body>
</html>
will look like this in the browser (click on the two links):
Link to heading 1
Link to heading 2
Heading 1
Text text text text
Heading 2
Text text text text
(Note: An id attribut must start with a letter)
Can I link to anything else?
You can also make a link to an e-mail address. It is done in almost the same way as when
you link to a document:
Example 6:
<a href="mailto:nobody@html.net">Send an e-mail to nobody at
HTML.net</a>
will look like this in the browser:
Send an e-mail to nobody at HTML.net
The only difference between a link to an e-mail and a link to a file is that instead of typing the
address of a document, you type mailto: followed by an e-mail address. When the link is
clicked, the default e-mail program opens with a new blank message addressed to the
specified e-mail address. Please note that this function will only work if there is an e-mail
program installed on your computer. Give it a try!
Are there any other attributes I should know
of?
To create a link, you always have to use the href attribute. In addition, you can also put
a title on your link:
Example 7:
<a href="http://www.html.net/" title="Visit HTML.net and learn
HTML">HTML.net</a>
Would look like this in the browser:
HTML.net
The title attribute is used to type a short description of the link. If you - without clicking - place
the cursor over the link, you will see the text "Visit HTML.net and learn HTML" appears.
Lesson 9: Images
Wouldn't it be great if you could have an image of actor and music legend David Hasselhoff
right in the centre of your page?
That sounds like a bit of a challenge...
Maybe, but in fact it is pretty easy to do. All you need is an element:
Example 1:
<img src="david.jpg" alt="David" />
would look like this in the browser:
All you need do is first tell the browser that you want to insert an image (img) and then where
it is located (src, short for "source"). Do you get the picture?
Notice how the img element is opened and closed using the same tag. Like the <br /> tag,
it is not tied to a piece of text.
"david.jpg" is the name of the image file you want to insert in your page. ".jpg" is the file type
of the image. Just like the extension ".htm" shows that a file is an HTML document, ".jpg"
tells the browser that a file is a picture. There are three different types of image file types you
can insert into your pages:



GIF (Graphics Interchange Format)
JPG / JPEG (Joint Photographic Experts Group)
PNG (Portable Network Graphics)
GIF images are usually best for graphics and drawings, while JPEG images are
usually better for photographs. This is for two reasons: first, GIF images only consist of
256 colours, while JPEG images comprise of millions of colours and second, the GIF format
is better at compressing simple images, than the JPEG format which is optimized for more
complex images. The better the compression, the smaller the size of the image file, the
faster your page will load. As you probably know from your own experience, unnecessarily
'heavy' pages can be extremely annoying for the user.
Traditionally, the GIF and JPEG formats have been the two dominant image types, but lately,
the PNG format has become more and more popular (primarily at the expense of the GIF
format). The PNG format contains in many ways the best of both the JPEG and GIF
format: millions of colours and effective compressing.
Where do I get my images from?
To make your own images, you need an image editing program. An image editing program
is one of the most essential tools you need to create beautiful websites.
Unfortunately, no good image editing programs comes with Windows or other operating
systems. Thus, you might consider investing in either Paint Shop Pro, PhotoShop or
Macromedia Fireworks, which are three of the best image editing programs currently on the
market.
However, as we said before, it will not be necessary to buy expensive programs to complete
this tutorial. For now, you can download the excellent image editing program IrfanView which
is so-called freeware and therefore costs nothing.
Or you can just borrow images from other sites by downloading them. But please be careful
not to violate copyrights when downloading pictures. Still, it's useful to know how to
download pictures, so here's how you do it:
1. Right-click on an image on any image on the Internet.
2. Choose "Save picture as..." in the menu that appears.
3. Choose a location for the image on your computer and press "Save".
Do this with the image below and save it on your computer at the same location as your
HTML documents. (Notice that the logo is saved as a PNG file: logo.png):
Now you can insert the image into one of your own pages. Try it yourself.
Is that all I need to know about images?
There are a few more things you should know about images.
First, you can easily insert pictures located in other folders, or even pictures that are located
on other websites:
Example 2:
<img src="images/logo.png" />
Example 3:
<img src="http://www.html.net/logo.png" />
Second, images can be links:
Example 4:
<a href="http://www.html.net">
<img src="logo.png" /></a>
will look like this in the browser (try clicking on the image):
Are there any other attributes I should know
about?
You always need to use the attribute src, which tells the browser where the image is
located. Besides that, there are a number of other attributes which can be useful when
inserting images.
The alt attribute is used to give an alternate description of an image if, for some reason, the
image is not shown for the user. This is especially important for users with impaired vision, or
if the page is loaded very slowly. Therefore, always use the alt attribute:
Example 5:
<img src="logo.gif" alt="HTML.net logo" />
Some browsers let the text of the alt attribute appear as a small pop-up box when the user
places their cursor over the picture. Please note that when using the alt attribute, the aim is
to provide an alternative description of the picture. The alt attribute should not be used to
create special pop-up messages for the user since then visually impaired users will hear the
message without knowing what the picture is.
The title attribute can be used to add information to the image:
Example 6:
<img src="logo.gif" title="Learn HTML from HTML.net" />
Will look like this in the browser:
If you, without clicking, place the cursor over the image, you will see the text "Learn HTML
from HTML.net" appear as a pop-up box.
Two other important attributes are width and height:
Example 7:
<img src="logo.png" width="141px" height="32px" />
will look like this in the browser:
The width and height attributes can be used to set the height and width of an image. The
value that is used to set the width and height is pixels. Pixels are the units of measurement
used to measure the resolution of screens. (The most common screen resolution is
1024x768 pixels). Unlike centimetres, pixels are relative units of measurement which depend
on the resolution of the screen. To a user with a high screen resolution, 25 pixels may
correspond to 1 centimetre, while the same 25 pixel in a low screen resolution may
correspond to 1.5 centimetres on the screen.
If you do not set the width and height, the image will be inserted in its actual size. But with
width and height you can manipulate the size:
Example 8:
<img src="logo.gif" width="32px" height="32px" />
will look like this in the browser:
However, it is worth keeping in mind that the actual size in kilobytes of the image file will
remain the same so it will take the same time to load the image as it did before, even though
it appears smaller on the screen. Therefore, you should never decrease the image size by
using the width and height attributes. Instead, you should always resize your images in
an image editing program to make your pages lighter and faster.
That said, it is still a good idea to use the width and height attributes because the browser
will then be able to detect how much space the image will need in the final page layout
before the image is fully downloaded. This allows your browser to set up the page nicely in a
quicker way.
That's enough about David Hasselhoff and images for now.
Lesson 10: Tables
Tables are used when you need to show "tabular data" i.e. information that is logically
presented in rows and columns.
Is it difficult?
Building tables in HTML may at first seem complicated but if you keep cool and watch your
step, it is actually strictly logical - just like everything else in HTML.
Example 1:
<table>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</table>
Will look like this in the browser:
Cell 1
Cell 2
Cell 3
Cell 4
What's the difference between <tr> and <td>?
As you will see from the above example, this is probably the most complicated HTML
example we have given you so far. Let's break it down and explain the different tags:
3 different elements are used to insert tables:



The opening tag <table> and the closing tag </table> starts and ends the table.
Logical.
<tr> stands for "table row" and starts and ends horizontal rows. Still logical.
<td> is short for "table data". This tag starts and ends each cell in the rows of your
table. All simple and logical.
Here is what happens in Example 1: the table starts with a <table>, followed by a <tr>,
which indicates the beginning of a new row. Two cells are inserted in this row: <td>Cell
1</td> and <td>Cell 2</td>. The row is hereafter closed with a </tr> and a new
row <tr> begins immediately after. The new row also contains two cells. The table is closed
with </table>.
Just to make it clear: rows are horizontal lines of cells and columns are vertical lines of
cells:
Cell 1
Cell 2
Cell 3
Cell 4
Cell 1 and Cell 2 form a row. Cell 1 and Cell 3 form a column.
In the above example, the table has two rows and two columns. However, a table can have
an unlimited number of rows and columns.
Example 2:
<table>
<tr>
<td>Cell
<td>Cell
<td>Cell
<td>Cell
1</td>
2</td>
3</td>
4</td>
<td>Cell
<td>Cell
<td>Cell
<td>Cell
5</td>
6</td>
7</td>
8</td>
<td>Cell
<td>Cell
<td>Cell
<td>Cell
9</td>
10</td>
11</td>
12</td>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
Will look like this in the browser:
Cell 1
Cell 2
Cell 3
Ce
Cell 5
Cell 6
Cell 7
Ce
Cell 9
Cell 10
Cell 11
Ce
Are there any attributes?
Of course there are attributes. For example, the border attribute is used to specify the
thickness of the border around your table:
Example 3:
<table border="1">
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</table>
Will look like this in the browser:
Cell 1
Cell 2
Cell 3
Cell 4
The thickness of the border is specified in pixels (See lesson 9)
As with images, you can also set the width of a table in pixels - or alternatively in percentage
of the screen:
Example 4:
<table border="1" width="30%">
This example will be displayed in the browser as a table with the width of 30% of the screen.
Try it yourself.
More attributes?
There are lots of attributes for tables. Here are two more:


align: specifies the horizontal alignment of the content in the entire table, in a row or
in a single cell. For example, left, center or right.
valign: specifies the vertical alignment of the content in a cell. For example, top,
middle or bottom.
Example 5:
<td align="right" valign="top">Cell 1</td>
What can I insert in my tables?
Theoretically, you can insert anything in tables: text, links and images... BUT tables are
meant for presenting tabular data (i.e. data which can be meaningfully presented in
columns and rows) so refrain from putting things into tables simply because you want them
to be placed next to each other.
In the old days on the Internet - i.e. a few years ago - tables were often used as a layout tool.
But if you want to control the presentation of texts and images there is a much cooler way to
do it (hint: CSS). But more about that later.
Now, put what you just learned to practice and design a number of tables in different sizes,
with different attributes and content. This should keep you busy for hours.
Lesson 11: More about tables
The title "More about tables" may sound a bit boring. But look at the positive side, when you
master tables, there is absolutely nothing about HTML that will knock you out.
What is left then?
The two attributes colspan and rowspan are used when you want to create fancy tables.
Colspan is short for "column span". Colspan is used in the <td> tag to specify how
many columns the cell should span:
Example 1:
<table border="1">
<tr>
<td colspan="3">Cell 1</td>
</tr>
<tr>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</table>
Will look like this in the browser:
Cell 1
Cell 2
Cell 3
Cell 4
By setting colspan to "3", the cell in the first row spans three columns. If we instead had
set colspan to "2", the cell would only have spanned two columns and it would have been
necessary to insert an additional cell in the first row so that the number of columns will fit in
the two rows.
Example 2:
<table border="1">
<tr>
<td colspan="2">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
<td>Cell 5</td>
</tr>
</table>
Will look like this in the browser:
Cell 1
Cell 2
Cell 3
Cell 4
What about rowspan?
As you might already have guessed, rowspan specifies how many rows a cell should
span over:
Example 3:
<table border="1">
<tr>
<td rowspan="3">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
Cell 5
</tr>
<tr>
<td>Cell 4</td>
</tr>
</table>
Will look like this in the browser:
Cell 2
Cell 1
Cell 3
Cell 4
In the example above rowspan is set to "3" in Cell 1. This specifies that the cell must span
over 3 rows (its own row plus an additional two). Cell 1 and Cell 2 are thereby in the same
row, while Cell 3 and Cell 4 form two independent rows.
Confused? Well, it is not uncomplicated and it is easy to lose track. Therefore, it might be a
good idea to draw the table on a piece of paper before you begin with the HTML.
Not confused? Then go ahead and create a couple of tables with
both colspan and rowspan on your own.
Lesson 12: Layout (CSS)
Wouldn't be great if you could give your pages the layout they deserve?
Sure, but how?
To give your website layout use Cascading Style Sheets (CSS). In this lesson you will
get a short introduction to CSS. But later you can learn all about CSS from scratch in our
CSS tutorial. So please consider this lesson only as an appetizer.
CSS is the better half of HTML. And in coding, there is no equality of status: HTML takes
care of the rough stuff (the structure), while CSS gives it a nice touch (layout).
As shown in Lesson 7, CSS can be added with the style attribute. For example, you can
set the font type and size on a paragraph:
Example 1:
<p style="font-size:20px;">This is typed in size 20px</p>
<p style="font-family:courier;">This is typed in Courier</p>
<p style="font-size:20px; font-family:courier;">This is typed in
Courier size 20px</p>
Will look like this in the browser:
This is typed in size 20px
This is typed in Courier
This is typed in Courier size 20px
In the example above we use the style attribute to specify the type of font to be used (with
the command font-family) and the font size (with the command font-size). Notice how
in the last paragraph we set both the font type and size with a separating semicolon.
It seems like a lot of work?
One of the smart features of CSS is the possibility to manage your layout centrally.
Instead of using the style attribute in each tag, you can tell the browser once how it must
layout all the text on the page:
Example 2:
<html>
<head>
<title>My first CSS page</title>
<style type="text/css">
h1 {font-size: 30px; font-family: arial;}
h2 {font-size: 15px; font-family: courier;}
p {font-size: 8px; font-family: "times new roman";}
</style>
</head>
<body>
<h1>My first CSS page</h1>
<h2>Welcome to my first CSS page</h2>
<p>Here you can see how CSS works </p>
</body>
</html>

Show example
In the example above CSS has been inserted in the head section and therefore applies
to the entire page. To do this, just use the tag <style type="text/css"> which tells the
browser that you are typing CSS.
In the example all headings on the page will be in Arial in size 30px. All subheads will in
Courier size 15. And all text in normal paragraphs will be in Times New Roman size 8.
Another option is to type the CSS in a separate document. With a separate CSS document
you can manage the layout of many pages all at once. Pretty smart if you want to change
the font type or size on a large website with hundreds or thousands of pages. We won't go
into that now but you can learn it later in our CSS tutorial.
What else can I do with CSS?
CSS can be used for much more than specifying font types and sizes. For example, you can
add colours and backgrounds. Here are some examples for you to experiment with:
<p style="color:green;">Green text</p>
<h1 style="background-color: blue;">Heading on blue
background</h1>
<body style="background-image:
url('http://www.html.net/logo.png');">
Try inserting the examples in some of your pages - both as shown above and also as CSS
inserted in the head section.
Is CSS nothing but colours and font types?
Besides adding layout such as colors, font types etc., CSS can also be used to control the
page setup and presentation (margins, float, alignment, width, height etc.). By regulating
the different elements with CSS you are able to layout your pages elegantly and precisely.
Example 3:
<p style="padding:25px;border:1px solid red;">I love CSS</p>
Will look like this in the browser:
I love CSS
With the property float an element can either be floated to the right or to the left. The
following example illustrates the principle:
Example 4:
<img src="bill.jpg" alt="Bill Gates" style= "float:left;" />
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam nonummy nibh euismod tincidunt ut laoreet
dolore
magna aliquam erat volutpat. Ut wisi enim ad minim
veniam,
quis nostrud exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo consequat...</p>
Will look like this in the browser:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis
nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat...
In the example, one element (the image) floats to the left and the other element (the text) fills
the hole.
With the property position, you can place an element exactly where you want it in your
page:
Example 5:
<img src="bill.jpg" alt="Bill Gates"
style="position:absolute;bottom:50px;right:10px;" />

Show example
In the example the image is placed 50 pixels from the bottom and 10 pixels from the right in
the browser. But you can place it exactly where you want it. Give it a try. Pretty easy and
pretty cool, eh?
Cool, sure. But easy?
You do not learn CSS in 10 minutes. And as mentioned above, this lesson is only meant
as a brief introduction. Later you will learn much more in ourCSS Tutorial.
For now, concentrate on HTML, and move on to the next lesson where you will learn how to
get your website out on the Internet so the whole world can see it!
Lesson 13: Uploading pages
Until now, only you have had the satisfaction of viewing your pages. Now it is time for the
rest of the world to see your masterpieces.
Is the world ready for that?
The world is ready - you soon will be too. To get your website on the internet, you just
need some server space and a free FTP program.
If you have Internet access, you might already have some free server space for your
website. Your server space will then probably be called something like
http://home.provider.com/~usernumber. But you might need to activate it first. Read more
about this in the papers from your Internet provider or on their support pages.
Another option is to get some free server space on the Internet. In the same way that you set
up an e-mail account (at for example Hotmail), you can register for free server space on
the Internet. Several companies offer such a service - among them 000webhost.com (click
"Order Now" under "Free Hosting") - it will only take a couple of minutes to register.
To have access to the server, you need to know the "Host Name" (For example,
ftp.htmlnet.site50.net) and have your username and password ready.
Is that all I need?
To access the server and upload your pages, you also need an FTP program. FTP is short
for File Transfer Protocol. A FTP program is used to connect two computers over the Internet
so that you can transfer files from your computer to another computer (the server). You might
not have such a program yet, but fortunately, this can be downloaded for free.
There are many different FTP programs. One of the better is FileZilla, which is entirely
free. So now you can download FileZilla atfilezilla.sourceforge.net.
And how do I upload the pages?
Described below is how you upload your pages to a free account at 000webhost.com with
FileZilla. But the procedure is, more or less, the same for all providers and FTP programs.
Open the FTP program while connected to the Internet. Insert "Host Name"
("ftp.htmlnet.site50.net" under "Address"), username (under "User") and password (under
"Password") and click "Connect". You should now have access to the server. In one side of
the program you can see the contents of your computer ("Local Site"), and in the other side,
you can see the content of the server ("Remote Site"):
Find your HTML documents and images on your computer (on the "Local site") and transfer
them to the server (the "Remote site") by double clicking on them. Now the whole world can
see them! (For example, at the address http://htmlnet.site50.net/page1.htm).
Name one of the pages "index.htm" (or "index.html") and it will automatically become the
start page. i.e. if you type http://htmlnet.site50.net (without any filename) you will actually
open http://htmlnet.site50.net/index.htm.
In the long run, it might be a good idea to purchase your own domain (for example
www.your-name.com or www.your-name.net) and avoid the long and complicated addresses
you are being assigned by your Internet provider or from providers of free server space. You
can find and purchase domains at for example Speednames or NetworkSolutions.
Lesson 14: Web standards and
validation
In this lesson, you will get a little more theoretical knowledge on HTML.
What more is there to know about HTML?
HTML can be coded in many different ways. And browsers can read HTML in just as many
ways. You could say that HTML has many dialects. That is why some websites look
different in different browsers.
There have been attempts to make a common standard of HTML through the World
Wide Web Consortium (W3C) founded by Tim Berners-Lee (yep! the great guy who
invented HTML). But it has been a long and tough road.
In the old days - when browsers where something you had to pay for - Netscape was the
dominate browser. Back then, the most supported HTML standard where called 2.0 and later
3.2. But with a market share of over 90% Netscape did not have to - and did not - care much
about common standards. On the contrary, Netscape invented their own strange elements,
which did not function in other browsers.
For many years Microsoft almost completely ignored the Internet. After a while they took up
the competition with Netscape and introduced a browser. The first versions of Microsoft's
browser, Internet Explorer, were not any better than Netscape at supporting the HTML
standards. But Microsoft chose to give away their browser for free (always a popular thing to
do) and Internet Explorer soon became the most popular browser.
From version 4 and 5 Microsoft aimed to support more and more of the HTML standards
from W3C. Netscape did not manage to develop a new version of their browser and
continued to distribute the outdated version 4.
The rest is history. Today the HTML standards are called 4.01 and XHTML. Now it is Internet
Explorer that has a market share of over 90%. Internet Explorer still has its own strange
elements but it also supports the W3C HTML standards. And so do all of the other browsers,
such as Mozilla, Opera and Netscape.
So, when you code HTML following the W3C standards, you make websites that can
be seen in all browsers - both now and in the future. And luckily, what you have learned
in this tutorial is a new and stricter and cleaner version of HTML called XHTML.
How do I tell which version is used?
With all the different types of HTML you need to tell the browser which "dialect" your HTML is
in, in your case XHTML. To do that, you use a Document Type Declaration. The Document
Type Declaration is always written in the top of the document:
Example 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Title</title>
</head>
<body>
<p>text text</p>
</body>
</html>
Besides the Document Type Declaration (the first line in the example above), which tells the
browser that you want to write XHTML, you also need to insert some extra information in the
html tag with the two attributes xmlns and lang.
xmlns is short for "XML-Name-Space" and should always have the
value http://www.w3.org/1999/xhtml. That is all you need to know. But if you have a big
hunger for complicated knowledge you can read more about namespaces on W3C's website.
In the lang attribute you state which language the document is written in. For this the ISO
639 standard is used, which lists codes for all the languages in the world. In the example
above the language are set to English ("en").
With a DTD the browser knows exactly how it should read and show your HTML. Hence, use
the example above as template for all your future HTML documents.
The DTD is also important when you want to validate your pages.
Validate? Why and how should I do that?
Insert a DTD in your pages and you can always check your HTML for errors by using W3C's
free validator.
To test this out, make a page and upload it to the Internet. Now, go to validator.w3.org and
type the address (the URL) of your page and validate it. If your HTML is correct you will get a
congratulations message. Otherwise you will get an error report telling you exactly what and
where you have done something wrong. Make some errors on purpose to see what happens.
The validator is not just helpful to locate an error. Some browsers try to compensate for lack
of skills among web developers by trying to fix errors in the HTML and showing the page as
they guess it should look. With such browsers, you might never see an error in your own
browser. However, other browsers might guess differently or not show the page at all. The
validator can help you find errors you did not even know existed.
Always validate your pages to be sure they will always be shown correctly.
Lesson 15: The final tips
Congratulations, you have now reached the final lesson.
So now I know everything?
You have learned a lot and you are now capable of making your own websites! However,
what you have learned are the basics and there is still a lot more to be mastered. But you
now have a good foundation from which to build on.
In this last lesson, you will get some final tips:






First, it is a good idea to maintain order and structure in your HTML documents. By
posting well arranged documents you will not only show others your mastery of
HTML but will also make it considerably easier for yourself to keep an overview.
Stick to the standards and validate your pages. This cannot be stressed enough:
Always write clean XHTML, use a DTD and validate your pages on validator.w3c.org.
Give your page contents. Remember that HTML is a tool, which enables you to
present information on the Internet, so make sure that there is information to present.
Pretty pages may look nice but most people use the Internet to find information.
Avoid overloading your pages with heavy images and other fancy stuff you have
found on the Internet. It slows down the loading of the page and could be confusing
for visitors. Pages that take more than 20 seconds to load can lose up to 50% of their
visitors.
Remember to add your website to search engines/directories so people other than
your closest family can find and enjoy it. On the front page of all search engines, you
will find a link to add new pages (The most important is Google, but there are also
others like DMOZ, Yahoo, AltaVista,AlltheWeb and Lycos).
In this tutorial, you have learned to use Notepad, which is a simple and very easy to
use editor, but perhaps you will find it helpful to use a more advanced editor which
gives a better overview and more possibilities. You can find a summary and reviews
of different editors on Download.com.
How do I learn more?
First of all, it is important that you continue to work and experiment with the things you have
learned in this tutorial. Study other people's websites and if you find something you like see
how it was made with "View Source" (Click "View" in the menu in your browser and choose
"Source").
Search the Internet for examples and articles on HTML. There are lots of websites with great
contents on HTML.
Read and ask questions in the Forums. This is where you meet the real experts from whom
you can learn a lot.
Last, but not least, you should - whenever you feel ready - continue learning CSS in our CSS
Tutorial.
The only thing left is to wish you hours of fun with your new friend, HTML.
See you on the Internet :-)
Lesson 1: What is CSS?
Maybe you already heard about CSS without really knowing what it is. In this lesson you will
learn more about what CSS is and what it can do for you.
CSS is an acronym for Cascading Style Sheets.
What can I do with CSS?
CSS is a style language that defines layout of HTML documents. For example, CSS covers
fonts, colours, margins, lines, height, width, background images, advanced positions and
many other things. Just wait and see!
HTML can be (mis-)used to add layout to websites. But CSS offers more options and is more
accurate and sophisticated. CSS is supported by all browsers today.
After only a few lessons of this tutorial you will be able to make your own style sheets using
CSS to give your website a new great look.
What is the difference between CSS and
HTML?
HTML is used to structure content. CSS is used for formatting structured content.
Okay, it sounds a bit technical and confusing. But please continue reading. It will all make
sense to you soon.
Back in the good old days when Madonna was a virgin and a guy called Tim Berners Lee
invented the World Wide Web, the language HTML was only used to add structure to text.
An author could mark his text by stating "this is a headline" or "this is a paragraph" using
HTML tags such as <h1> and <p>.
As the Web gained popularity, designers started looking for possibilities to add layout to
online documents. To meet this demand, the browser producers (at that time Netscape and
Microsoft) invented new HTML tags such as for example <font> which differed from the
original HTML tags by defining layout - and not structure.
This also led to a situation where original structure tags such as <table> were increasingly
being misused to layout pages instead of adding structure to text. Many new layout tags
such as <blink> were only supported by one type of browser. "You need browser X to view
this page" became a common disclaimer on web sites.
CSS was invented to remedy this situation by providing web designers with sophisticated
layout opportunities supported by all browsers. At the same time, separation of the
presentation style of documents from the content of documents, makes site maintenance a
lot easier.
Which benefits will CSS give me?
CSS was a revolution in the world of web design. The concrete benefits of CSS include:




control layout of many documents from one single style sheet;
more precise control of layout;
apply different layout to different media-types (screen, print, etc.);
numerous advanced and sophisticated techniques.
In the next lesson we take a closer look at how CSS actually works and how you get started.
Lesson 2: How does CSS work?
In this lesson you will learn how to make your first style sheet. You will get to know about the
basic CSS model and which codes are necessary to use CSS in an HTML document.
Many of the properties used in Cascading Style Sheets (CSS) are similar to those of HTML.
Thus, if you are used to use HTML for layout, you will most likely recognize many of the
codes. Let us look at a concrete example.
The basic CSS syntax
Let's say we want a nice red color as the background of a webpage:
Using HTML we could have done it like this:
<body bgcolor="#FF0000">
With CSS the same result can be achieved like this:
body {background-color: #FF0000;}
As you will note, the codes are more or less identical for HTML and CSS. The above
example also shows you the fundamental CSS model:
But where do you put the CSS code? This is exactly what we will go over now.
Applying CSS to an HTML document
There are three ways you can apply CSS to an HTML document. These methods are all
outlined below. We recommend that you focus on the third method i.e. external.
Method 1: In-line (the attribute style)
One way to apply CSS to HTML is by using the HTML attribute style. Building on the above
example with the red background color, it can be applied like this:
<html>
<head>
<title>Example</title>
</head>
<body style="background-color: #FF0000;">
<p>This is a red page</p>
</body>
</html>
Method 2: Internal (the tag style)
Another way is to include the CSS codes using the HTML tag <style>. For example like
this:
<html>
<head>
<title>Example</title>
<style type="text/css">
body {background-color: #FF0000;}
</style>
</head>
<body>
<p>This is a red page</p>
</body>
</html>
Method 3: External (link to a style sheet)
The recommended method is to link to a so-called external style sheet. Throughout this
tutorial we will use this method in all our examples.
An external style sheet is simply a text file with the extension .css. Like any other file, you
can place the style sheet on your web server or hard disk.
For example, let's say that your style sheet is named style.css and is located in a folder
named style. The situation can be illustrated like this:
The trick is to create a link from the HTML document (default.htm) to the style sheet
(style.css). Such link can be created with one line of HTML code:
<link rel="stylesheet" type="text/css" href="style/style.css" />
Notice how the path to our style sheet is indicated using the attribute href.
The line of code must be inserted in the header section of the HTML code i.e. between
the <head> and </head> tags. Like this:
<html>
<head>
<title>My document</title>
<link rel="stylesheet" type="text/css"
href="style/style.css" />
</head>
<body>
...
This link tells the browser that it should use the layout from the CSS file when displaying the
HTML file.
The really smart thing is that several HTML documents can be linked to the same style
sheet. In other words, one CSS file can be used to control the layout of many HTML
documents.
This technique can save you a lot of work. If you, for example, would like to change the
background color of a website with 100 pages, a style sheet can save you from having to
manually change all 100 HTML documents. Using CSS, the change can be made in a few
seconds just by changing one code in the central style sheet.
Let's put what we just learned into practice.
Try it yourself
Open Notepad (or whatever text editor you use) and create two files - an HTML file and a
CSS file - with the following contents:
default.htm
<html>
<head>
<title>My document</title>
<link rel="stylesheet" type="text/css" href="style.css"
/>
</head>
<body>
<h1>My first stylesheet</h1>
</body>
</html>
style.css
body {
background-color: #FF0000;
}
Now place the two files in the same folder. Remember to save the files with the right
extensions (respectively ".htm" and ".css")
Open default.htm with your browser and see how the page has a red background.
Congratulations! You have made your first style sheet!
Hurry on to the next lesson where we will take a look at some of the properties in CSS.
Lesson 3: Colors and backgrounds
In this lesson you will learn how to apply colors and background colors to your websites. We
will also look at advanced methods to position and control background images. The following
CSS properties will be explained:







color
background-color
background-image
background-repeat
background-attachment
background-position
background
Foreground color: the 'color' property
The color property describes the foreground color of an element.
For example, imagine that we want all headlines in a document to be dark red. The
headlines are all marked with the HTML element <h1>. The code below sets the color
of <h1> elements to red.
h1 {
color: #ff0000;
}

Show example
Colors can be entered as hexadecimal values as in the example above (#ff0000), or you can
use the names of the colors ("red") or rgb-values (rgb(255,0,0)).
The 'background-color' property
The background-color property describes the background color of elements.
The element <body> contains all the content of an HTML document. Thus, to change the
background color of an entire page, the background-color property should be applied to
the <body> element.
You can also apply background colors to other elements including headlines and text. In the
example below, different background colors are applied to<body> and <h1> elements.
body {
background-color: #FFCC66;
}
h1 {
color: #990000;
background-color: #FC9804;
}

Show example
Notice that we applied two properties to <h1> by dividing them by a semicolon.
Background images [background-image]
The CSS property background-image is used to insert a background image.
As an example of a background image, we use the butterfly below. You can download the
image so you can use it on your own computer (right click the image and choose "save
image as"), or you can use another image as you see fit.
To insert the image of the butterfly as a background image for a web page, simply apply the
background-image property to <body> and specify the location of the image.
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
}
h1 {
color: #990000;
background-color: #FC9804;
}

Show example
NB: Notice how we specified the location of the image as url("butterfly.gif"). This means
that the image is located in the same folder as the style sheet. You can also refer to images
in other folders using url("../images/butterfly.gif") or even on the Internet indicating the full
address of the file:url("http://www.html.net/butterfly.gif").
Repeat background image [backgroundrepeat]
In the example above, did you notice that by default the butterfly was repeated both
horizontally and vertically to cover the entire screen? The propertybackgroundrepeat controls this behaviour.
The table below outlines the four different values for background-repeat.
Value
Description
background-repeat: repeat-x
The image is repeated horizontally
background-repeat: repeat-y
The image is repeated vertically
background-repeat: repeat
The image is repeated both horizontally and vertically
background-repeat: no-repeat
The image is not repeated
For example, to avoid repetition of a background image the code should look like this:
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
}
h1 {
color: #990000;
background-color: #FC9804;
}

Show example
Lock background image [backgroundattachment]
The property background-attachment specifies whether a background picture is fixed or
scrolls along with the containing element.
A fixed background image will not move with the text when a reader is scrolling the page,
whereas an unlocked background image will scroll along with the text of the web page.
The table below outlines the two different values for background-attachment. Click on the
examples to see the difference between scroll and fixed.
Value
Description
Background-attachment: scroll
The image scrolls with the page - unlocked
Background-attachment: fixed
The image is locked
For example, the code below will fix the background image.
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
background-attachment: fixed;
}
h1 {
color: #990000;
background-color: #FC9804;
}

Show example
Place background image [backgroundposition]
By default, a background image will be positioned in the top left corner of the screen. The
property background-position allows you to change this default and position the
background image anywhere you like on the screen.
There are numerous ways to set the values of background-position. However, all of them
are formatted as a set of coordinates. For example, the value '100px 200px' positions the
background image 100px from the left side and 200px from the top of the browser window.
The coordinates can be indicated as percentages of the browser window, fixed units (pixels,
centimetres, etc.) or you can use the words top, bottom, center, left and right. The model
below illustrates the system:
The table below gives some examples.
Value
Description
background-position: 2cm 2cm
The image is positioned 2 cm from the left and 2 cm down the
background-position: 50% 25%
The image is centrally positioned and one fourth down the pag
background-position: top right
The image is positioned in the top-right corner of the page
The code example below positions the background image in the bottom right corner:
body {
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: right bottom;
}
h1 {
color: #990000;
background-color: #FC9804;
}

Show example
Compiling [background]
The property background is a short hand for all the background properties listed in this
lesson.
With background you can compress several properties and thereby write your style sheet in
a shorter way which makes it easier to read.
For example, look at these five lines:
background-color: #FFCC66;
background-image: url("butterfly.gif");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: right bottom;
Using background the same result can be achieved in just one line of code:
background: #FFCC66 url("butterfly.gif") no-repeat fixed right
bottom;
The list of order is as follows:
[background-color] | [background-image] | [background-repeat] | [backgroundattachment] | [background-position]
If a property is left out, it will automatically be set to its default value. For example,
if background-attachment and background-position are taken out of the example:
background: #FFCC66 url("butterfly.gif") no-repeat;
These two properties that are not specified would merely be set to their default values which
as you know are scroll and top left.
Summary
In this lesson, you have already learned new techniques that would not be possible using
HTML. The fun continues in the next lesson which examines the broad range of possibilities
when using CSS to describe fonts.
Lesson 4: Fonts
In this lesson you will learn about fonts and how they are applied using CSS. We will also
look at how to work around the issue that specific fonts chosen for a website can only be
seen if the font is installed on the PC used to access the website. The following CSS
properties will be described:






font-family
font-style
font-variant
font-weight
font-size
font
Font family [font-family]
The property font-family is used to set a prioritized list of fonts to be used to display a
given element or web page. If the first font on the list is not installed on the computer used to
access the site, the next font on the list will be tried until a suitable font is found.
There are two types of names used to categorize fonts: family-names and generic families.
The two terms are explained below.
Family-name
Examples of a family-name (often known as "font") can e.g. be "Arial", "Times New
Roman" or "Tahoma".
Generic family
Generic families can best be described as groups of family-names with uniformed
appearances. An example is sans-serif, which is a collection of fonts without "feet".
The difference can also be illustrated like this:
When you list fonts for your web site, you naturally start with the most preferred font followed
by some alternative fonts. It is recommended to complete the list with a generic font family.
That way at least the page will be shown using a font of the same family if none of the
specified fonts are available.
An example of a prioritized list of fonts could look like this:
h1 {font-family: arial, verdana, sans-serif;}
h2 {font-family: "Times New Roman", serif;}

Show example
Headlines marked with <h1> will be displayed using the font "Arial". If this font is not installed
on the user's computer, "Verdana" will be used instead. If both these fonts are unavailable, a
font from the sans-serif family will be used to show the headlines.
Notice how the font name "Times New Roman" contains spaces and therefore is listed using
quotation marks.
Font style [font-style]
The property font-style defines the chosen font either in normal, italic or oblique. In the
example below, all headlines marked with <h2> will be shown in italics.
h1 {font-family: arial, verdana, sans-serif;}
h2 {font-family: "Times New Roman", serif; font-style: italic;}

Show example
Font variant [font-variant]
The property font-variant is used to choose between normal or small-caps variants of a
font. A small-caps font is a font that uses smaller sized capitalized letters (upper case)
instead of lower case letters. Confused? Take a look at these examples:
If font-variant is set to small-caps and no small-caps font is available the browser will
most likely show the text in uppercase instead.
h1 {font-variant: small-caps;}
h2 {font-variant: normal;}

Show example
Font weight [font-weight]
The property font-weight describes how bold or "heavy" a font should be presented. A
font can either be normal or bold. Some browsers even support the use of numbers
between 100-900 (in hundreds) to describe the weight of a font.
p {font-family: arial, verdana, sans-serif;}
td {font-family: arial, verdana, sans-serif; font-weight: bold;}

Show example
Font size [font-size]
The size of a font is set by the property font-size.
There are many different units (e.g. pixels and percentages) to choose from to describe font
sizes. In this tutorial we will focus on the most common and appropriate units. Examples
include:
h1 {font-size: 30px;}
h2 {font-size: 12pt;}
h3 {font-size: 120%;}
p {font-size: 1em;}

Show example
There is one key difference between the four units above. The units 'px' and 'pt' make the
font size absolute, while '%' and 'em' allow the user to adjust the font size as he/she see fit.
Many users are disabled, elderly or simply suffer from poor vision or a monitor of bad
quality. To make your website accessible for everybody, you should use adjustable units
such as '%' or 'em'.
Below you can see an illustration of how to adjust the text size in Mozilla Firefox and Internet
Explorer. Try it yourself - neat feature, don't you think?
Compiling [font]
Using the font short hand property it is possible to cover all the different font properties in
one single property.
For example, imagine these four lines of code used to describe font-properties for <p>:
p {
font-style: italic;
font-weight: bold;
font-size: 30px;
font-family: arial, sans-serif;
}
Using the short hand property, the code can be simplified:
p {
font: italic bold 30px arial, sans-serif;
}
The order of values for font is:
font-style | font-variant | font-weight | font-size | font-family
Summary
You have now learned about some of the possibilities related to fonts. Remember that one of
the major advantages of using CSS to specify fonts is that at any given time, you can change
font on an entire website in just a few minutes. CSS saves time and makes your life easier.
In the next lesson we will look at text.
Lesson 5: Text
Formatting and adding style to text is a key issue for any web designer. In this lesson you will
be introduced to the amazing opportunities CSS gives you to add layout to text. The
following properties will be described:





text-indent
text-align
text-decoration
letter-spacing
text-transform
Text indention [text-indent]
The property text-indent allows you to add an elegant touch to text paragraphs by
applying an indent to the first line of the paragraph. In the example below a 30px is applied
to all text paragraphs marked with <p>:
p {
text-indent: 30px;
}

Show example
Text alignment [text-align]
The CSS property text-align corresponds to the attribute align used in old versions of
HTML. Text can either be aligned to the left, to the right orcentred. In addition to this, the
value justify will stretch each line so that both the right and left margins are straight. You
know this layout from for example newspapers and magazines.
In the example below the text in table headings <th> is aligned to the right while the table
data <td> are centred. In addition, normal text paragraphs are justified:
th {
text-align: right;
}
td {
text-align: center;
}
p {
text-align: justify;
}

Show example
Text decoration [text-decoration]
The property text-decoration makes it is possible to add different "decorations" or
"effects" to text. For example, you can underline the text, have a line through or above the
text, etc. In the following example, <h1> are underlined headlines, <h2> are headlines with a
line above the text and <h3> are headlines with a line though the text.
h1 {
text-decoration: underline;
}
h2 {
text-decoration: overline;
}
h3 {
text-decoration: line-through;
}

Show example
Letter space [letter-spacing]
The spacing between text characters can be specified using the property letter-spacing.
The value of the property is simply the desired width. For example, if you want a spacing
of 3px between the letters in a text paragraph <p> and 6px between letters in
headlines <h1> the code below could be used.
h1 {
letter-spacing: 6px;
}
p {
letter-spacing: 3px;
}

Show example
Text transformation [text-transform]
The text-transform property controls the capitalization of a text. You can choose
to capitalize, use uppercase or lowercase regardless of how the original text is looks in the
HTML code.
An example could be the word "headline" which can be presented to the user as
"HEADLINE" or "Headline". There are four possible values for text-transform:
capitalize
Capitalizes the first letter of each word. For example: "john doe" will be "John Doe".
uppercase
Converts all letters to uppercase. For example: "john doe" will be "JOHN DOE".
lowercase
Converts all letters to lowercase. For example: "JOHN DOE" will be "john doe".
none
No transformations - the text is presented as it appears in the HTML code.
As an example, we will use a list of names. The names are all marked with <li> (list-item).
Let's say that we want names to be capitalized and headlines to be presented in uppercase
letters.
Try to take a look at the HTML code for this example and you will see that the text actually is
in lowercase.
h1 {
text-transform: uppercase;
}
li {
text-transform: capitalize;
}

Show example
Summary
In the last three lessons you have already learned several CSS properties, but there is much
more to CSS. In the next lesson we will take a look at links.
Lesson 6: Links
You can apply what you already learned in the previous lessons to links (i.e. change colors,
fonts, underline, etc). The new thing is that CSS allows you to define these properties
differently depending on whether the link is unvisited, visited, active, or whether the cursor is
on the link. This makes it possible to add fancy and useful effects to your website. To control
these effects you use so-called pseudo-classes.
What is a pseudo-class?
A pseudo-class allows you to take into account different conditions or events when defining a
property for an HTML tag.
Let's look at an example. As you know, links are specified in HTML with <a> tags. We can
therefore use a as a selector in CSS:
a {
color: blue;
}
A link can have different states. For example, it can be visited or not visited. You can use
pseudo-classes to assign different styles to visited and unvisited links.
a:link {
color: blue;
}
a:visited {
color: red;
}
Use a:link and a:visited for unvisited and visited links respectively. Links that are active
have the pseudo-class a:active and a:hover is when the cursor is on the link.
We will now go through each of the four pseudo-classes with examples and further
explanation.
Pseudo-class: link
The pseudo-class :link is used for links leading to pages that the user has not visited.
In the code example below, unvisited links will be light blue.
a:link {
color: #6699CC;
}

Show example
Pseudo-class: visited
The pseudo-class :visited is used for links leading to pages that the user has visited. For
example, the code below would make all visited links dark purple:
a:visited {
color: #660099;
}

Show example
Pseudo-class: active
The pseudo-class :active is used for links that are active.
This example gives active links a yellow background color:
a:active {
background-color: #FFFF00;
}

Show example
Pseudo-class: hover
The pseudo-class :hover is used when the mouse pointer hovers over a link.
This can be used to create interesting effects. For example, if we want our links to be orange
and be italicized when the cursor is pointed at them, our CSS should look like this:
a:hover {
color: orange;
font-style: italic;
}

Show example
Example 1: Effect when the cursor is over a
link
It is particular popular to create different effects when the cursor is over a link. We will
therefore look at a few extra examples related to the pseudo-class:hover.
Example 1a: Spacing between letters
As you will remember from lesson 5, the spacing between letters can be adjusted using the
property letter-spacing. This can be applied to links for a special effect:
a:hover {
letter-spacing: 10px;
font-weight:bold;
color:red;
}

Show example
Example 1b: UPPERCASE and lowercase
In lesson 5 we looked at the property text-transform, which can switch between upperand lowercase letters. This can also be used to create an effect for links:
a:hover {
text-transform: uppercase;
font-weight:bold;
color:blue;
background-color:yellow;
}

Show example
The two examples gives you an idea about the almost endless possibilities for combining
different properties. You can create your own effects - give it a try!
Example 2: Remove underline of links
A frequently asked question is how to remove the underlining of links?
You should consider carefully whether it is necessary to remove the underlining as it
might decrease usability of your website significantly. People are used to blue
underlined links on web pages and know that they can click on them. Even my mum knows
that! If you change the underlining and color of links there is a good chance that users will
get confused and therefore not get the full benefit of the content on your website.
That said, it is very simple to remove the underlining of links. As you will recall from lesson 5,
the property text-decoration can be used to determine whether text is underlined or not.
To remove underlining, simply set the value of text-decoration to none.
a {
text-decoration:none;
}
Alternatively, you can set text-decoration along with other properties for all four pseudoclasses.
a:link {
color: blue;
text-decoration:none;
}
a:visited {
color: purple;
text-decoration:none;
}
a:active {
background-color: yellow;
text-decoration:none;
}
a:hover {
color:red;
text-decoration:none;
}

Show example
Summary
In this lesson you have learned about pseudo-classes, using some of the properties from the
previous lessons. This should give you an idea of some the possibilities CSS provides.
In the next lesson we will teach you how to define properties for specific elements and
groups of elements.
Lesson 7: Identification and grouping of
elements (class and id)
Sometimes you want to apply a special style to a particular element or a particular group of
elements. In this lesson, we will take a closer look at how you can use class and id to
specify properties for selected elements.
How can you color one particular headline differently than the other headlines on your
website? How can you group your links into different categories and give each category a
special style? These are just examples of questions we will answer in this lesson.
Grouping elements with class
Let's say that we have two lists of links of different grapes used for white wine and red wine.
The HTML code could look like this:
<p>Grapes for white wine:</p>
<ul>
<li><a href="ri.htm">Riesling</a></li>
<li><a href="ch.htm">Chardonnay</a></li>
<li><a href="pb.htm">Pinot Blanc</a></li>
</ul>
<p>Grapes for red wine:</p>
<ul>
<li><a href="cs.htm">Cabernet Sauvignon</a></li>
<li><a href="me.htm">Merlot</a></li>
<li><a href="pn.htm">Pinot Noir</a></li>
</ul>

Show example
Then we want the white wine links to be yellow, the red wine links to be red and the rest of
the existing links on the webpage to stay blue.
To achieve this, we divide the links into two categories. This is done by assigning a class to
each link using the attribute class.
Let us try to specify some classes in the example above:
<p>Grapes for white wine:</p>
<ul>
<li><a href="ri.htm" class="whitewine">Riesling</a></li>
<li><a href="ch.htm" class="whitewine">Chardonnay</a></li>
<li><a href="pb.htm" class="whitewine">Pinot Blanc</a></li>
</ul>
<p>Grapes for red wine:</p>
<ul>
<li><a href="cs.htm" class="redwine">Cabernet Sauvignon</a></li>
<li><a href="me.htm" class="redwine">Merlot</a></li>
<li><a href="pn.htm" class="redwine">Pinot Noir</a></li>
</ul>
We can hereafter define special properties for links belonging to whitewine and redwine,
respectively.
a {
color: blue;
}
a.whitewine {
color: #FFBB00;
}
a.redwine {
color: #800000;
}

Show example
As shown in the example you can define the properties for elements which belong to a
certain class by using .classname in the style sheet of the document.
Identification of element using id
In addition to grouping elements, you might need to identify one unique element. This is
done by using the attribute id.
What is special about the attribute id is that there can not be two elements in the same
document with the same id. Each id has to be unique. In other cases, you should use
the class attribute instead. Now, let us take a look at an example of a possible usage of id:
<h1>Chapter
...
<h2>Chapter
...
<h2>Chapter
...
<h1>Chapter
...
<h2>Chapter
...
<h3>Chapter
...
1</h1>
1.1</h2>
1.2</h2>
2</h1>
2.1</h2>
2.1.2</h3>
The above could be headings of any document split into chapters or paragraphs. It would be
natural to assign an id to each chapter as follows:
<h1
...
<h2
...
<h2
...
<h1
...
<h2
...
<h3
...
id="c1">Chapter 1</h1>
id="c1-1">Chapter 1.1</h2>
id="c1-2">Chapter 1.2</h2>
id="c2">Chapter 2</h1>
id="c2-1">Chapter 2.1</h2>
id="c2-1-2">Chapter 2.1.2</h3>
Let us say that the headline for chapter 1.2 must be in red. This can be done accordingly
with CSS:
#c1-2 {
color: red;
}

Show example
As shown in the example above you can define the properties in a specific element by using
#id in the stylesheet of the document.
Summary
In this lesson we have learned that through the use of the selectors, class and id, you are
able to specify properties for specific elements.
In the next lesson, we will take a closer look at two HTML-elements which is widely used in
connection with CSS: <span> and <div>.
Lesson 8: Grouping of elements (span
and div)
The elements <span> and <div> are used to group and structure a document and will often
be used together with the attributes class and id.
In this lesson, we will take a closer look at the use of <span> and <div> as exactly these two
HTML elements are of central importance with regards to CSS.


Grouping with <span>
Grouping with <div>
Grouping with <span>
The element <span> is what you could call a neutral element which does not add anything to
the document itself. But with CSS, <span> can be used to add visual features to specific
parts of text in your documents.
An example of this could be this Benjamin Franklin quotation:
<p>Early to bed and early to rise
makes a man healthy, wealthy and wise.</p>
Lets us say we want what Mr. Franklin sees as the benefits of not sleeping your day away
emphasized in red. For that purpose, we can mark the benefits with <span>. Each span is
then added a class, which we can define in our style sheet:
<p>Early to bed and early to rise
makes a man <span class="benefit">healthy</span>,
<span class="benefit">wealthy</span>
and <span class="benefit">wise</span>.</p>
The CSS belonging to it:
span.benefit {
color:red;
}

Show example
Of course you may also use id to add style to the <span>-elements. Just as long as you
remember, that you'll have to apply a unique id to each of the three <span>-elements, as
you learned in the previous lesson.
Grouping with <div>
Whereas <span> is used within a block-level element as seen in the previous
example, <div> is used to group one or more block-level elements.
Aside from this difference, the grouping with <div> works in more or less the same way. Let
us take a look at an example with two lists of U.S. presidents divided into their political
affiliations:
<div id="democrats">
<ul>
<li>Franklin D. Roosevelt</li>
<li>Harry S. Truman</li>
<li>John F. Kennedy</li>
<li>Lyndon B. Johnson</li>
<li>Jimmy Carter</li>
<li>Bill Clinton</li>
</ul>
</div>
<div id="republicans">
<ul>
<li>Dwight D. Eisenhower</li>
<li>Richard Nixon</li>
<li>Gerald Ford</li>
<li>Ronald Reagan</li>
<li>George Bush</li>
<li>George W. Bush</li>
</ul>
</div>
And in our style sheet, we can utilize the grouping in the exact same way as above:
#democrats {
background:blue;
}
#republicans {
background:red;
}

Show example
In the examples above, we have only used <div> and <span> on very simple things such as
text and background colors. Both elements have the potential to do much more advanced
things. However this will not be introduced in this lesson. We will look into these later in this
tutorial.
Summary
In lesson 7 and 8, you have learned about the selectors id and class and the
elements span and div.
You should now be able to group and identify, more or less, all parts of a document, which is
a big step in the direction of mastering CSS. In lesson 9 we will introduce you to the box
model.
Lesson 9: The box model
The box model in CSS describes the boxes which are being generated for HTML-elements.
The box model also contains detailed options regarding adjusting margin, border, padding
and content for each element. The diagram below shows how the box model is constructed:
The box model in CSS
The illustration above might seem pretty theoretical to look at, so let's try to use the model in
an actual case with a headline and some text. The HTML for our example is (from the
Universal Declaration of Human Rights):
<h1>Article 1:</h1>
<p>All human beings are born free
and equal in dignity and rights.
They are endowed with reason and conscience
and should act towards one another in a
spirit of brotherhood</p>
By adding some color and font-information the example could be presented as follows:
The example contains two elements: <h1> and <p>. The box model for the two elements can
be illustrated as follows:
Even though it may look a bit complicated, the illustration shows how each HTML-element is
surrounded by boxes. Boxes which we can adjust using CSS.
<% '
The properties which regulate the different boxes are: padding, margin and border. The
next two lessons deal with exactly these three properties:
'
'

Lesson 10: The box model - margin & padding
'

Lesson 11: The box model - border
'
'
When you have finished these two lessons, you will master the box model and be able to
layout your documents much finer and more precise than in the old fashion using tables in
HTML.
%>
Summary
In this lesson you have been introduced to the box model. In the following three lesson we
will take a closer look at how to create and control elements in the box model.
Lesson 10: Margin and padding
In the previous lesson you were introduced to the box model. In this lesson, we will look at
how you can change the presentation of elements by setting
the margin and padding properties.


Set the margin in an element
Set the padding in an element
Set the margin in an element
An element has four sides: right, left, top and bottom. The margin is the distance from each
side to the neighboring element (or the borders of the document). See also the diagram
in lesson 9 for an illustration.
As the first example, we will look at how you define margins for the document itself i.e. for
the element <body>. The illustration below shows how we want the margins in our pages to
be.
The CSS code for this would look as follow:
body {
margin-top: 100px;
margin-right: 40px;
margin-bottom: 10px;
margin-left: 70px;
}
Or you could choose a more elegant compilation:
body {
margin: 100px 40px 10px 70px;
}

Show example
You can set the margins in the same way on almost every element. For example, we can
choose to define margins for all of our text paragraphs marked with <p>:
body {
margin: 100px 40px 10px 70px;
}
p {
margin: 5px 50px 5px 50px;
}

Show example
Set padding in an element
Padding can also be understood as "filling". This makes sense as padding does not affect
the distance of the element to other elements but only defines the inner distance between
the border and the content of the element.
The usage of padding can be illustrated by looking at a simple example where all headlines
have background colors:
h1 {
background: yellow;
}
h2 {
background: orange;
}

Show example
By defining padding for the headlines, you change how much filling there will be around the
text in each headline:
h1 {
background: yellow;
padding: 20px 20px 20px 80px;
}
h2 {
background: orange;
padding-left:120px;
}

Show example
Summary
You are now on your way to master the box model in CSS. In the next lesson, we will take a
closer look at how to set borders in different colors and how to shape your elements.
Lesson 11: Borders
Borders can be used for many things, for example as a decorative element or to underline a
separation of two things. CSS gives you endless options when using borders in your pages.




border-width
border-color
border-style
border
The width of borders [border-width]
The width of borders is defined by the property border-width, which can obtain the values
thin, medium, and thick, or a numeric value, indicated in pixels. The figure below illustrates
the system:
The color of borders [border-color]
The property border-color defines which color the border has. The values are the normal
color-values for example "#123456", "rgb(123,123,123)" or "yellow" .
Types of borders [border-style]
There are different types of borders to choose from. Below are shown 8 different types of
borders as Internet Explorer 5.5 interprets them. All examples are shown with the color
"gold" and the thickness "thick" but can naturally be shown in other colors and thicknesses.
The values none or hidden can be used if you do not want any border.
Examples of defining borders
The three properties described above can be put together by each element and thereby
produce different borders. To illustrate this, we will take a look at a document where we
define different borders for <h1>, <h2>, <ul> and <p>. The result may not be that pretty but
it illustrates some of the many possibilities:
h1 {
border-width: thick;
border-style: dotted;
border-color: gold;
}
h2 {
border-width: 20px;
border-style: outset;
border-color: red;
}
p {
border-width: 1px;
border-style: dashed;
border-color: blue;
}
ul {
border-width: thin;
border-style: solid;
border-color: orange;
}

Show example
It is also possible to state special properties for top-, bottom-, right- or left borders. The
following example shows you how:
h1 {
border-top-width: thick;
border-top-style: solid;
border-top-color: red;
border-bottom-width: thick;
border-bottom-style: solid;
border-bottom-color: blue;
border-right-width: thick;
border-right-style: solid;
border-right-color: green;
border-left-width: thick;
border-left-style: solid;
border-left-color: orange;
}

Show example
Compilation [border]
As it is also the case for many other properties, you can compile many properties into one
using border. Let us take a look at an example:
p {
border-width: 1px;
border-style: solid;
border-color: blue;
}
Can be compiled into:
p {
border: 1px solid blue;
}
Summary
In this lesson you have learned about the endless options CSS gives you when using
borders in your pages.
In the next lesson, we will look at how you define the dimensions in the box model - height
and width.
Lesson 12: Height and width
Up until now, we have not cared much about the dimensions of the elements we have
worked with. In this lesson, we will take a look at how you easily can define the height and
width of an element.


width
height
Setting the width [width]
With the width-property, you can define a certain width of an element.
The simple example below provides us with a box wherein text can be typed:
div.box {
width: 200px;
border: 1px solid black;
background: orange;
}

Show example
Setting the height [height]
In the example above notice how the height of the box is set by the content of the box. You
can affect the height of an element with the property height. As an example let us try to
make the box in the example 500px high:
div.box {
height: 500px;
width: 200px;
border: 1px solid black;
background: orange;
}

Show example
Summary
Lesson 9, 10, 11 and 12 have given you an introduction to the box model in CSS. As you can
probably see, the box model gives you many new options. You might have been using tables
in HTML to create your layouts until now, but with CSS and the box model you should now
be able to achieve elegant layouts more precisely and in accordance with the
recommendations of W3C.
Lesson 13: Floating elements (floats)
An element can be floated to the right or to left by using the property float. That is to say
that the box with its contents either floats to the right or to the left in a document (or the
containing box) (see lesson 9 for a description of the Box model). The following figure
illustrates the principle:
If we for example would like to have a text wrapping around a picture, the result would be like
this:
How is it done?
The HTML code for the example above, look as follows:
<div id="picture">
<img src="bill.jpg" alt="Bill Gates">
</div>
<p>causas naturales et antecedentes,
idciro etiam nostrarum voluntatum...</p>
To get the picture floating to the left and the text to surround it, you only have to define the
width of the box which surrounds the picture and thereafter set the property float to left:
#picture {
float:left;
width: 100px;
}

Show example
Another example: columns
Floats can also be used for columns in a document. To create the columns, you simply have
to structure the desired columns in the HTML-code with<div> as follows:
<div id="column1">
<p>Haec disserens qua de re agatur
et in quo causa consistat non videt...</p>
</div>
<div id="column2">
<p>causas naturales et antecedentes,
idciro etiam nostrarum voluntatum...</p>
</div>
<div id="column3">
<p>nam nihil esset in nostra
potestate si res ita se haberet...</p>
</div>
Now the desired width of the columns is set to e.g. 33%, and then you simply float each
column to the left by defining the property float:
#column1 {
float:left;
width: 33%;
}
#column2 {
float:left;
width: 33%;
}
#column3 {
float:left;
width: 33%;
}

Show example
float can be set as either left, right or none.
The property clear
The clear property is used to control how the subsequent elements of floated elements in a
document shall behave.
By default, the subsequent elements are moved up to fill the available space which will be
freed when a box is floated to a side. Look at the example above wherein the text is
automatically moved up beside the picture of Bill Gates.
The property clear can assume the values left, right, both or none. The principle is,
if clear, for example, is set to both for a box, the top margin border of this box will always
be under the lower margin border for possible floating boxes coming from above.
<div id="picture">
<img src="bill.jpg" alt="Bill Gates">
</div>
<h1>Bill Gates</h1>
<p class="floatstop">causas naturales et antecedentes,
idciro etiam nostrarum voluntatum...</p>
To avoid the text from floating up next to the picture, we can add the following to our CSS:
#picture {
float:left;
width: 100px;
}
.floatstop {
clear:both;
}

Show example
Summary
Floats are useful in many situations and will often be used together with positioning. In
the next lesson we will take a closer look at how to position a box, either relative or absolute.
Lesson 14: Positioning of elements
With CSS positioning, you can place an element exactly where you want it on your page.
Together with floats (see lesson 13), positioning gives you many possibilities to create an
advanced and precise layout.
The following will be discussed in this lesson:



The principle behind CSS positioning
Absolute positioning
Relative positioning
The principle behind CSS positioning
Imagine a browser window as a system of coordinates:
The principle behind CSS positioning is that you can position any box anywhere in the
system of coordinates.
Let's say we want to position a headline. By using the box model (see lesson 9) the headline
will appear as follows:
If we want this headline positioned 100px from the top of the document and 200px from the
left of the document, we could type the following in our CSS:
h1 {
position:absolute;
top: 100px;
left: 200px;
}
The result will be as follows:
As you can see, positioning with CSS is a very precise technique to place elements. It is
much easier than trying to use tables, transparent images or anything else.
Absolute positioning
An element which is positioned absolute does not obtain any space in the document. This
means that it does not leave an empty space after being positioned.
To position an element absolutely, the position property is set as absolute. You can
subsequently use the properties left, right, top, and bottom to place the box.
As an example of absolute positioning, we choose to place 4 boxes in each corner of the
document:
#box1 {
position:absolute;
top: 50px;
left: 50px;
}
#box2 {
position:absolute;
top: 50px;
right: 50px;
}
#box3 {
position:absolute;
bottom: 50px;
right: 50px;
}
#box4 {
position:absolute;
bottom: 50px;
left: 50px;
}

Show example
Relative positioning
To position an element relatively, the property position is set as relative. The difference
between absolute and relative positioning is how the position is being calculated.
The position for an element which is relatively positioned is calculated from the original
position in the document. That means that you move the element to the right, to the left, up
or down. This way, the element still obtains a space in the document after it is positioned.
As an example of relative positioning, we can try to position three pictures relatively to their
original position on the page. Notice how the pictures leave empty spaces at their original
positions in the document:
#dog1 {
position:relative;
left: 350px;
bottom: 150px;
}
#dog2 {
position:relative;
left: 150px;
bottom: 500px;
}
#dog3 {
position:relative;
left: 50px;
bottom: 700px;
}

Show example
Summary
In the previous two lessons, you learned how to float and position elements. These two
methods give you many opportunities to construct your pages without having to use some of
the old-fashioned methods with tables and transparent images in HTML. Use CSS instead. It
is more precise, gives you more advantages, and it is also far easier to maintain.
Lesson 15: Layer on layer with z-index
(Layers)
CSS operates in three dimensions - height, width and depth. We have seen the first two
dimensions in previous lessons. In this lesson, we will learn how to let different elements
become layers. In short, this means the order of which the elements overlap one another.
For that purpose, you can assign each element a number (z-index). The system is that an
element with a higher number overlaps an element with a lower number.
Let us say we are playing poker and have a royal flush. Our hand can be presented in a way
where each card has got a z-index:
In this case, the numbers follow on another (1-5) but the same result can be obtained by
using 5 different numbers. The important thing is the chronological sequence of the numbers
(the order).
The code in the card example could look like this:
#ten_of_diamonds {
position: absolute;
left: 100px;
top: 100px;
z-index: 1;
}
#jack_of_diamonds {
position: absolute;
left: 115px;
top: 115px;
z-index: 2;
}
#queen_of_diamonds {
position: absolute;
left: 130px;
top: 130px;
z-index: 3;
}
#king_of_diamonds {
position: absolute;
left: 145px;
top: 145px;
z-index: 4;
}
#ace_of_diamonds {
position: absolute;
left: 160px;
top: 160px;
z-index: 5;
}

Show example
The method is relatively simple but the possibilities are several. You can place images on
text or text above text etc.
Summary
Layers can be used in many situations. For example, try to use z-index to create effects in
headlines instead of creating these as graphics. For one thing, it is faster to load text and for
another, it provides a potentially better ranking in search engines.
Lesson 16: Web-standards and
validation
W3C is the World Wide Web Consortium, which is an independent organization that
manages code standards on the web (e.g. HTML, CSS, XML and others). Microsoft, The
Mozilla Foundation and many others are a part of W3C and agree upon the future
developments of the standards.
If you have been working just a bit with web design, you probably know that there can be a
big differences in how a webpage is presented across different browsers. It can be very
frustrating and time-consuming to create a webpage which can be viewed in Mozilla, Internet
Explorer, Opera and all the rest of the existing browsers.
The idea of having standards is to agree upon a common denominator on how to use web
technologies. This means that by observing the standards, a webdeveloper has a certainty
that what he or she does will work in a more appropriate manner across different
platforms. We therefore recommend that you back up the work carried out by the W3C
and validate your CSS in order to observe the standard.
CSS validator
To make it easier to observe the CSS standard, W3C has made a so-called validator which
reads your stylesheet and returns a status listing errors and warnings, if your CSS does not
validate.
To make it easier for you to validate your stylesheet, you can do it directly from this
webpage. Simply replace the URL with the URL of your stylesheet below and click to
validate. You will then be informed by the W3C site if there are any errors found.
http://w w w .ht
Click to check stylesheet
If the validator does not find any errors; this picture will be shown, which you can put on your
website to illustrate that you are using validated coding:
The validator can also be found at this link: http://jigsaw.w3.org/css-validator/
Lesson 1: What is PHP
Whenever anyone is learning PHP, the most common questions that first come up are: What
is PHP? And how does it work?
It is precisely these questions we will look at in this lesson. It's a big help to understand such
basics related to PHP before you start developing you own PHP pages. Such basic
understanding will increase the speed of learning significantly.
So, let's get started!
What is PHP?
PHP was originally an acronym for Personal Home Pages, but is now a recursive acronym
for PHP: Hypertext Preprocessor.
PHP was originally developed by the Danish Greenlander Rasmus Lerdorf, and was
subsequently developed as open source. PHP is not a proper web standard - but an opensource technology. PHP is neither real programming language - but PHP lets you use socalled scripting in your documents.
To describe what a PHP page is, you could say that it is a file with the extension .php that
contains a combination of HTML tags and scripts that run on a web server.
How does PHP work?
The best way to explain how PHP works is by comparing it with standard HTML. Imagine you
type the address of an HTML document (e.g.http://www.mysite.com/page.htm) in the
address line of the browser. This way you request an HTML page. It could be illustrated like
this:
As you can see, the server simply sends an HTML file to the client. But if you instead
type http://www.mysite.com/page.php - and thus request anPHP page - the server is put
to work:
The server first reads the PHP file carefully to see if there are any tasks that need to be
executed. Only when the server has done what it is supposed to do, the result is then sent to
the client. It is important to understand that the client only sees the result of the server's
work, not the actual instructions.
This means that if you click "view source" on a PHP page, you do not see the PHP codes only basic HTML tags. Therefore, you cannot see how a PHP page is made by using "view
source". You have to learn PHP in other ways, for example, by reading this tutorial.
What you learn in this tutorial is to write commands to a server!
So, the first thing you need to get ahold of is... a server! But don't worry - you don't need to
buy a new computer. You just need to install some software on your computer that makes it
function as a server. Another option is to have a website on a hosted server that supports
PHP. Then you just need to be online while coding.
The next lesson is about how to get your computer to act as a server.
Lesson 2: Servers
PHP is a server-side technology. Therefore, you need to have a server to run PHP. But it
doesn't need to cost you anything to make this upgrade and there are several options for
doing so.
Since you ultimately only need to choose one option, this lesson is divided into three parts.
First comes a little introduction on the different options (just choose the one that suits you
best). When your server is up and running, we'll pick up with Lesson 3 to make your first
PHP page.
Option 1: Website on a hosted server
You can choose to have a website on a host that supports PHP.


Test whether your host supports PHP
If you don't already have a website on hosted server you can create a free account
on 000webhost.com which supports PHP.
Option 2: Install PHP on your computer
It's no walk in the park to install PHP on your computer. This option is only recommend for
experienced computer users, but it can obviously be done. Here are links to downloads and
installtion guides:



Windows Installation Guide
Mac Installation Guide
Linux Installation Guide
Option 3: XAMPP
XAMPP is a program that makes it easy and possible for us ordinary folks to run the PHP
directly on our computer without having to install PHP on our own.

Learn how to install XAMPP
Lesson 3: Your first PHP page
From lesson 1 and 2, you now know a little about what PHP is, and you've installed (or have
access to) a server. Now we are ready to begin making our first PHP page. We keep it
simple and easy, but after you have gone through this lesson, you will understand much
more about what PHP is and what you can do with it.
Basically, a PHP file is a text file with the extension .php which consists of:



Text
HTML tags
PHP Scripts
You already know what text and HTML tags are. So let's look a little more at PHP scripts.
PHP Scripts
PHP Documentation Group has issued detailed
documentation for PHP. Throughout the
tutorial, there will be many links to the documentation. The goal is that you become
accustomed to looking up and finding answers to your questions. PHP is so extensive that
you can't to learn all facets in this tutorial. But PHP is not difficult! On the contrary, PHP is
often very similar to plain English.
Let's get started with your first PHP page.
Example: Hello World!
Start by making an ordinary HTML document, but name the file page.php and save it in the
root of the site:


If you use XAMPP (see lesson 2), the path for the root is "c:\xampp\htdocs\page.php"
on your computer (which is now a server). Read more abot saving PHP files in
XAMPP.
If you have a website on a host that supports PHP, you simply upload/ftp the file to
your web host.
The HTML code should look like this:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
</body>
</html>
As you probably remember from lesson 1, PHP is all about writing commands to a
server. So let's write a command to the server.
First, we need to tell the server when the PHP will start and end. In PHP you use the
tags <?php and ?> to mark the start and end for the PHP codes that the server must
execute (on most servers it will be suficient to use just <? as start tag, but <?php is the most
correct to use the first time PHP is used.)
Now try to add the following simple code snippet to your HTML code:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
echo "<h1>Hello World!</h1>";
?>
</body>
</html>
When we look at the PHP document in a browser, it should look like this:
But it gets interesting when you look at the HTML code in the browser (by selecting "view
source"):
The PHP codes are gone! As you may remember from lesson 1, it is only the server that can
see the PHP codes - the client (the browser) only sees the result!
Let's look at what happened. We asked the server to write <h1> Hello World!</h1>. In a
more technical language, one would say that we used the string function
echo to write a
specified string to the client where the semicolon ends the command. But do not worry! In
this tutorial, we try to keep the technical language at a minimum.
Our first example is obviously not particularly exciting. But just wait! From now on, it's only
going to be more and more interesting. Let's look at another example.
Example: Now!
Let's make the server write something else. We could, for example, ask it to write the current
date and time:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
echo date("r");
?>
</body>
</html>
That will look like this in the browser:
And the corresponding HTML code:
Now things are getting interesting, right?
We make the server write the date and time when the PHP page is displayed. Note that if
you refresh the page in the browser, a new time is written. The server writes the current date
and time each time the page is sent to a client.
It is also important to note that the HTML code contains only the date - not the PHP codes.
Therefore, the example is not affected by which browser is used. Actually, all functionalities
that are made with server-side technologies always work in all browsers!
And again, notice the semicolon after the code line. It is a separator and very important to
include - otherwise the script won't work.
In the example, we used
on the server.
date, which is a function that returns the current date and time
Let's try to extend the example by writing both a string and a function - separated by "." (a
period) - it's done like this:
<html>
<head>
<title>My first PHP document</title>
</head>
<body>
<?php
echo "<p>Current date and time: " . date("r") . "</p>";
?>
</body>
</html>
It will look like this in the browser:
And the corresponding HTML code:
In the next lesson, we will take a closer look at the
for date and time.
date function and the different formats
Lesson 4: Working with time and dates
In this lesson, we will try to look at the many different options for working with time and dates
in PHP. We went through some very simple examples in the previous lesson mostly to show
you what PHP is. In this lesson, we will take a closer look at the
date function.
Time and date functions
PHP provides a wide range of funtions in relation to time and date. In this lesson, we will look
at the most important of these functions:
date.
With different parameters, the
date function can return the current date / time in many
different formats. Some of the most useful parameters are:
date("y")
Returns the current year from a date - with today's date, it returns: 12
date("m")
Returns the current month from a date - with today's date, it returns: 07
date("n")
Returns the current month from a date without leading zeroes ( eg. "1" instead of
"01") - with today's date, it returns: 7
date("F")
Returns the current month name from a date - with today's date, it returns: July
date("d")
Returns the current day of the month from a date - with today's date, it returns: 28
date("l")
Returns the name of the current weekday from a date - with today's date, it
returns: Saturday
date("w")
Returns the current day of the week from a date - with today's date, it returns: 6
date("H")
Returns the current hour from a time - with the current time, it returns: 09
date("i")
Returns the current minute from a time - with the current time, it returns: 28
date("s")
Returns the current second from a time - with the current time, it returns: 05
This example illustrates the use of the
date function:
<html>
<head>
<title>Time and date</title>
</head>
<body>
<?php
echo "<p>Today it's " . date("l") . "</p>";
?>
</body>
</html>
Show example
The time is 1343460485
And now hold on... because now it becomes a little nerdy! The function
time() returns the
current time as the number of seconds since January 1, 1970, 12:00 PM, GMT.
<html>
<head>
<title>time and date</title>
</head>
<body>
<?php
echo "<p>It's been exactly " . time() . " seconds since January
1, 1970, 12:00 PM, GMT </ p> ";
?>
</body>
</html>
Show example
Time expressed in the number of seconds since January 1, 1970, 12:00 PM GMT is a socalled "timestamp" (UNIX timestamp) and is quite useful when you work with dates/times in
the future or the past.
By default, the
date function uses the current timestamp (i.e. the current value of
time()). But with an extra parameter you can specify a different time stamp and thus work
with the future or the past. In the example below, we set the timestamp to 0 seconds from
January 1, 1970 12:00 PM, GMT. Thereby we can check what day of week January 1, 1970
was.
<html>
<head>
<title>time and date</title>
</head>
<body>
<?php
echo "<p>January 1, 1970 was a " . date("l",0) . "</p>";
?>
</body>
</html>
Show example
Unless you are a mathematical genius, it quickly becomes complicated to count the number
of seconds since January 1, 1970 to a specific time in the future or past. But here you can
get help from another nifty function:
mktime, which does the calculations for you.
The syntax for
mktime is (hour, minute, second, month, day, year). The example below
converts the time of the first step on the Moon (July 21, 1969, 02:56):
<html>
<head>
<title>time and date</title>
</head>
<body>
<?php
echo mktime (2,56,0,7,21,1969);
?>
</body>
</html>
Show example
Notice that it's returning a negative number as the date is earlier than January 1, 1970.
We can now put this together with the
historic day took place.
date function and find out which weekday this
<html>
<head>
<title>time and date</title>
</head>
<body>
<?php
echo date("l", mktime(2,56,0,7,21,1969));
?>
</body>
</html>
Show example
What can you use it for?
All this may seem a bit theoretical at this stage. After all, what on earth can you use a
function like
time() for? More importantly, when will you learn something you can actually
use on your pages?
The answer is that what you learn here are building blocks - the only limitations to what you
can build are your creativity and imagination! I would venture to say that you have already
learned more than you think. For example, do you think you can make a website with
different background images each day of the week and that works in all browsers?
Sure you can! Look at this example:
<html>
<head>
<title>time and date</title>
</head>
<body background="background_<?php echo date("w"); ?>.png">
</body>
</html>
Show example
The example above, with a dynamic background image, simply requires that you make
seven images and name them background_1.png, background_2.png, background_3.png,
etc.
If a user then enters your site on a Tuesday, the site will have background_2.png as
background, and the next day, background_3.png. Easy and simple!
In the next lesson, you will be introduced to new building blocks that can be used to make
loops and repetitions in your codes.
PHP is fun, don't you think?
Lesson 5: Loops
In PHP, it is possible to manage the execution of scripts with different control structures. In
this lesson, we will look at loops. Loops can be used to repeat parts of a script a specified
number of times or until a certain condition is met.
"while" loops
The syntax for a
while loop is:
while (condition) {
Statement
}
The syntax can almost be directly translated into English: do something while a condition is
met.
Let's look at a simple example:
<html>
<head>
<title>Loops</title>
</head>
<body>
<?php
$x = 1;
while ($x <= 50) {
echo "<p>This text is repeated 50 times</p>";
$x = $x + 1;
}
?>
</body>
</html>
Show example
In the example, a variable named "$x" is used. As you can see, variables in PHP always
start with a "$" character. It's easy to forget this at first, but it's absolutely necessary to
remember or else the script doesn't work.
Apart from that, the example is almost self-explanatory. First the variable $x is set to be
equal to 1. Then the loop asks the server to repeat the text while $x is less or equal to 50. In
each loop, the variable $x will be increased by 1.
"for" loops
Another way to make a loop is with
for on the form:
for (Initialization; Condition; Step) {
Statement
}
The statement is repeated as long as 'Initialization' + 'Step' meets the 'Condition'. If that
doesn't make sense, look at this example:
<html>
<head>
<title>Loops</title>
</head>
<body>
<?php
for ($x=0; $x<=50; $x=$x+5) {
echo '<p>variable $x is now = ' . $x . '</p>';
}
?>
</body>
</html>
Show example
In the example above, $x is growing with the value 5 in each loop. The loop will continue as
long as $x is below or equals 50. Also note how the value $x is used as part of the sentence.
Here is another example:
<html>
<head>
<title>Loops</title>
</head>
<body>
<?php
for ($x=1; $x<=6; $x=$x+1) {
echo "<h" . $x . ">Heading level " . $x . "</h" . $x . ">";
}
?>
</body>
</html>
Show example
Do you get it? First we set the value of $x to 1. Then in each loop, we write a heading at level
$x (h1, h2, h3, etc.) until $x is equal to six.
Loops within loops
In principle, there are no limitations on how loops can be used. For instance, you can easily
put loops inside loops and thereby create many repeats.
But be careful! PHP becomes slower the more complicated and extensive the scripts. For
instance, look at the next example where, with three loops, we can write over 16 million
colors!
In order not to make the page slow, we have drastically reduced the number by putting the
step to 30 and thereby limited the number of colors to 512.
<html>
<head>
<title>Loops </title>
</head>
<body>
<?php
for ($intRed=0; $intRed<=255; $intRed=$intRed+30) {
for ($intGreen=0; $intGreen<=255; $intGreen=$intGreen+30) {
for ($intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) {
$StrColor = "rgb(" . $intRed . "," . $intGreen . "," .
$intBlue . ")";
echo "<span style='color:" . $StrColor . "'>" .
$StrColor . "</span>";
}
}
}
?>
</body>
</html>
Show example
In this example, each of three primary colors (red, green and blue) can have a value
between 0 and 255. Any combination of the three colors creates a color on the form
rgb(255,255,255). The color code is used as color in a <span>.
Loops becomes more useful when you've learned a little more. When you understand the
principle in a loop, you can proceed to the next lesson, where we look at conditions.
Lesson 6: Conditions
Conditions are used to execute part of a script only if some predefined requirements
(conditions) are fulfilled. For example, a condition could be that a date must be after January
1, 2012 or that a variable is greater than 7.
If...
The first type of condition we will look at is
if, which has the following syntax:
if (condition) {
statement
}
Again, the syntax is very close to ordinary English: If a condition is met, then execute
something. Let's look at a simple example:
<html>
<head>
<title>Loops </title>
</head>
<body>
<?php
$x = 2;
if ($x > 1) {
echo "<p>variable $x is greater than 1 </p>";
}
?>
</body>
</html>
if ... else ...
The next type of condition will want to look at is
following form:
else , which may be presented in the
if (condition) {
statement
}
else {
statement
}
Again, the syntax is very close to ordinary English: if a condition is met execute something
or else execute something else.
In lesson 4, you learned how to find the number of a month. In the following example, we will
use the month number in an
if
else condition to find out what season it is:
<html>
<head>
<title>Conditions</title>
</head>
<body>
<?php
if (date ("m") == 3) {
echo "<p>Now it's spring!</p> ";
}
else {
echo "<p>I do not know what season it is!</p> ";
}
?>
</body>
</html>
Show example
As you can see, this condition is not a particularly smart condition - it only works when it's
March!
However, there are plenty of ways to improve the condition and make it more precise. Below
are listed comparison operators that can be used in the condition:
== Equals
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
In addition, there are some logical operators:
&& And
|| Or
! Not
The operators can be used to develop more precise conditions, so now we can expand the
above example to include all the spring months:
<html>
<head>
<title>Conditions</title>
</head>
<body>
<?php
if (date("m") >= 3 && date("m") <= 5) {
echo "<p> Now it's spring!</p> ";
}
else {
echo "<p> Now it's either winter, summer or autumn!</p> ";
}
?>
</body>
</html>
Let's take a closer look at the extended condition:
date("m") >= 3 && date("m") <= 5
The condition can be translated into:
If the month is greater than or equal to 3,
and the month is less than or equal to 5
Smart, eh? Operators play a significant role in many different parts of PHP.
But it still only works with March, April and May. All other months are not yet covered by the
condition. So let's try to develop the condition a little more.
if ... elseif ... else...
Using
elseif, we can expand the condition and make it work for all months:
<html>
<head>
<title>Conditions</title>
</head>
<body>
<?php
if (date("m") >= 3 && date("m") <= 5) {
echo "<p>Now it's spring!</p>";
}
elseif (date("m") >= 6 && date("m") <= 8) {
echo "<p>Now it's summer!</p>";
}
elseif (date("m") >= 9 && date("m") <= 11) {
echo "<p>Now it's autumn!</p>";
}
else {
echo "<p>Now is winter!</p>";
}
?>
</body>
</html>
Show example
To write conditions is all about thinking logically and being methodical. The example above is
pretty straightforward, but conditions can get very complex.
switch ... case
Another way of writing conditions is to use the
switch (expression) {
case 1:
statement
break;
case 2:
statement
break;
default:
switch method:
statement
break;
}
This method is based on an expression and then lists different "answers" or "values" with
related statements. The easiest way to explain the method is to show an example.
As you may remember from lesson 4, the function
date("w") returns the current weekday.
This can be used in an example where we write the name of the day (instead of a number):
<html>
<head>
<title>Conditions</title>
</head>
<body>
<?php
switch(date("w")) {
case 1:
echo "Now
break;
case 2:
echo "Now
break;
case 3:
echo "Now
break;
case 4:
echo "Now
break;
case 5:
echo "Now
break;
case 6:
echo "Now
break;
default:
echo "Now
break;
}
?>
</body>
</html>
Show example
it's Monday";
it's Tuesday";
it's Wednesday";
it's Thursday";
it's Friday";
it's Saturday";
it's Sunday";
Often
switch can be a good alternative to
if
else conditions. What you should use in
a given situation depends on which method you find easiest and most logical. Making your
scripts logical and clear can be a great challenge.
In the next lesson, we will look at how you can add comments to your scripts to explain how
they work. Good comments can be crucial if you or somebody else has to make changes in
your codes at a later stage.
Lesson 7: Comment your scripts
As you may have noticed, PHP scripts can easily look confusing. In this lesson, we cover
why comments are important and how to insert them into your scripts.
Why is it important to comment your scripts?
When you are coding, you are writing commands to a server/computer and need to use a
highly formal language that may not clearly reflect your thoughts when making the script.
Therefore, it can be difficult for others (or yourself) to understand how the script is structured,
and thus hard to identify and correct errors in the script.
Comments can be used to write short explanatory text in the script. The server completely
ignores the comments, and the comments do not affect the actual functionality of the script.
In the business world, it is often a requirement that scripts and programming are commented,
otherwise it would be too risky for a company to take over a system in which it would be too
difficult to find and correct errors.
How do you insert comments?
It is quite easy to insert a comment. You simply start the comment with a double slash: "//".
Take a look at this example from lesson 5, now with comments:
<html>
<head>
<title>Loops</title>
</head>
<body>
<?php
// Here we write color codes using three loops
// Red can be between 0 and 255
for ($intRed=0; $intRed<=255; $intRed=$intRed+30) {
// Green can be between 0 and 255
for ($intGreen=0; $ intGreen<=255; $intGreen=$intGreen+30) {
// Blue can be between 0 and 255
for ($ intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) {
// The color code is made on the form rgb(red,green,blue)
$strColor = "rgb(" . $intRed . "," . $intGreen . "," .
$intBlue . ")"
// Now we write the color code to the client
echo "<span style='color:" . $strColor . "'> " .
$strColor . " </span>";
// Closes the loops
}
}
}
?>
For the sake of the example, we have included many extra comments, so it should be clear
that you are far better off debugging a script with comments than without.
Therefore, remember to comment your scripts!
Lesson 8: Arrays
In this lesson, we will look at what an array is, how it is used, and what it can do.
Understanding arrays can be a little difficult in the beginning. But give it a try anyway... we've
tried to make it as easy as possible.
What is an array?
An array is a set of indexed elements where each has its own, unique identification number.
Sound confusing? It's actually not that complicated.
Imagine a list of words separated by commas. It is called a comma-separated list, and it
could, for example, look like this:
apples, pears, bananas, oranges, lemons
Then try to imagine dividing the list at each comma. Next, give each section a unique
identification number like this:
What you see is an array. We can, for example, name the array "fruits". The idea is that we
can access the array with a number and get a value back, like this:
fruits(0) = apples
fruits(1) = pears
fruits(2) = bananas
fruits(3) = oranges
fruits(4) = lemons
This is the idea behind arrays. Let us try to use it in practice.
How do you use an array?
We will continue with the fruit example. Step by step, we will make it work as a real array.
First, we set a variable equal to the list of fruits:
<?php
$fruitlist = "apples, pears, bananas, oranges, lemons";
?>
Next, we use the function
explode to split the list at each comma:
<?php
$fruitlist = "apples, pears, bananas, oranges, lemons";
$arrFruits = explode(",", $fruitlist);
?>
Voila! "$arrFruits" is now an array!
Notice that we called the function
explode with two arguments:
1. the list that should be split
2. and the delimiter - i.e., the character used to split (in this case a comma) - in
quotation marks: ",".
Here we use a comma as a delimiter, but you can use any character or word as a delimiter.
Let us try to comment the script and put it into a PHP page:
<html>
<head>
<title>Array</title>
</head>
<body>
<?php
// Comma separated list
$fruitlist = "apples, pears, bananas, oranges, lemons";
// Create an array by splitting the list (with comma as
delimiter)
$arrFruits = explode(",", $fruitlist);
// Write the values from our array
echo "<p>The list of fruits:</p>";
echo
echo
echo
echo
echo
echo
echo
"<ul>";
"<li>" .
"<li>" .
"<li>" .
"<li>" .
"<li>" .
"</ul>";
$arrFruits[0]
$arrFruits[1]
$arrFruits[2]
$arrFruits[3]
$arrFruits[4]
.
.
.
.
.
"</li>";
"</li>";
"</li>";
"</li>";
"</li>";
?>
</body>
</html>
Show example
This example is very simple, and it might be a bit difficult to see the advantage of using an
array for this particular task. But just wait... arrays can be used for many very useful things.
Loop through an array
Back in lesson 5 you learned about loops. Now we will look at how you can loop through an
array.
When you know how many elements an array contains, it is not a problem defining the loop.
You simply start with 0 and let the loop continue to the number of items available. In the
example with the fruits, you would loop through the array like this:
<html>
<head>
<title>Array</title>
</head>
<body>
<?php
// Comma separated list
$fruitlist = "apples, pears, bananas, oranges, lemons";
// Create an array by splitting the list (with a comma as
delimiter)
$arrFruits = explode (",", $fruitlist);
echo "<p>The list of fruits:</p>";
echo "<ul>";
// Loop through the array $arrFruits
for ($x=0; $x<=4; $x++) {
echo "<li>" . $arrFruits[$x] . "</li>";
}
echo "</ul>";
?>
</body>
</html>
Show example
As you can see, the variable $x (which increases from 0 to 4 in the loop) was used to call the
array.
How to find the size of an array
But what if we add another fruit to the list? Then our array will contain one element more which will get the identification number 5. Do you see the problem? Then we need to change
the loop, so it runs from 0 to 5, or else not all of the elements will be included.
Wouldn't it be nice if we automatically could find out how many elements an array contains?
That's exactly what we can do with the function
works regardless of the number of elements:
<?php
foreach ($arrFruits as $x) {
echo $x;
}
?>
foreach. Now we can make a loop that
This loop will work regardless of how many or few elements the array contains.
Another example
Below is another example of how you can use an array to write the name of the month:
<html>
<head>
<title>Array</title>
</head>
<body>
<?php
// Creates array with each month.
// Creates array with the months. Note the comma before January
- because there is no month with the number 0
$arrMonths =
array("","January","February","March","April","May","June","July","Augu
st","September","October","November","December");
// Call the array with the number of the month - write to the
client
echo $arrMonths[date("n")];
?>
</body>
</html>
Show example
Notice that we use the function
array.
array instead of the function
explode to create an
Ok. Enough about arrays! In the next lesson, you'll learn how to write your own functions.
Lesson 9: Functions
In previous lessons you have learned to use functions like
date() and
lesson, you will learn to create your own functions using
function.
array(). In this
What is a function?
A function process inputs and returns an output. It can be useful if, for example, you have a
wide range of data you have processed or if you have calculations or routines that must be
performed many times.
A function has the following syntax:
Function Name(list of parameters) {
Statement
}
This way, we can make a very simple function that can add the value 1 to a number. It could
look like this:
function AddOne($x) {
$x = $x + 1;
echo $x;
}
Our function is named AddOne and must be called with a number - e.g. 34....
echo AddOne(34);
... which (surprise!) will return 35.
The example above processes a number, but functions can work with text, dates or anything
else. You can also create functions that are called by many different parameters. In this
lesson you will see different examples of functions.
Example 1: Function with more parameters
As mentioned above, you can easily create a function that can be called with more
parameters. In the next example, we'll create a function that is called with three numbers and
then returns the value of the three numbers added together:
<html>
<head>
<title>Functions</title>
</head>
<body>
<?php
function AddAll($number1,$number2,$number3) {
$plus = $number1 + $number2 + $number3;
return $plus;
}
echo "123 + 654 + 9 equals " . AddAll(123,654,9);
?>
</body>
</html>
Show example
Ok. Now that was almost too simple! But the point was just to show you that a function can
be called with more parameters.
Example 2: English date and time
Let us try to make a slightly more complex function. A function that's called with a date and
time returns it in the format: Wednesday, 15 February, 2012, 10:00:00 AM
<html>
<head>
<title>Functions</title>
</head>
<body>
<?php
function EnglishDateTime($date) {
// Array with the English names of the days of the week
$arrDay =
array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Su
nday");
// Array with the English names of the months
$arrMonth =
array("","January","February","March","April","May","June","July","Augu
st","September","October","November","December");
// The date is constructed
$EnglishDateTime = $arrDay[(date("w",$date))] . ", " .
date("d",$date);
$EnglishDateTime = $EnglishDateTime . " " .
$arrMonth[date("n",$date)] . " " . date("Y",$date);
$EnglishDateTime = $EnglishDateTime . ", " . date("H",$date)
. ":" . date("i",$date);
return $EnglishDateTime;
}
// Test function
echo EnglishDateTime(time());
?>
</body>
</html>
Show example
Please note how '$arrMonth' and '$EnglishDateTime' are constructed over several lines. This
is done so that users with a low screen resolution can better see the example. The method
has no effect on the code itself.
The function above works on all web servers regardless of language. This means that you
can use such a function if your website, for example, is hosted on a French server, but you
want English dates.
At this stage, we will not go into more depth with functions, but now you know a little about
how functions work.
Lesson 10: Passing variables in a URL
When you work with PHP, you often need to pass variables from one page to another. This
lesson is about passing variables in a URL.
How does it work?
Maybe you have wondered why some URLs look something like this:
http://html.net/page.php?id=1254
Why is there a question mark after the page name?
The answer is that the characters after the question mark are an HTTP query string. An
HTTP query string can contain both variables and their values. In the example above, the
HTTP query string contains a variable named "id", with the value "1254".
Here is another example:
http://html.net/page.php?name=Joe
Again, you have a variable ("name") with a value ("Joe").
How to get the variable with PHP?
Let's say you have a PHP page named people.php. Now you can call this page using the
following URL:
people.php?name=Joe
With PHP, you will be able to get the value of the variable 'name' like this:
$_GET["name"]
So, you use
$_GET to find the value of a named variable. Let's try it in an example:
<html>
<head>
<title>Query string</title>
</head>
<body>
<?php
// The value of the variable name is found
echo "<h1>Hello " . $ _GET["name"] . "</h1>";
?>
</body>
</html>
Show example (keep an eye on the URL)
When you look at the example above, try to replace the name "Joe" with your own name in
the URL and then call the document again! Quite nice, eh?
Several variables in the same URL
You are not limited to pass only one variable in a URL. By separating the variables with &,
multiple variables can be passed:
people.php?name=Joe&age=24
This URL contains two variables: name and age. In the same way as above, you can get the
variables like this:
$_GET["name"]
$_GET["age"]
Let's add the extra variable to the example:
<html>
<head>
<title>Query string </title>
</head>
<body>
<?php
// The value of the variable name is found
echo "<h1>Hello " . $_GET["name"] . "</h1>";
// The value of the variable age is found
echo "<h1>You are " . $_GET["age"] . " years old </h1>";
?>
</body>
</html>
Show example (keep an eye on the URL)
Now you have learned one way to pass values between pages by using the URL. In the next
lesson, we'll look at another method: forms.
Lesson 11: Passing variables with forms
Interactive websites require input from users. One of the most common ways to get input is
with forms.
In this lesson, we will look at how to build forms and process inputs on the server.
<form>
When you code a form, there are two particular important attributes: action and method.
action
Is used to enter the URL where the form is submitted. It would be the PHP file that
you want to handle the input.
method
Can either have the value "post" or "get", which are two different methods to pass
data. At this point, you don't need to know much about the difference, but with "get",
the data is sent through the URL, and with "post", the data is sent as a block of data
through standard input service (STDIN). In the last lesson, we looked at how data is
retrieved through the URL using
$_GET. In this lesson, we look at how data
submitted through a form using the method "post" is retrieved.
An HTML page with a form
The page that contains the form doesn't need to be a PHP file (but it can be). It need not
even be on the same site as the file that will receive the data.
In our first example, we will look at a very simple form with one text field:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter your name</h1>
<form method="post" action="handler.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
The result in the browser is a form:
Now we come to the fun part: receiving and handling the data with PHP.
Requesting form data with PHP
When you need to request data submitted through a form (post method), you use
$_POST:
$_POST["fieldname"];
Which returns the value of a field in the form. Let us try to use it in an example.
First create a page with a form as above. Then make a PHP page named "handler.php"
(notice that this is the name of the page we wrote in the action attribute in our <form>).
The file "handler.php" shall have the following content:
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
echo "<h1>Hello " . $_POST["username"] . "</h1>";
?>
</body>
</html>
Show example
User input and conditions
In the next example, we will try to use user input to create conditions. First, we need a form:
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="handler.php">
<p>What is your name:</p>
<input type="text" name="username"></p>
<p>What is your favorite color:
<input type="radio" name="favoritecolor" value="r" /> Red
<input type="radio" name="favoritecolor" value="g" /> Green
<input type="radio" name="favoritecolor" value="b" /> Blue </p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Which will look like this in the browser:
Now we will use these inputs to create a page that automatically changes background color
according to what the user's favorite color is. We can do this by creating a condition
(see lesson 6) that uses the data the user has filled out in the form.
<?php
$strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";
switch ($_POST["favoritecolor"]) {
case "r":
$strBackgroundColor = "rgb(255,0,0)";
break;
case "g";
$strBackgroundColor = "rgb(0,255,0)";
break;
case "b":
$strBackgroundColor = "rgb(0,0,255)";
break;
default:
$strBackgroundColor = "rgb(255,255,255)";
break;
}
?>
<html>
<head>
<title>Form</title>
</head>
<body style="background: <? echo $strBackgroundColor; ?>;">
<? echo $strHeading; ?>
</body>
</html>
The background color will be white if the user has not chosen any favorite color in the form.
This is done by using default to specify what should happen if none of the above conditions
are met.
But what if the user does not fill out his name? Then it only says "Hello" in the title. We will
use an extra condition to change that.
<?php
$strUsername = $_POST["username"];
if ($strUsername != "") {
$strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";
}
else {
$strHeading = "<h1>Hello stranger!</h1> ";
}
switch ($_POST["favoritecolor"]) {
case "r":
$strBackgroundColor = "rgb(255,0,0)";
break;
case "g";
$strBackgroundColor = "rgb(0,255,0)";
break;
case "b":
$strBackgroundColor = "rgb(0,0,255)";
break;
default:
$strBackgroundColor = "rgb(255,255,255)";
break;
}
?>
<html>
<head>
<title>Form</title>
</head>
<body style="background: <? echo $strBackgroundColor; ?>;">
<? echo $strHeading; ?>
</body>
</html>
Show example.
In the example above, we use a condition to validate the information from the user. In this
case, it might not be so important if the user did not write his name. But as you code more
and more advanced stuff, it's vital that you take into account that the user may not always fill
out forms the way you had imagined.
Example: contact form
With your new knowledge of PHP and forms, you are able to create a contact form using the
function
mail, which has the following syntax:
mail(to, subject, message);
First, we need a simple HTML form:
<html>
<head>
<title>Contact form</title>
</head>
<body>
<h1>Contact form</h1>
<form method="post" action="handler.php">
<p>Subject:<br /><input type="text" name="subject" /></p>
<p>Message:<br /><textarea name="message"></textarea></p>
<input type="submit">
</form>
</body>
</html>
Next we need a PHP script to send the users input:
<html>
<head>
<title>Functions</title>
</head>
<body>
<?php
// Recipient (change to your e-mail address)
$strEmail = "name@mydomain.com";
// Get user inputs
$strSubject = $_POST["subject"];
$strMessage = $_POST["message"];
mail($strEmail,$strSubject,$strMessage);
echo "Mail Sent.";
?>
</body>
</html>
Please note that the example will only work if you have access to a mail server. By default,
this is not the case in XAMPP and most free hosts. Also, some hosts may require that you
include a from header, which is done with an extra parameter:
mail("you@yourdomain.com", "Test", "This is a test mail", "From:
me@mydomain.com");
Lesson 12: Sessions
When you visit a website, you do a number of different things. You click from one page to
another. Perhaps you also fill out a form or purchase a product.
As a web developer, such information is of great importance to developing successful web
solutions.
Suppose, for example, that you want to make a site where some pages are protected with
login and password. To make this protection effective, the password-protected pages should
have access to information on whether the user has logged in at an earlier time. You must, in
other words, be able to "remember" what the user did earlier.
This is exactly what this lesson is about - how you can use sessions in PHP to store and
retrieve information during a user's visit to your site.
Session
PHP
session allows you to manage information about a user's session. You can write
smart applications that can identify and gather information about users.
A session can begin in different ways. We will not go into technical details here but focus on
the case where a session starts by a value being stored. A session ends/dies if the user
hasn't requested any pages within in a certain timeframe (by the standard 20 minutes). Of
course, you can also always end/kill a session in your script.
Let us say that 50 people are clicking around on the same site, e.g. a web shop, at the same
time. Information on what each of them have in their shopping cart would best be stored in a
session. In order to identify the individual users, the server uses a unique user ID that is
stored in a cookie. A cookie is a small text file stored on the user's computer (more about
cookies in lesson 13). Therefore, sessions often require support of cookies in the user's
browser.
An example of using sessions
When you requested this page, I stored the current time in a session. I did this so that I can
now show you an example of how a session works.
I named the item "StartTime" and stored it by adding the following line in my PHP script:
<?php
session_start();
$_SESSION["StartTime"] = date("r");
?>
Thereby, a session was started. As described above, each session is given an ID by the
server.
Your session has the following ID: 51674855c875ba3e9d63da05c261b648
At any time, I can call the "StartTime" from the session by writing:
<?php
session_start();
echo $_SESSION["StartTime"];
?>
Which would reveal that the page was requested at Sat, 28 Jul 2012 09:32:58 +0200
(according to the clock on this web server).
But what is interesting is that the information remains in the session, even after you have left
this page. The information will follow you until your session ends.
By default, a session lasts till the user closes the browser, then it dies automatically. But if
you want to stop a session, it can always be killed in this way:
<?php
session_destroy();
?>
Let us try to look at another example where sessions are used: a password solution.
Login system with sessions
In the following example, we will make a very simple login system. We will use many of the
things we have learned in previous lessons.
The first thing we need is a form where people can enter their username and password. It
could look like this:
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="post" action="login.php">
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="text" name="password" /></p>
<p><input type="submit" value="Let me in" /></p>
</form>
</body>
</html>
Then we create the file: login.php.
In this file, we check whether it is the correct username and password that has been entered.
If that is the case, we set a session that says that this user is logged in with the correct
username and password.
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
// Check if username and password are correct
if ($_POST["username"] == "php" && $_POST["password"] == "php")
{
// If correct, we set the session to YES
session_start();
$_SESSION["Login"] = "YES";
echo "<h1>You are now logged correctly in</h1>";
echo "<p><a href='document.php'>Link to protected
file</a><p/>";
}
else {
// If not correct, we set the session to NO
session_start();
$_SESSION["Login"] = "NO";
echo "<h1>You are NOT logged correctly in </h1>";
echo "<p><a href='document.php'>Link to protected
file</a></p>";
}
?>
</body>
</html>
In the protected files, we want to check whether the user is logged in properly. If this is not
the case, the user is sent back to the login form. This is how the protection is made:
<?php
// Start up your PHP Session
session_start();
// If the user is not logged in send him/her to the login form
if ($_SESSION["Login"] != "YES") {
header("Location: form.php");
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>This document is protected</h1>
<p>You can only see it if you are logged in.</p>
</body>
</html>
Click here to test the login system
Now you've been introduced to the Session object. In the next lesson, we are still working in
the same area but will take a closer look at cookies.
Lesson 13: Cookies
How and what kind of information websites are collecting from their users, and especially
how they use it, is a hot topic. Cookies are often mentioned as an example of how
information is collected and pose a threat to your privacy. But are there reasons to be
worried? Judge for yourself. Once you have gone through this lesson, you will know what
can be done with cookies.
What is a cookie?
A cookie is a small text file in which a website can store different information. Cookies are
saved on the user's hard drive and not on the server.
Most cookies expire (delete themselves) after a predetermined time period, which can range
from one minute to several years. But the user can also identify and delete any cookies on
his/her computer.
Most browsers, such as Microsoft Internet Explorer, Mozilla Firefox and Google Chrome, can
be configured to let the user choose whether or not he/she will accept a cookie. But then,
why not just say no to all cookies? It is possible. But many websites would not work as
intended without cookies, since cookies in many contexts are used to improve the usability
and functionality of the website.
How is information stored in a cookie?
It's easy to set or modify a cookie in PHP with
create a cookie and set the value.
setcookie. In the first example, we will
First, you need a name for the cookie. In this example we will use the name "HTMLTest".
Next, you set the value of the cookie like this:
<?php
// Setting the cookie
setcookie("HTMLTest", "This is a test cookie");
?>
By default, a cookie is kept untill the browser is closed, but it can easily be modified by
adding another parameter setting the expiry time:
<?php
// Setting the cookie
setcookie("Name", "C. Wing, time()+3600);
setcookie("Interests", "plane spotting", time()+3600);
?>
"Time()+3600" specified that the cookie should expire in 3600 seconds (60 minutes) from
now.
In the example above, we stored information about a user's name and interests. This
information can, for example, be useful to target the website specifically for the individual
visitor.
How do you retrieve the value of a cookie?
To get the value of the cookie,
$_COOKIE is used. For example, if we need the
information from the example above, we do it like this:
<?php
// Retrieve values from the cookie
$strName = $_COOKIE["Name"];
$strInterest = $_COOKIE["Interest"];
// Write to the client
echo "<p>" . strName . "</p>"
echo "<p>Your interest is . " strInterest . "</p>"
?>
Who can read the cookie?
By default, a cookie can be read at the same second-level domain (e.g. html.net) as it was
created. But by using the parameters domain and path, you can put further restrictions on
the cookie using the following syntax:
setcookie(name, value, expiration time, path, domain);
Let us look at an example:
<?php
// Setting the cookie: name, value, expiration time, path,
domain
setcookie("Name", "C. Wing", time()+60*60*24*365,
"/tutorials/php/", "www.html.net");
?>
In the example above, we set a cookie called "Name" with the value "C. Wing." The cookie
expires after one year (60 seconds * 60 minutes * 24 hours * 365 days) and can be read only
by sites located in the directory "/tutorials/php/" on the (sub-)domain "www.html.net".
Example of a cookie
We can try to save a sample cookie on your computer and then see how it looks.
The following code sets the cookie:
<?php
// Setting the cookie
setcookie("HTMLTest", "This text is in a cookie!",
time()+60*60*24, "/tutorials/php/", "www.html.net");
// Write the information to the client
echo $_COOKIE ["HTMLTest"];
?>
Show example
The cookie is being placed on your hard drive. Depending on what operating system you
use, your cookies may be saved in different places. Once you find them, they will probably
look like this:
As you can see, a cookie is a normal text file that can be open with Notepad, for example.
The contents of the cookie we have just created will probably look something like this:
HTMLTest TEXT=This+text+is+in+a+cookie% 21
www.html.net/tutorials/php 0 80973619229399148 4216577264 29399141 *
We will not go into detail with the different codes, but simply note that the user has full
control over cookies on his/her computer.
In this lesson, we have looked at what cookies can do but not what they can be used for. It's
a common concern that some sites use cookies for inappropriate activities. But in most
cases, cookies are used to make sites more user-friendly or relevant for the individual users.
If you choose to use cookies on your site, it might be a good idea to tell your users that your
site uses cookies. This can, for example, be communicated in a privacy policy or registration
process.
Lesson 14: Filesystem
With PHP, you can access the server's filesystem. This allows you to manipulate folders and
text files in PHP scripts.
For example, you can use PHP to read or write a text file. Or you can list all files in a
specified folder. There are many possibilities and PHP can save you lots of tedious work.
Here, we'll look at how you can use PHP to work with folders and files. The goal is to give
you a quick overview. In the next lessons, we will look more closely at the different
possibilities. We will not go through all the different possibilities. Again, see the
documentation for a complete listing.
filemtime
Returns the time for which the contents of a file was last edited (as UNIX timestamp see lesson 4)).
fileatime
Returns the time when a file was last accessed / opened (as a UNIX timestamp - see
lesson 4)).
filesize
Returns the size of a file in bytes.
Let us try to find the three properties of the file you are looking at now:
"/tutorials/php/lesson14.php"
<html>
<head>
<title>Filesystem</title>
</head>
<body>
<?php
// Find and write properties
echo "<h1>file: lesson14.php</h1>";
echo "<p>Was last edited: " . date("r",
filemtime("lesson14.php"));
echo "<p>Was last opened: " . date("r",
fileatime("lesson14.php"));
echo "<p>Size: " . filesize("lesson14.php") . " bytes";
?>
</body>
</html>
Show example
Folders
PHP also allows you to work with folders on the server. We will not go through all the
different possibilities - only show an example. Again, see the documentation for more
information.
opendir
Opens a specified folder.
readdir
Returns the filename of the next file in the open folder (cf.
closedir
Closes a specified folder.
The example below lists the contents of the folder "tutorials/php/".
<html>
<head>
<title>FileSystemObject</title>
</head>
<body>
opendir)
<?php
// Opens the folder
$folder = opendir("../../tutorials/php/");
// Loop trough all files in the folder
while (($entry = readdir($folder)) != "") {
echo $entry . "<br />";
}
// Close folder
$folder = closedir($folder);
?>
</body>
</html>
Show example
In the example the directory "../../tutorials/php/" is first opened. Then a loop is used to write
the name of the next file in the folder as long as there are more files. At the end, the folder is
closed.
In the next lessons, we will look at how to read from and write to a text file.
Lesson 15: Reading from a text file
In the previous lesson, we learned how to use PHP to access the server's filesystem. In this
lesson, we will use that information to read from an ordinary text file.
Text files can be extremely useful for storing various kinds of data. They are not quite as
flexible as real databases, but text files typically don't require as much memory. Moreover,
text files are a plain and simple format that works on most systems.
Open the text file
We use the
fopen function to open a text file. The syntax is as follows:
fopen(filename, mode)
filename
Name of the file to be opened.
mode
Mode can be set to "r" (reading), "w" (writing) or "a" (appending). In this lesson, we
will only read from a file and, therefore, use "r". In the next lesson, we will learn to
write and append text to a file.
The examples in this lesson use the text file unitednations.txt. This is a simple list of the
Programmes and Funds of the United Nations and their domains. You can either download
the file, or you can create your own file and test the examples with it.
First, let's try to open unitednations.txt:
<?php
// Open the text file
$f = fopen("unitednations.txt", "r");
// Close the text file
fclose($f);
?>
Example 1: Read a line from the text file
With the function
fgets, we can read a line from the text file. This method reads until the
first line break (but not including the line break).
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<?php
$f = fopen("unitednations.txt", "r");
// Read line from the text file and write the contents to the
client
echo fgets($f);
fclose($f);
?>
</body>
</html>
Show example
Example 2: Read all lines from the text file
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<?php
$f = fopen("unitednations.txt", "r");
// Read line by line until end of file
while(!feof($f)) {
echo fgets($f) . "<br />";
}
fclose($f);
?>
</body>
</html>
Show example
In the example, we loop through all the lines and use the function
feof (for end-of-file) to
check if you are at the end of the file. If this is not the case ("!" - see lesson 6), the line is
written.
Instead of looping through all the lines, we could have achieved the same result with the
function
fread. If you work with very large text files with thousands of lines, be aware
that the
fread function uses more resources than the
it makes very little difference.
fgets function. For smaller files,
Example 3: A simple link directory
As mentioned at the beginning of this lesson, text files can be excellent for data storage. This
is illustrated in the next example where we create a simple link directory from the contents of
the text file unitednations.txt.
The file is systematically written with the name of the program, then a comma, and then the
domain. As you can probably imagine, more information could easily be stored in this
comma-separated data file.
To get the information in each line, we use an array. See Lesson 8 for more information on
arrays.
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<?php
$f = fopen("unitednations.txt", "r");
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
$arrM = explode(",",fgets($f));
// Write links (get the data in the array)
echo "<li><a href='http://" . $arrM[1] . "'>" . $arrM[0].
"</a></li>";
}
fclose($f);
?>
</body>
</html>
Show example
Quite handy, right? In principle, you could now just expand the text file with hundreds of links
or perhaps expand your directory to also include address information.
In the next lesson, we will look at how to write to a text file.
Lesson 16: Writing to a text file
In the previous lesson, we learned to read from a text file. In this lesson, we will learn to write
to a text file.
The two methods are very similar, but there is one very important difference: You must have
write permissions to the file. This means that the file will have to be located in a folder where
you have the necessary permissions.
If you work locally on your own computer, you can set the permissions yourself: right-click on
the folder and choose "Properties". With most web hosts, you will normally have one folder
with write permissions. It's often called something like "cgi-bin", "log", "databases" or
something similar. If your web host permits it, you might also be able to set permissions
yourself. Usually you can simply right-click on a folder in your FTP client and choose
"properties" or "permissions" or something similar. The screendumps below shows how it's
done in FileZilla.
Read more on your web host's support pages.
Note that it is the text file that needs to be in the folder with write permissions - not the PHP
file.
Open the text file for writing
In the same way as when reading from a text file, the
fopen function is used for writing,
but this time we set the mode to "w" (writing) or "a" (appending).
The difference between writing and appending is where the 'cursor' is located - either at the
beginning or at the end of the text file.
The examples in this lesson use an empty text file called textfile.txt. But you can also create
your own text file if you like.
First, let us try to open the text file for writing:
<?php
// Open the text file
$f = fopen("textfile.txt", "w");
// Close the text file
fclose($f);
?>
Example 1: Write a line to the text file
To write a line, we must use the function
fwrite, like this:
<html>
<head>
<title>Writing to a text file</title>
</head>
<body>
<?php
// Open the text file
$f = fopen("textfile.txt", "w");
// Write text line
fwrite($f, "PHP is fun!");
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen("textfile.txt", "r");
echo fgets($f);
fclose($f);
?>
</body>
</html>
Show example
Since we opened the file for writing, the line is added at the top, and thus overwrites the
existing line. If we instead open the file appending, the line is added at the bottom of the text
file, which then will increase by one line each time it's written to.
Example 2: Adding a text block to a text file
Of course, it is also possible to add an entire text block, instead of just a single line, like this:
<html>
<head>
<title>Write to a text file</title>
</head>
<body>
<h1>Adding a text block to a text file:</h1>
<form action="myfile.php" method='post'>
<textarea name='textblock'></textarea>
<input type='submit' value='Add text'>
</form>
<?php
// Open the text file
$f = fopen("textfile.txt", "w");
// Write text
fwrite($f, $_POST["textblock"]);
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen("textfile.txt", "r");
// Read text
echo fgets($f);
fclose($f);
?>
</body>
</html>
Show example
In the next lessons, we look at another way of storing data: databases.
Lesson 17: Databases
A database is a collection of information / data that is organized so that it can easily be
retrieved, administrated and updated. Databases thereby enable the opportunity to create
dynamic websites with large amounts of information. For example, all data on members of
HTML.net and all posts in the forums are stored in databases.
A database usually consists of one or more tables. If you are used to working with
spreadsheets, or maybe have used databases before, tables will look familiar to you with
columns and rows:
There are many different databases: MySQL, MS Access, MS SQL Server, Oracle SQL
Server and many others. In this tutorial, we will use the MySQL database. MySQL is the
natural place to start when you want to use databases in PHP.
You need to have access to MySQL in order to go through this lesson and the next lessons:



If you have a hosted website with PHP, MySQL is probably already installed on the
server. Read more at your web host's support pages.
If you have installed PHP on your computer yourself and have the courage to install
MySQL as well, it can be downloaded in a free version (MySQL Community Edition)
at the MySQL's website.
If you use XAMPP (see lesson 2), MySQL is already installed and ready to use on
your computer. Just make sure MySQL is running in the Control Panel:
In the rest of this lesson, we will look more closely at how you connect to your database
server, before we learn to create databases and retrieve and update data in the following
sessions.
Connection to database server
First, you need to have access to the server where your MySQL database is located. This is
done with the function
mysql_connect with the following syntax:
mysql_connect(server, username, password)
Pretty straightforward: First, you write the location of the database (server), and then type in
the username and password.
If you have your own website, you should read about location of your MySQL server on your
host's support pages. Username and password will often be the same as those you use for
FTP access. Otherwise contact your provider.
Example of a MySQL connection on a hosted website:
mysql_connect("mysql.myhost.com", "user001", "sesame") or
die(mysql_error());
Example of a MySQL connection with XAMPP (default settings):
mysql_connect("localhost", "root", "") or die (mysql_error());
In the examples are added or die(mysql_error()) which, in brief, interrupts the script
and writes the error if the connection fails.
Now we have made a connection to a MySQL server, and can now start creating databases
and retrieve and insert data. This is exactly what we will look at in the next lessons.
By the way, keep in mind that it is good practice to close the database connection again
when you're finished retrieving or updating data. This is done with the function
mysql_close.
Lesson 18: Create databases and tables
In the previous lesson we looked at how to create a connection to a database server. Next
step is to create databases and tables.
We'll look at two ways to create databases and tables. First, how it is done in PHP, and then
how it's made with the more user-friendly tool PhpMyAdmin, which is standard on most web
hosts and in XAMPP.
If you have a hosted website with PHP and MySQL, a database has probably been created
for you already and you can just skip this part of the lesson and start creating tables. Again,
you should consult your host's support pages for more information.
Create a database and tables with PHP
The function
mysql_query are used to send a query to a MySQL database. The queries
are written in the language Structured QueryLanguage (SQL). SQL is the most widely used
language for database queries - not only for MySQL databases - and is very logical and easy
to learn. In this lesson and the next, you will learn the most important SQL queries.
When creating a database, the SQL query
following syntax:
CREATE DATABASE is used with the
CREATE DATABASE database name
Logical and easy, right!? Let's try to put it into a PHP script:
mysql_connect("mysql.myhost.com", "user", "sesame") or
die(mysql_error());
mysql_query("CREATE DATABASE mydatabase") or die(mysql_error());
mysql_close();
First, we connect to the MySQL server. Next, we create a database named "mydatabase".
And finally, we close the connection to the MySQL server again.
So far so good... but things become a little bit more complicated when we want create tables
in PHP. When creating tables, we use the SQL query
following syntax:
CREATE TABLE
(
column1_name
column2_name
column3_name
...
)
CREATE TABLE with the
table name
DATA_TYPE,
DATA_TYPE,
DATA_TYPE,
table_name and column_name are of course the name of the table and the columns,
respectively. DATA_TYPE are used to specify the data type to be inserted into the column.
The most commonly used data types are:
INT
For numbers without decimals
DECIMAL
For numbers with decimals
CHAR
Short text up to 255 characters
TEXT
For plain text up to 65,535 characters
LONGTEXT
For long passages of text up to 4,294,967,295 characters
Date
For dates in the format YYYY-MM-DD
Time
For time in the format HH:MM:SS
DATETIME
For date and time in the format YYYY-MM-DD HH:MM:SS
All in all, logical and relatively easy. Let's try to put it into an example:
mysql_connect("mysql.myhost.com", "user", "sesame") or
die(mysql_error());
mysql_select_db("people") or die(mysql_error());
mysql_query("CREATE TABLE MyTable (
id INT AUTO_INCREMENT,
FirstName CHAR,
LastName CHAR,
Phone INT,
BirthDate DATE
PRIMARY KEY(id)
)") Or die(mysql_error());
mysql_close ();
In the example, we start by connecting to the MySQL server. Next we use the function
mysql_select_db to select the database "people". Then we create the table "persons" with 5
columns.
Note that at the "id" column, we first use
INT to specify that the column contains numbers
and then add
AUTO_INCREMENT to automatically increase the number and ensure a
unique ID for each row.
At the end, we use
PRIMARY KEY to set the "id" column as the primary key. The primary
key uniquely identifies each record (/row) in the table, which becomes very useful later when
we update the database.
Create database and tables with phpMyAdmin
It can be useful to be able to create databases and tables directly in PHP. But often, it will be
easier to use phpMyAdmin (or any other MySQL administration tool), which is standard on
most web hosts and XAMPP. The screendumps below shows how to create a database and
tables in phpMyAdmin.
Start by logging onto phpMyAdmin. Often, the address will be the same as your MySQL
server (eg. "http://mysql.myhost.com") and with the same username and password. In
XAMPP, the address is http://localhost/phpmyadmin/.
When you are logged on, simply type a name for the database and press the button
"Create":
At some hosts, it's possible the have already created a database, and you may not have the
rights to create more. If that is the case, you obviously just use the assigned database.
To create a table, click on the tab "Databases" and choose a database by clicking on it:
Then there will be a box titled "Create new table in database", where you type the name of
the table and the number of columns and press the button "Go":
Then you can name the columns and set the data type, etc., as in the SQL example above.
An error occurs if you, for example, attempt to insert text or numbers in a date field.
Therefore, try to set the data types as precisely as possible.
Below is the most common data types listed:
Setting
Data Type
CHAR
Text or combinations of text and numbers. Can also be used for numbers that are not used Up
in calculations (e.g., phone numbers).
defi
TEXT
Longer pieces of text, or combinations of text and numbers.
Up
INT
Numerical data for mathematical calculations.
4 by
DATE
Dates in the format YYYY-MM-DD
3 by
TIME
Time in the format hh:mm:ss
3 by
DATETIME Date and time in the format YYYY-MM-DD hh:mm:ss
8 by
SQL statements with quotes or backslash
If you try to insert text that contains the characters single quote ('), double quote (") or
backslash (\), the record may not be inserted into the database. The solution is to add
backslashes before characters that need to be quoted in database queries.
This can be done with the function
addslashes this way:
<?php
$strText = "Is your name O'Reilly?";
$strText = addslashes($strText);
?>
All single quotes ('), double quotes (") and backslashs (\) will then get an extra backslash
before the character. This would only be to get the data into the database, the extra \ will not
be inserted. Please note that PHP runs
addslashes on all $_GET, $_POST, and
$_COOKIE data by default. Therefore do not use
addslashes on strings that have already
been escaped.
In the next lesson you will learn to retrieve data from your database. But first, try to insert
some more people in your database (as shown in the example above with Gus Goose).
Lesson 20: Get data from database
Now it's time to retrieve data from our database to our PHP pages.
This is really one of the most important lessons in this tutorial. Once you have read and
understood this lesson, you will realize why database-driven web solutions are so powerful,
and your views on web development will be expanded dramatically.
SQL queries
To retrieve data from a database, you use queries. An example of a query could be: "get all
data from the table 'people' sorted alphabetically" or "get names from the table 'people'".
Again, the language Structured Query Language (SQL) is used to communicate with the
database. Try looking at this simple example:
Get all data from the table 'people'
Will be written like this in SQL:
SELECT * FROM people
The syntax is pretty self-explanatory. Just read on and see how SQL statements are used in
the examples below.
Example 1: Retrieve data from a table
This example uses the database and table from lesson 19 and lesson 18. Therefore, it is
important that you read these lessons first.
The example shows how data in the table "people" is retrieved with an SQL query.
The SQL query returns a result in the form of a series of records. These records are stored
in a so-called recordset. A recordset can be described as a kind of table in the server's
memory, containing rows of data (records), and each record is subdivided into individual
fields (or columns).
A recordset can be compared to a table where each record could be compared to a row in
the table. In PHP, we can run through a recordset with a loop and the function
mysql_fetch_array, which returns each row as an array.
The code below shows how to use
mysql_fetch_array to loop through a recordset:
<html>
<head>
<title>Retrieve data from database </title>
</head>
<body>
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM people";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using
mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in
the array $row)
echo $row['FirstName'] . "<br />";
}
// Close the database connection
mysql_close();
?>
</body>
</html>
Show example
Notice that for every record how we get the content of the column "FirstName" by typing
$row['FirstName']. Similarly, we can get the content of the column "Phone" by writing
$row['Phone'], for example.
The order of the recordset is exactly the same as in the table in the database. But in the next
example, it will be shown how to sort recordset.
Example 2: Sort the data alphabetically,
chronologically or numerically
Often it can be helpful if a list or table of data is presented alphabetically, chronologically or
numerically. Such sorting is very easy to do with SQL, where the syntax Order By
ColumnName is used to sort according to the column contents.
Look at the SQL statement from the example above:
strSQL = "SELECT * FROM people"
The records can, for example, be sorted alphabetically by the first name of the people this
way:
strSQL = "SELECT * FROM people ORDER BY FirstName"
Or chronologically by date of birth like this:
strSQL = "SELECT * FROM people ORDER BY BirthDate"
The sorting can be charged from ascending to descending by adding DESC:
strSQL = "SELECT * FROM people ORDER BY BirthDate DESC"
In the following example, the people are sorted by age:
<html>
<head>
<title>Retrieve data from database </title>
</head>
<body>
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM people ORDER BY BirthDate DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName and BirthDate
echo $row['FirstName'] . " " . $row['BirthDate'] . "<br />";
}
// Close the database connection
mysql_close();
?>
</body>
</html>
Show example
Try to change the SQL statement yourself and sort the records by first name, last name or
phone number.
Retrieve selected data
Until now, our SQL statement retrieves all rows from the table. But often you need to set
criteria in the SQL query for the data to be retrieved, for instance, if we only want the rows for
those who have a particular phone number or a certain last name.
Say, we only want to retrieve people from the database who have the phone number
"66554433". That could be done like this:
strSQL = "SELECT * FROM people WHERE Phone = '66554433 '"
There are six relational operators in SQL:
= Equals
< Less than
> Greater Than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
In addition, there are some logical operators:
AND
OR
NOT
See lesson 6 for more information on how to set up conditions.
In the next example, we use conditions to set up an address book.
Example 3: Address book
In this example, we will try to combine many of the things you have just learned. We will
make a list of the names from the database where each name is a link to further details
about the person.
For this, we need two files - list.php and person.php - with the following code:
The code of list.php
<html>
<head>
<title>Retrieve data from the database</title>
</head>
<body>
<ul>
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM people ORDER BY FirstName DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Name of the person
$strName = $row['FirstName'] . " " . $row['LastName'];
// Create a link to person.php with the id-value in the URL
$strLink = "<a href = 'person.php?id = " . $row['id'] . "'>"
. $strNavn . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
// Close the database connection
mysql_close();
?>
</ul>
</body>
</html>
The code for person.php
<html>
<head>
<title>Retrieve data from database</title>
</head>
<body>
<dl>
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// Get data from the database depending on the value of the id
in the URL
$strSQL = "SELECT * FROM people WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo "<dt>Name:</dt><dd>" . $row["FirstName"] . " " .
$row["LastName"] . "</dd>";
echo "<dt>Phone:</dt><dd>" . $row["Phone"] . "</dd>";
echo "<dt>Birthdate:</dt><dd>" . $row["BirthDate"] .
"</dd>";
}
// Close the database connection
mysql_close();
?>
</dl>
<p><a href="list.php">Return to the list</a></p>
</body>
</html>
Show example
The address book example is rather simple, but it shows the potential of working with PHP
and databases.
Imagine that the database had contained 10,000 products with detailed descriptions. By
making a few changes in the above files, you could easily create a product catalogue with
more than 10,000 pages with only one database and two PHP files.
Welcome to a world with extensive websites that are easy to develop and maintain! Once
you've learned to work with databases, your web solutions will never be the same again.
Lesson 21: Delete data from database
In the two previous lessons, you have learned to insert and retrieve data from a database. In
this lesson, we'll look at how to delete records in the database, which is considerably easier
than inserting data.
Delete data using SQL
The syntax for an SQL statement that deletes records is:
DELETE FROM TableName WHERE condition
Example: Delete a record
When deleting a record, you can use the unique AutoNumber field in the database. In our
database, it is the column named id. Using this unique identifier ensures that you only delete
one record. In the next example, we delete the record where id has the value 24:
<html>
<head>
<title>Delete data in the database</title>
</head>
<body>
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// The SQL statement that deletes the record
$strSQL = "DELETE FROM people WHERE id = 24";
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
<h1>Record is deleted!</h1>
</body>
</html>
Remember that there is no "Recycle Bin" when working with databases and PHP. Once you
have deleted a record, it is gone and cannot be restored.
Lesson 22: Update data in a database
In previous lessons, you have learned to insert, retrieve and delete data from a database. In
this lesson, we will look at how to update a database, i.e., edit the values of existing fields in
the table.
Update data with SQL
The syntax for an SQL statement that updates the fields in a table is:
UPDATE TableName SET TableColumn='value' WHERE condition
It is also possible to update multiple cells at once using the same SQL statement:
UPDATE TableName SET TableColumn1='value1',
TableColumn2='value2' WHERE condition
With the knowledge you now have from the lessons 19, 20 and 21, it should be quite easy to
understand how the above syntax is used in practice. But we will of course look at an
example.
Example: Update cells in the table "people"
The code below updates Donald Duck's first name to D. and changes the phone number
to 44444444. The other information (last name and birthdate) are not changed. You can try
to change the other people's data by writing your own SQL statements.
<html>
<head>
<title>Update data in database</title>
</head>
<body>
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// The SQL statement is built
$strSQL = "Update people set ";
$strSQL = $strSQL . "FirstName= 'D.', ";
$strSQL = $strSQL . "Phone= '44444444' ";
$strSQL = $strSQL . "Where id = 22";
// The SQL statement is executed
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
<h1>The database is updated!</h1>
</body>
</html>
This example completes the lessons on databases. You have learned to insert, retrieve,
delete and update a database with PHP. Thus, you are actually now able to make very
advanced and dynamic web solutions, where the users can maintain and update a database
using forms.
If you want to see a sophisticated example of what can be made with PHP and databases,
try to join our community. It's free and takes approximately one minute to sign up. You can,
among other things, maintain your own profile using the form fields. Maybe you will get ideas
for your own site.
This also ends the tutorial. PHP gives you many possibilities for adding interactivity to your
web site. The only limit is your imagination - have fun!
Lesson 1: What is Active Server Pages
(ASP)
Whenever anyone is learning ASP, the most common questions that first come up are: What
is ASP? And how does it work?
It is precisely these questions we will look at in this lesson. It's a big help to understand such
basics related to ASP before you start developing you own ASP pages. Such basic
understanding will increase the speed of learning significantly. So, let's get started!
What is ASP?
As you can see by the title, ASP is an acronym for Active Server Pages.
ASP is developed by Microsoft. It is not really a standard ASP is neither a real programming
language nor is it a programming language, but it's a Microsoft technology that lets you use
so-called scripting in your documents.
To describe what an ASP page is, you could say that it is a file with the extension .asp that
contains a combination of HTML tags and scripts that run on a web server.
How does ASP work?
The best way to explain how ASP works is by comparing it with standard HTML. Imagine you
type the address of an HTML document (eg.http://www.mysite.com/page.htm) in the
address line of the browser. This way you request an HTML page. It could be illustrated like
this:
As you can see, the server simply sends an HTML file to the client. But if you instead
type http://www.mysite.com/page.asp - and thus request anASP page - the server is put
to work:
The server first reads the ASP file carefully to see if there are any tasks that need to be
executed. Only when the server has done what it is supposed to do, the result is then sent to
the client. It is important to understand that the client only sees the result of the server's
work - not the actual instructions.
This means that if you click "view source" on an ASP page, you do not see the ASP codes only basic HTML tags. Therefore, you can not see how an ASP page is made by using "view
source". You have to learn ASP in other ways, for example, by reading this tutorial.
What you learn in this tutorial is to write commands to a server!
So, the first thing you need to get hold of is... a server! But don't worry - you don't need to
buy a new computer. You just need to install some software on your computer that makes it
function as a server. Another option is to have a website on a hosted server that supports
ASP. Then you just need to be online while coding.
The next lesson is about how to get your computer to act as a server.
Lesson 3: Your first ASP page
From lesson 1 and 2, you now know a little about what ASP is, and you've installed (or have
access to) a server. Now we are ready to begin making our first ASP page. We keep it
simple and easy, but after you have gone through this lesson, you will understand much
more about what ASP is and what you can do with it.
Basically, an ASP file is a text file with the extension .asp which consists of:



Text
HTML tags
ASP Scripts
You already know what text and HTML tags are. So let's look a little more at ASP scripts.
ASP Scripts
ASP scripts can be written in different languages. The examples in this tutorial are written in
Microsoft Visual Basic Scripting Edition (VBScript), but could also be written in another
language - eg. JScript.
Microsoft has issued detailed
documentation for VBScript and
documentation for ASP
Objects. Throughout the tutorial, there will be many links to the documentation. The goal is
that you become accustomed to looking up and finding answers to your questions. VBScript
is so extensive that you can manage to learn all facets in this tutorial. But VBScipt is not
difficult! On the contrary, VBScript is often very similar to plain English.
Let's get started with your first ASP page.
Example: Hello World!
Start by making an ordinary HTML document. But name the file default.asp and place it in
the root of the site. On your computer (which is now a server), the path is
c:\inetpub\wwwroot\default.asp.
The HTML code should look like this:
<html>
<head>
<title>My first ASP page</title>
</head>
<body>
</body>
</html>
As you probably remember from lesson 1, ASP is all about writing commands to a
server. So let's write a command to the server.
First, we need to tell the server when the ASP will start and end. In ASP you use the
tags <% and %> to mark the start and end for the ASP codes that the server must execute.
Now try to add the following simple code snippet to your HTML code:
<html>
<head>
<title>My first ASP page</title>
</head>
<body>
<%
Response.Write "<h1>Hello World!</h1>"
%>
</body>
</html>
When we look at the ASP document in a browser, it should look like this:
But it gets interesting when you look at the HTML code in the browser (by selecting "view
source"):
The ASP codes are gone! As you may remember from lesson 1, it is only the server that can
see the ASP codes - the client (the browser) only sees the result!
Let's look at what happened. We asked the server to write <h1> Hello World!</h1>. In a
more technical language, one would say that we used the object Response and the
method
Write to write a specified string to the client. But do not worry! In this tutorial we
try to keep the technical language at a minimum.
Our first example is obviously not particularly exciting. But just wait! From now on, it's only
going to be more and more interesting. Let's look at another example.
Example: Now!
Let's make the server write something else. We could, for example, ask it to write the current
date and time:
<html>
<head>
<title>My first ASP page</title>
</head>
<body>
<%
Response.Write Now
%>
</body>
</html>
Will look like this in the browser:
And the corresponding HTML code:
Now things are getting interesting, right?
We make the server write the date and time when the ASP page is displayed. Note that if
you refresh the page in the browser, a new time is written. The server writes the current date
and time each time the page is sent to a client.
It is also important to note that the HTML code contains only the date - not the ASP codes.
Therefore, the example is not affected by which browser is used. Actually, all functionalities
that are made with server-side technologies always work in all browsers!
In the example, we used
on the server.
Now - which is a function that returns the current date and time
Let's try to extend the example by writing both a string and a function - separated by & - it's
done like this:
<html>
<head>
<title>My first ASP document</title>
</head>
<body>
<%
Response.Write "<p>Current time: " & Time & "</p>"
%>
</body>
</html>
Will look like this in the browser:
And the corresponding HTML code:
As you can see, the function
Time returns the current time. There are several functions
that relate to time and date. And that's exactly what we'll look at in the next lesson.
Lesson 4: Working with time and dates
In this lesson, we will try to look at the many different options for working with time and dates
in ASP. We went through two very simple functions in the previous lesson mostly to show
you what ASP is. In this lesson, we will look at some more functions and advanced
techniques.
Time and date functions
VBScript contains three important functions that return the current time and/or date on the
server:
Now
Returns the current date and time on the server.
Date
Returns the current date on the server.
Time
Returns the current time on the server.
This example illustrates the three functions:
<html>
<head>
<title>Time and date</title>
</head>
<body>
<%
Response.Write "<p>The function Now returns: " & Now & "</p>"
Response.Write "<p>The function Date returns: " & Date & "</p>"
Response.Write "<p>The function Time returns: " & Time & "</p>"
%>
</body>
</html>
Show example
Formatting time and dates
As you've probably noticed, the functions returns the date and time in some very "raw"
formats. But there are, of course, different ways to format both the date and time.
The option we want to cover in this lesson is based on the function
FormatDateTime. In a
later lesson, we will make our own function that can return exactly the format we want. But
first, let us look at the predefined options in VBScript.
FormatDateTime
Returns a time in specified format
FormatDateTime is a function exactly like the functions above but the function
FormatDateTime must be called with arguments. This means that you call the function in
the following form:
FormatDateTime(Date[, NamedFormat])
The NamedFormat argument may take the following values:




vbLongDate
vbShortDate
vbLongTime
vbShortTime
Let us look at an example that shows the different date and time formats. In the example
below, we call the function with
Now. But it can be called with any date and time (eg. "1402-2011 12:34:01")
<html>
<head>
<title>time and date</title>
</head>
<body>
<dl>
<dt>vbLongDate</dt>
<dd><% Response.Write FormatDateTime(Now, vbLongDate) %></dd>
<dt>vbShortDate </dt>
<dd><% Response.Write FormatDateTime(Now, vbShortDate) %></dd>
<dt>vbLongTime</dt>
<dd><% Response.Write FormatDateTime(Now, vbLongTime) %></dd>
<dt>vbShortTime</dt>
<dd><% Response.Write FormatDateTime(Now, vbShortTime) %></dd>
</dl>
<p>
<%
Response.Write "Today it is " & datetime format (Now,
vbLongDate)
Response.Write " and the time is " & Format datetime (Now,
vbShortTime)
%>
</p>
</body>
</html>
Show example
More functions related to date and time
There are a number of other functions that return parts of a date or time. They are all called
with a date or time as an argument. We will not go into depth with them all here, but just
show one example and briefly describe the others.
As an example, we look at the function
Minute which returns a number corresponding to
the minutes in the argument (the specified time). The function is called in the following form:
Minute(time)
Therefore, to find out what minute we're in right now, we write:
Minute(Time)
The function returns the number 42 - which is exactly the minutes in the time right
now: 09:42:48
The following functions relate similarly to dates or times. As an example they are called
with
Now (28-07-2012 09:42:48)
Year
Returns the current year from a date - with today's date, it returns: 2012
Month
Returns the current month from a date - with today's date, it returns: 7
Day
Returns the current day of the month from a date - with today's date, it returns: 28
Weekday
Returns the current day of the week from a date - with today's date, it returns: 6
NOTE: this function has to be called with the argument "the first day of the week"
(eg. Monday or Sunday) as well
- like this: Weekday(Now,vbMonday)
Hour
Returns the current hour from a time - with the current time, it returns: 9
Minute
Returns the current minute from a time - with the current time, it returns: 42
Second
Returns the current second from a time - with the current time, it returns: 48
What can you use it for?
All this may seem a bit theoretical at this stage. After all, what on earth can you use a
function like
Second for? More importantly, when will you learn something you can
actually use on your pages?
The answer is that what you learn here are building blocks - the only limitations to what you
can build are your creativity and imagination! I would venture to say that you have already
learned more than you think. For example, do you think you can make a website with
different background images each day of the week and that works in all browsers?
Sure you can! Look at this example:
<html>
<head>
<title>time and date</title>
</head>
<body background="background_<% =Weekday(Now,vbMonday) %> .png">
</body>
</html>
Show example
The example above, with a dynamic background image, simply requires that you make
seven images and name them background_1.png, background_2.png, background_3.png,
etc.
If a user then enters your site on a Tuesday the site will have background_2.png as
background, and the next day, background_3.png. Easy and simple!.
In the next lesson, you will be introduced to new building blocks that can be used to make
loops and repetitions in your codes.
ASP is fun, don't you think?
Lesson 5: Loops
In VBScript it is possible to manage the execution of scripts with different control structures.
In this lesson, we will look at loops. Loops can be used to repeat parts of a script a specified
number of times or until a certain condition is met.
For ... Next
The syntax for a
For ...Next loop is:
For Initializion To Expressions
Statement
Next
The statement is repeated 'expression' minus 'initialization' number of times. If it doesn't
make sense, look at this example:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
Dim t
For t = 1 to 50
Response.Write "<p>This text is repeated 50 times</p>"
Next
%>
</body>
</html>
Show example
In the example, a variable named "t" is used. As you can see, we start by writing Dim t, this
is called to declare a variable. You do not need to declare your variables, but it's considered
to be good code practice, and it makes your code more clear and easier to understand if
someone else at a later time has to read through your code.
Otherwise the example is almost self explanatory. The loop asks the server to repeat the text
while t is between 1 and 50. Each time the loop reaches "Next" the variable t will be
increased by 1.
It is possible to specify what value that the variable t should be increased by in each loop.
This is done with Step as shown in the following example:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
Dim t
For t = 1 to 50 Step 5
Response.Write "<p>variable t is now = " & t & "</p>"
Next
%>
</body>
</html>
Show example
In the example above, t is growing with the value 5 in each loop. Also note how the value t is
used as part of the sentence.
Do ... Loop
Another way to make a loop is with
Do ...Loop on the form:
Do {While | Until} condition
Statement
Loop
Or you can set the condition after Loop instead (no practical difference):
Do
Statement
Loop {While | Until} condition
Regardless of whether you use While or Until, the syntax is almost normal English:
Until
Execute until a condition is met.
While
Execute while a condition is met.
Let's look at a simple example:
<html>
<head>
<title>Loops </title>
</head>
<body>
<%
Dim t
t = 1
Do Until t = 6
Response.Write "<h" & t & ">Heading Levels</h" & t & ">"
t = t + 1
Loop
%>
</body>
</html>
Show example
Did you catch it? First we declare the variable t and set the value to 1. Then in each loop,
we write a heading at level t (h1, h2, h3, etc.) until t is equal to six.
Loops within loops
In principle, there are no limitations on how loops can be used. For instance, you can easily
put loops inside loops and thereby create many repeats.
But be careful! ASP becomes slower the more complicated and extensive the scripts. For
instance, look at the next example where, with three loops, we can write over 16 million
colors!
In order not to make the page slow, we have drastically reduced the number by putting the
step to 30 and thereby limited the number of colors to 512.
<html>
<head>
<title>Loops </title>
</head>
<body>
<%
Dim intRed, intGreen, intBlue, strColor
For intRed = 0 to 255 Step 30
For intGreen = 0 to 255 Step 30
For intBlue = 0 to 255 Step 30
strColor = "rgb (" & intRed & "" & intGreen & "" &
intBlue & ")"
Response.Write "<span style='color:" & strColor & "'>"
& strColor & " </span>"
Next
Next
Next
%>
</body>
</html>
Show example
In the example, each of three primary colors (red, green and blue) can have a value between
0 and 255. Any combination of the three colors creates a color on the form rgb(255,255,255).
The color code is used as color in a <span>.
Loops becomes more useful when you've learned a little more. When you understand the
principle in a loop, you can proceed to the next lesson, where we look at conditions.
Lesson 6: Conditions
Conditions are used to execute part of a script only if some predefined requirements
(conditions) are fulfilled. For example, a condition could be that a date must be after 1/1 2012
or that a variable is greater than 7.
If... Then ... Else
The first type of condition we will look at is the
following syntax:
If condition Then
statment
Else
statement
End If
If-Then-Else condition, which has the
Again, the syntax is very close to ordinary English: If a condition is met Then execute
something or Else execute something else.
In lesson 4, you learned how to find the number of a month. In the following example, we will
use the month number in
If-Then-Else condition to find out what season it is:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
If Month (Date) = 3 Then
Response.Write "<p>Now it's spring!</p>"
Else
Response.Write "<p>I do not know what season it is!</p>"
End If
%>
</body>
</html>
As you can see, it's not a particularly smart condition - it only works when it's March!
However, there are plenty of ways to improve the condition and make it more precise. Below
are listed comparison operators that can be used in the statement:
= Equals
< Less than
> Greater than
<= Less than or equal to
> = Greater than or equal to
<> Not equal to
In addition, there are some logical operators:
AND
OR
NOT
The operators can be used to develop more precise conditions, so now we can expand the
above example to include all the spring months:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
If Month(Date)> = 3 AND Month(Date) <= 5 Then
Response.Write "<p>Now it's spring!</p>"
Else
Response.Write "<p>Now it's either winter, summer or
autumn!</p>"
End If
%>
</body>
</html>
Let us take a closer look at the extended condition:
Month(Date)> = 3 AND Month(Date) <= 5
The condition can be translated into:
If the month is greater than or equal to 3, and the month is less than or equal to 5
Smart, eh? Operators play a significant role in many different parts of ASP.
But it still only works with March, April and May. All other months are not yet covered by the
condition. Let us try to develop the condition a little more.
If ... Then ... ElseIf ... Else
Using ElseIf, we can expand the condition and make it work for all months:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
If Month(Date)> = 3 AND Month(Date) <= 5 Then
Response.Write "<p>Now it's spring!</p>"
Elseif Month(Date)> = 6 AND Month(Date) <= 8 Then
Response.Write "<p>Now it's summer!</p>"
Elseif Month(Date)> = 9 AND Month(Date) <= 11 Then
Response.Write "<p>Now it's autumn!</p>"
Else
Response.Write "<p>Now is the winter!</p>"
End If
%>
</body>
</html>
To write conditions is all about thinking logically and being methodical. The example above is
pretty straightforward, but conditions can get very complex.
Select ... Case
Another way of writing conditions is to use the
Select Case method:
Select Case Expression
Case 1
statement
Case 2
statement
Case Else
statement
End Select
This method is based on an expression and then list different "answers" or "values" with
related statements. The easiest way to explain the method is to show an example.
As you may remember from lesson 4, the function
Weekday returns the current weekday.
This can be used in an example where we write the name of the day (instead of a number):
<html>
<head>
<title>Loops </title>
</head>
<body>
<%
Select Case Weekday(Now,vbMonday)
Case 1
Response.Write "Monday"
Case 2
Response.Write "Tuesday"
Case 3
Response.Write "Wednesday"
Case 4
Response.Write "Thursday"
Case 5
Response.Write "Friday"
Case 6
Response.Write "Saturday"
Case Else
Response.Write "Sunday"
End Select
%>
</body>
</html>
Often
Select Case can be a good alternative to
If-Then-Else. What you should use in a
given situation depends on which method you find easiest and most logical. Making your
scripts logical and clear can be a great challenge.
In the next lesson, we will look at how you can add comments to your scripts to explain how
they work. Good comments can be crucial if you or somebody else has to make changes in
your codes at a later stage.
Lesson 7: Comment your scripts
As you may have noticed, ASP scripts can easily look confusing. In this lesson, we cover
why comments are important and how to insert them into your scripts.
Why is it important to comment your scripts?
When you are coding, you are writing commands to a server/computer and need to use a
highly formal language which may not clearly reflect your thoughts when making the script.
Therefore, it can be difficult for others (or yourself) to understand how the script is structured,
and thus hard to identify and correct errors in the script.
Comments can be used to write short explanatory text in the script. The server completely
ignores the comments, and the comments do not affect the actual functionality of the script.
In the business world, it is often a requirement that scripts and programming are commented,
otherwise it would be too risky for a company to take over a system in which it would be too
difficult to find and correct errors.
How do you insert comments?
It is quite easy to insert a comment. You simply start the comment with an apostrophe: " ' ".
Take a look at this example from lesson 5, now with comments:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
' Here we write color codes using three loops
' Three variables for the colors (red, green and blue)
' and a variable for the color code:
Dim intRed, intGreen, intBlue, strColor
' Red can be between 0 and 255
For intRed = 0 to 255 Step 30
' Green can be between 0 and 255
For intGreen = 0 to 255 Step 30
' Blue can be between 0 and 255
For intBlue = 0 to 255 Step 30
' The color code is made on the form rgb(red,green,blue)
strColor = "rgb(" & intRed & "," & intGreen & "," &
intBlue & ")"
' Now we write the color code to the client
Response.Write "<span style='color: " & strColor & "'>" &
strColor & " </span>"
' Repeat loop
Next
Next
Next
%>
</body>
</html>
For the sake of the example, we have included many extra comments, so it should be clear
that you are far better off debugging a script with comments than without.
Therefore, remember to comment your scripts!
Lesson 7: Comment your scripts
As you may have noticed, ASP scripts can easily look confusing. In this lesson, we cover
why comments are important and how to insert them into your scripts.
Why is it important to comment your scripts?
When you are coding, you are writing commands to a server/computer and need to use a
highly formal language which may not clearly reflect your thoughts when making the script.
Therefore, it can be difficult for others (or yourself) to understand how the script is structured,
and thus hard to identify and correct errors in the script.
Comments can be used to write short explanatory text in the script. The server completely
ignores the comments, and the comments do not affect the actual functionality of the script.
In the business world, it is often a requirement that scripts and programming are commented,
otherwise it would be too risky for a company to take over a system in which it would be too
difficult to find and correct errors.
How do you insert comments?
It is quite easy to insert a comment. You simply start the comment with an apostrophe: " ' ".
Take a look at this example from lesson 5, now with comments:
<html>
<head>
<title>Loops</title>
</head>
<body>
<%
' Here we write color codes using three loops
' Three variables for the colors (red, green and blue)
' and a variable for the color code:
Dim intRed, intGreen, intBlue, strColor
' Red can be between 0 and 255
For intRed = 0 to 255 Step 30
' Green can be between 0 and 255
For intGreen = 0 to 255 Step 30
' Blue can be between 0 and 255
For intBlue = 0 to 255 Step 30
' The color code is made on the form rgb(red,green,blue)
strColor = "rgb(" & intRed & "," & intGreen & "," &
intBlue & ")"
' Now we write the color code to the client
Response.Write "<span style='color: " & strColor & "'>" &
strColor & " </span>"
' Repeat loop
Next
Next
Next
%>
</body>
</html>
For the sake of the example, we have included many extra comments, so it should be clear
that you are far better off debugging a script with comments than without.
Therefore, remember to comment your scripts!
Lesson 8: Arrays
In this lesson we will look at what an array is, how it is used, and what it can do.
Arrays can be a little difficult in the beginning. But give it a try anyway... we've tried to make it
as easy as possible.
What is an array?
An array is a set of indexed elements where each has its own, unique identification number.
Sound confusing? It's actually not that complicated.
Imagine a list of words separated by commas. It is called a comma separated list, and it
could, for example, look like this:
apples, pears, bananas, oranges, lemons
Then try to imagine dividing the list at each comma. Next, give each section a unique
identification number like this:
What you see is an array. We can, for example, name the array "fruits". The idea is that we
can access the array with a number and get a value back, like this:
fruits(0) = apples
fruits(1) = pears
fruits(2) = bananas
fruits(3) = oranges
fruits 4) = lemons
This is the idea behind arrays. Let us try to use it in practice.
How do you use an array?
We will continue with the fruit example. Step by step, we will make it work as a real array.
First, we set a variable equal to the list of fruits:
<%
Dim fruitlist
fruitlist = "apples, pears, bananas, oranges, lemons"
%>
Next, we use the function
Split to split the list at each comma:
<%
Dim fruitlist, arrFruits
fruitlist = "apples, pears, bananas, oranges, lemons"
arrFruits = Split(fruitlist,",")
%>
Voila! "arrFruits" is now an array!
Notice that we called the function
Split with two arguments:
1. the list that should be split
2. and the delimiter - i.e., the character used to split (in this case a comma) in quotation
marks: ",".
Here we use a comma as a delimiter, but you can use any character or word as delimiter.
Let us try to comment the script and put it into an ASP page:
<html>
<head>
<title>Array</title>
</head>
<body>
<%
' Two variables for the list and the array
Dim fruitlist, arrFruits
' Comma separated list
fruitlist = "apples, pears, bananas, oranges, lemons"
' Create an array by splitting the list (with comma as
delimiter)
arrFruits = Split(fruitlist,",")
' Write the values from our array
Response.Write "<p>The list of fruits:</p>
Response.Write "<ul>"
Response.Write "<li>" & arrFruits(0) & "</li>"
Response.Write "<li>" & arrFruits(1) & "</li>"
Response.Write "<li>" & arrFruits(2) & "</li>"
Response.Write "<li>" & arrFruits(3) & "</li>"
Response.Write "<li>" & arrFruits(4) & "</li>"
Response.Write "</ul>"
%>
</body>
</html>
Show example
This example is very simple, and it might be a difficult to see the advantage of using an array
for this particular task. But just wait... arrays can be used for many very useful things.
Loop through an array
Back in lesson 5 you learned about loops. Now we will look at how you can loop through an
array.
When you know how many elements an array contains, it is not a problem defining the loop.
You simply start with 0 and let the loop continue to the number of items available. In the
example with the fruits, you would loop through the array like this:
<html>
<head>
<title>Array</title>
</head>
<body>
<%
' Two variables for the list and the array
Dim fruitlist arrFruits
' Comma separated list
fruitlist = "apples, pears, bananas, oranges, lemons"
' Create an array by splitting the list (with comma as
delimiter)
arrFruits = Split(fruit list ,",")
Response.Write "<p>List of fruits:</p>
Response.Write "<ul>"
' Loop through the array arrFrugt
For t = 0 to 4
Response.Write "<li>" & arrFruits (t) & "</li>
Next
Response.Write "</ul>"
%>
</body>
</html>
Show example
As you can see, the variable t (which increase from 0 to 4 in the loop) was used to call the
array.
How to find the size of an array
But what if we add another fruit to the list? Then our array will contain an element more which will get the identification number 5. Do you see the problem? Then we need to change
the loop, so it runs from 0 to 5, or else not all of the elements will be included.
Wouldn't it be nice if we automatically could find out how many elements an array contains?
That is exactly what we can do with the functions
Ubound and
Lbound, which return
respectively the highest and lowest identification number in an array.
With these two functions, we can determine the size of any array. This can be used to create
a loop that works regardless of the number of elements:
<%
For t = LBound(arrFrugt) to UBound(arrFrugt)
Response.Write arrFruits(t)
Next
%>
This loop will work regardless of how many or few elements the array contains.
Another example
Below is another example of how you can use an array to write the name of the month:
<html>
<head>
<title>Array<title>
</head>
<body>
<%
' A variable for the names of the months
Dim arrMaaneder
' Note the comma before January - because there is no month with
the number 0
arrMaaneder =
Array(,"January","February","March","April","May","June","July","August
","September","October","November","December")
' Call the array with the number of the month - write to the
client
Response.Write arrMaaneder(Month(Date))
%>
</body>
</html>
Show example
Notice that we use the function
Array instead of the function
Split to create an array.
Ok. Enough about arrays! In the next lesson, you will learn how to write your own functions.
Lesson 9: Functions
In previous lessons you have learned to use functions like Ubound and Weekday. In this
lesson, you will learn to create your own functions using
Function .
What is a function?
A function process inputs and return an output. It can be useful if, for example, you have a
wide range of data you have processed or if you have calculations or routines in other ways
that must be performed many times.
A function has the following syntax:
Function Name(list of parameters)
Statement
End Function
This way, we can make a very simple function that can add the value 1 to a number. It could
look like this:
Function AddOne(t)
t = t + 1
AddOne = t
End Function
Our function is named AddOne and must be called with a number - e.g. 34....
Response.Write AddOne(34)
... which (surprise!) will return 35.
The example above processes a number, but functions can work with text, dates or anything
else. You can also create functions that are called by many different parameters. In this
lesson you will see different examples of functions.
Example: Function with more parameters
As mentioned above, you can easily create a function that can be called with more
parameters. In the next example, we'll create a function that is called with three numbers and
then returns the value of the three numbers added together:
<html>
<head>
<title>Functions</title>
</head>
<body>
<%
Function AddAll(number1, number2, number3)
AddAll = number1 + number2 + number3
End Function
Response.Write "123 + 654 + 9 equals " & AddAll(123,654,9)
%>
</body>
</html>
Show example
Ok. Now that was almost too simple! But the point was just to show you that a function can
be called with more parameters.
Example: English date and time
Let us try to make a slightly more complex function. A function that's called with a date and
time returns it in the format: Wednesday, 15 February, 2012, 10:00:00 AM
<html>
<head>
<title> Loops </title>
</head>
<body>
<%
Function EnglishDateTime(strDate)
' Array with the English names for days of the week
arrDay = "Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday, Sunday"
arrDay = Split(arrDay,",")
' Array with the English names of the months
arrMonth =
"January,February,March,April,May,June,July,August,"
arrMonth = arrMonth & "September,October,November,December"
arrMonth = Split(arrMonth,",")
' The date is constructed
EnglishDateTime = arrDay(Weekday(strDate,vbMonday)) & ",
Day(strDate) "
" &
EnglishDateTime = EnglishDateTime & arrMonth(Month(srDate)) &
", " & Year(strDate)
EnglishDateTime = EnglishDateTime & ",
FormatDatetime(strDate, vbLongTime)
" &
End Function
' Test function
Response.Write EnglishDateTime(Now)
%>
</body>
</html>
Show example
Please note how 'ArrMonth' and 'EnglishDateTime' are constructed over several lines. This is
done so that users with a low screen resolution better can see the example. The method has
no effect on the code itself.
The function above works on all web servers regardless of language. This means that you
can use such a function if your website, for example, is hosted on a French server, but you
want English dates.
At this stage, we will not go into more depth with functions, but now you know a little about
how functions work.
Lesson 10: Passing variables in a URL
When you work with ASP, you often need to pass variables from one page to another. This
lesson is about passing variables in a URL.
How does it work?
Maybe you have wondered why some URLs looks something like this:
http://html.net/page.asp?id=1254
Why is there a question mark after the page name?
The answer is that the characters after the question mark are a HTTP query string. A HTTP
query string can contain both variables and their values. In the example above, the HTTP
query string contains a variable named id, with the value 1254.
Here is another example:
http://html.net/page.asp?navn=Joe
Again, you have a variable (name) with a value (Joe).
How to get the variable with ASP?
Let's say you have an ASP page named people.asp. Now you call this page using the
following URL:
people.asp?name=Joe
With ASP you will be able to get the value of variable 'name' like this:
Request.QueryString("name")
So, you use the object
Request and
Let's try it in an example:
QueryString to find the value of a named variable.
<html>
<head>
<title>QueryString</title>
</head>
<body>
<%
' The value of the variable is found
Response.Write "<h1>Hello " & Request.QueryString("name") &
"</h1>"
%>
</body>
</html>
Show example (keep an eye on the URL)
When you look at the example above, try to replace the name "Joe" with your own name in
the URL and then call the document again! Quite nice, eh?
Several variables in the same URL
You are not limited to pass only one variable in a URL. By separating the variables with &,
multiple variables can be passed:
people.asp?name=Joe&age=24
This URL contains two variables: name and age. In the same way as above, you can get the
variables like this:
Request.QueryString("name")
Request.QueryString("age")
Let's add the extra variable to the example:
<html>
<head>
<title>QueryString </title>
</head>
<body>
<%
' The value of the variable name is found
Response.Write "<h1>Hello" & Request.QueryString("name") &
"</h1>"
' The value of the variable age is found
Response.Write "<h1>You are " & Request.QueryString("age") & "
years old</h1>"
%>
</body>
</html>
Show example (keep an eye on the URL)
Now you have learned one way to pass values between pages by using the URL. In the next
lesson, we'll look at another method: forms.
Lesson 11: Passing variables with forms
Interactive websites require input from users. One of the most common ways to get input are
with forms.
In this lesson, we will look at how to build forms and process inputs on the server.
<form>
When you code a form, there are two particular important attributes: action and method.
action
Is used to enter the URL where the form is submitted. It this case it would be the
ASP file that you want to handle the input.
method
Can either have the value "post" or "get" which are two different methods to pass
data. At this point, you don't need to know much about the difference, but with "get",
the data is sent through the URL, and with "post", data is sent as a block of data
through standard input service (STDIN).
An HTML page with a form
The page that contains the form doesn't need to be an ASP file (but it can be). It need not
even be on the same site as the file that will receive the data.
In our first example, we will look at a very simple form with one text field:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter your name</h1>
<form method="post" action="handler.asp">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
The result in the browser is a form:
Now we come to the fun part: receiving and handling the data with ASP.
Requesting form data with ASP
When you need to request data from a form - and many other places (we will come back to
that) - you use the object request. Since our data was submitted through a form using the
method "post", we write:
Request.Form("fieldname")
Which returns the value of the text field in the form. Let us try to use it in an example.
First create a page with a form as above. Then make an ASP page named "handler.asp"
(notice that this is the name of the page we wrote in the action attribute in our <form>).
The file "handler.asp" shall have the following content:
<html>
<head>
<title>Form</title>
</head>
<body>
<%
Response.Write "<h1>Hello " & Request.Form("username") & "</h1>"
%>
</body>
</html>
Show example
User input and conditions
In the next example, we will try to use user input to create conditions. First, we need a form:
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="handler.asp">
<p>What is your name:</p>
<input type="text" name="username"></p>
<p>What is your favorite color:
<input type="radio" name="favoritecolor" value="r" /> Red
<input type="radio" name="favoritecolor" value="g" /> Green
<input type="radio" name="favoritecolor" value="b" /> Blue </p>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Which will look like this in the browser:
Now we will use these inputs to create a page that automatically changes background color
according to what the user's favorite color is. We can do this by creating a condition
(see lesson 6) that uses the data the user has filled out in the form.
<%
strHeading = "<h1>Hello " & Request.Form("username") & "</h1>"
Select Case Request.Form ("favoritecolor")
Case "r"
strBackgroundColor = "rgb(255,0,0)"
Case "g"
strBackgroundColor = "rgb(0255.0)"
Case "b"
strBackgroundColor = "rgb(0,0,255)"
Case Else
strBackgroundColor = "rgb(255,255,255)"
End Select
%>
<html>
<head>
<title>Form</title>
</head>
<body style="background: <% = strBackgroundColor %>;">
<% Response.Write strHeading %>
</body>
</html>
The background color will be white if the user has not chosen any favorite color in the form.
This is done by using Case Else to specify what should happen if none of the above
conditions are met.
But what if the user does not fill out his name? Then it only says "Hello" in the title. We will
use an extra condition to change that.
<%
strUserName = Request.Form ("username")
If strUserName <>"" Then
strHeading = "<h1>Hello " & strUserName & "</h1>"
Else
strHeading = "<h1>Hello stranger!</h1>"
End If
Select Case Request.Form ("favoritecolor")
Case "r"
strBackgroundColor = "rgb(255,0,0)"
Case "g"
strBackgroundColor = "rgb(0255.0)"
Case "b"
strBackgroundColor = "rgb(0,0,255)"
Case Else
strBackgroundColor = "rgb(255,255,255)"
End Select
%>
<html>
<head>
<title>Form</title>
</head>
<body style="background: <% = strBackgroundColor %>;">
<% Response.Write strHeading %>
</body>
</html>
Show example.
In the example above we use a condition to validate the information from the user. In this
case, it might not be so important if the user did not write his name. But as you code more
and more advanced stuff, it's vital that you take into account that the user may not always fill
out forms the way you had imagined.
Lesson 12: Sessions
When you visit a website, you do a number of different things. You click from one page to
another. Perhaps you also fill out a form or purchase a product.
As a web developer, such information is of great importance to developing successful web
solutions.
Suppose, for example, that you want to make a site where some pages are protected with
login and password. To make this protection effective, the password-protected pages should
have access to information on whether the user has logged in at an earlier time. You must, in
other words, be able to "remember" what the user did earlier.
This is exactly what this lesson is about - how you can use Sessions in ASP to store and
retrieve information during a user's visit to your site.
Session object
The
Session object allows you to manage information about a user's session. You can
write smart applications that can identify and gather information about users.
A session can begin in different ways. We will not go into technical details here but focus on
the case where a session starts by a value is being stored in the Session object. A session
ends/dies if the user hasn't requested any pages within in a certain timeframe (by the
standard 20 minutes). Of course, you can also always end/kill a session in your script.
Let us say, 50 people are clicking around on the same site, eg. a web shop, at the same
time. Information on what they each of them have in their shopping cart would best be stored
in the Session object. In order to identify the individual users the server uses a unique user
ID that is stored in a cookie. A cookie is a small text file stored on the user's computer - more
about cookies in lesson 13. Therefore, sessions often require support of cookies in the user's
browser.
An example of using sessions
When you requested this page, I stored the current time in a session. I did this so that I can
now show you an example of how a session works.
I named the item "StartTime" and stored it by adding the following line in my ASP script:
<%
Session ("StartTime") = Now
%>
Thereby, a session was started. As described above, each session is given an ID by the
server.
Your session has the following ID: 51674855c875ba3e9d63da05c261b648
At any time, I can call the "StartTime" from the session by writing:
<%
Response.Write Session("StartTime")
%>
Which would reveal that the page was requested at 7/28/2012 9:48:43 (according to the
clock on this web server).
But what is interesting is that the information remains in the Session object, even after you
have left this page. The information will follow you until your session ends.
By default, a session lasts for 20 minutes, then it dies automatically. But if you want a
session to last longer or shorter, you can define the desired time in minutes this way:
<%
Session.Timeout = 60
%>
In this case, the session will last for 60 minutes before it dies. Too many sessions at the
same time overload the server. Therefore, you should not let sessions run longer than
necessary.
If you want to stop a session, it can always be killed in this way:
<%
Session.Abandon
%>
Let us try to look at another example where sessions are used: a password solution.
Login system with sessions
In the following example, we will make a very simple login system. We will use many of the
things they have learned in previous lessons.
The first thing we need is a form where people can enter their username and password. It
could look like this:
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="post" action="login.asp">
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="text" name="password" /></p>
<p><input type="submit" value="Let me in" /></p>
</form>
</body>
</html>
Then we create the file login.asp.
In this file, we check whether it is the correct username and password that has been entered.
If that is the case, we set a session that says that this user is logged in with the correct
username and password.
<html>
<head>
<title>Login</title>
</head>
<body>
<%
' Check if username and password are correct
If Request.Form("username") = "asp" AND Request.Form("password")
= "asp" Then
' If correct, we set the session to YES
Session("login") = "YES"
Session.Timeout = 30
Response.Write "<h1> You are now logged in</h1>"
Response.Write "<p><a href='document.asp'>Link to protected
file</a> </p>"
Else
'If not correct, we set the session to NO
Session("login") = "NO"
Session.Timeout = 30
Response.Write "<h1>You are NOT logged in</h1>"
Response.Write "<p> <a href='document.asp'>Link to protected
file</a></p>"
End If
%>
</body>
</html>
In the protected files, we want to check whether the user is logged in properly. If this is not
the case, the user is sent back to the login form. This is how the protection is made:
<%
' If the user is not logged in
' send him/her to the login form
If Session ("login") <>"YES" Then
Response.Redirect "form.asp"
End If
%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>This document is protected</h1>
<p>You can only see it if you are logged in.</p>
</body>
</html>
Click here to test the login system
Now you've been introduced to the Session object. In the next lesson we are in same alley
and take a closer look at cookies.
Lesson 13: Cookies
How and what kind of information websites are collecting from their users, and especially
how they use it, is a hot topic. Often cookies are mentioned as an example of how
information is collected and pose a threat to your privacy. But are there reasons to be
worried? Judge for yourself. Once you have gone through this lesson, you will know what
can be done with cookies.
What is a cookie?
A cookie is a small text file in which a website can store different information. Cookies are
saved on the user's hard drive and not on the server.
Most cookies expire (delete themselves) after a predetermined time period, which can range
from one minute to several years. But the user can also identify and delete any cookies on
his/her computer.
Most browsers - such as Microsoft Internet Explorer, Mozilla Firefox and Google Chrome can be configured to let the user choose whether or not he/she will accept a cookie. But
then, why not just say no to all cookies? It is possible. But many websites would not work as
intended without cookies, since cookies in many contexts are used to improve the usability
and functionality of the website.
How is information stored in a cookie?
It easy to set or modify a cookie in ASP with
will create a cookie and set the value.
Response.Cookies . In the first example, we
First, you need a name for the cookie. In this example we will use the name "HTMLTest".
Next, you set the value of the cookie like this:
<%
' Setting the cookie
Response.Cookies("HTMLTest")("Name") = "C. Wing"
Response.Cookies("HTMLTest")("interest") = "planespotting"
' How long the cookie should last - in this case one year
Response.Cookies("HTMLTest").Expires = Date+365
%>
In this example, we stored information about a user's name and interests. This information
can, for example, be useful to target the website specifically for the individual visitor.
How do you retrieve the value of a cookie?
To get the value of the cookie,
Request.Cookies is used. For example, if we need the
information from the example above, we do it like this:
<%
' Retrieve values from the cookie
strName = Request.Cookies("HTMLTest")("Name")
strInterest = Request.Cookies("HTMLTest")("interest")
' Write to the client
Response.Write "<p>" & strName & "</p>"
Response.Write "<p> Your interest is " & strInterest & "</p>"
%>
Who can read the cookie?
By default, a cookie can be read at the same second-level domain (eg. html.net) as it was
created. But by using the attributes domain and path, you can put further restrictions on the
cookie.
<%
' Setting the cookie
Response.Cookies ("HTMLTst")("Name") = "C Wing"
Response.Cookies ("HTMLTest")("interest") = "planespotting"
' How long the cookie should last - in this case one year
Response.Cookies ("HTMLTest").Expires = Date+365
' The cookie should only be read by fr.html.dk
Response.Cookies("HTMLTest").Domain = "fr.html.dk"
' The cookie can only be read by pages in this folder
Response.Cookies("HTMLTest").Path = "/tutorials/asp"
%>
Example of a cookie
We can try to save a sample cookie on your computer and then see how it looks.
The following code sets the cookie:
<%
' Setting the cookie
Response.Cookies ("HTMLTest")("text") = "This text is in a
cookie!"
' The cookie should live for 24 hours
Response.Cookies ("HTMLTest").Expires = Date+1
' The cookie should only be read by www.html.net
Response.Cookies("HTMLTest").Domain = "www.html.net"
' The cookie can only be read by pages in this folder
Response.Cookies ("HTMLTest").Path = "/tutorials/asp"
' Write the information to the client
strText = Request.Cookies("HTMLTest")("text")
Response.Write "<p> & strText & "</p>"
%>
Show example
The cookie is being placed on your hard drive. Depending on what operating system you
use, your cookies may be saved in different places. Once you find them, they will probably
look like this:
As you can see, a cookie is an normal text file that can be open with for example Notepad.
The contents of the cookie we have just created will probably look something like this:
HTMLTest TEXT=This+text+is+in+a+cookie% 21 www.html.net/tutorials/asp 0
80973619229399148 4216577264 29399141 *
We will not go into detail with the different codes, but simply note that the user has full
control over cookies on his/her computer.
In this lesson we have looked at what cookies can do but not what they can be used for. It's
a common concern that some sites use cookies for inappropriate activities. But in most
cases, cookies are used to make sites more user-friendly or relevant for the individual users.
If you choose to use cookies on your site it might be a good idea to tell your users that your
site uses cookies. This can, for example, be communicated in a privacy policy or registration
process.
Lesson 14: The File System Object
With the
FileSystemObject you can access the server's filesystem. This allows you to
manipulate drives, folders and text files in ASP scripts.
For example, you can use the {0}{1/}FileSystemObject{/0} to read or write a text file. Or you
can list all files in a specified folder. There are many possibilities and the FileSystemObject
can save you lots of tedious work.
Here, we'll look at how you can use the FileSystemObject to work with drives, folders and
files. The goal is to give you a quick overview. In the next lessons, we will look more closely
at the different possibilities with the FileSystemObject.
Drives
We start by looking at the computer's drives. Not because this is what you will be using the
most, but because it's sensible to start with drives before digging into the topic of folders and
files.
In the example below, we get all the drives on the server listed. This is done by the
FileSystemObject, which creates an array with the drives. Each drive letter is then written as
we run through the array.
<html>
<head>
<title>FileSystemObject</title>
</head>
<body>
<%
' Variables
Dim FSO, d, dc
' FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Array of drives
Set dc = fso.Drives
' Loop through the array and write the drive letter
For Each d in dc
Response.Write d.DriveLetter & "<br />"
Next
%>
</body>
</html>
Show example
Now we have listed all the drives on the server. It is also possible to retrieve additional
information about each drive. For example, let's look closer at the E drive and examine what
type of drive it is. For this, we use the property
DriveType:
<html>
<head>
<title>FileSystemObject</title>
</head>
<body>
<%
' Variables
Dim fso, d, t
' FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Object Drive
Set d = fso.GetDrive("E:")
' Find drive type and set description
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
Response.Write "Drive" & dDriveLetter & ": is a " & t & " drive"
%>
</body>
</html>
Show example
At this time, we will not go into more depth with drives. See
Drive Object in the VBScript
documentation if you want more information on the different properties, etc.
Folders
The FileSystemObject also allows you to work with folders on the server. But before we
begin to look at the
Folder object, we need to be able to find the physical location of a
folder or file.
The problem is that your website normally is hosted on a web-hosting server. Therefore, you
probably don't know the physical location of a folder or a file. But help is near: You can use
the method
Server.Mappath to find the physical location of any file or folder.
For example, to find the physical location of the folder we are in right now, we write:
<%
Response.Write Server.Mappath("/tutorials/asp/")
%>
Which returns:
d:\www2\html\tutorials\asp
We now know that we are in the folder "www2" on drive d at the web server - a very nifty
feature!
Let's now use this method together with the FileSystemObject and the FolderObject. We will
not go through all the different possibilities - only a few selected. Again, see the
documentation for a complete listing.
DateCreated
Returns the date and time when a file or folder was created.
DateLastModified
Returns the date and time when a file or folder was edited/modified.
Size
Returns the size of a file or a folder (including all files and subfolders) in bytes.
Let us try to find the three properties of the folder we are in now, which is
http://www.html.net/tutorials/asp/.
<html>
<head>
<title>FileSystemObject</title>
</head>
<body>
<%
' Variables
Dim fso, f, folderspec
' Find the physical location of the folder
folderspec = Server.Mappath ("/tutorials/asp/")
' FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Folder object
Set f = fso.GetFolder(folderspec)
' Find and write properties
Response.Write "<h1>Folder: " & folderspec & "</h1>"
Response.Write "<p>Was created: " & f.DateCreated & "</p>"
Response.Write "<p>Last edited: " & f.DateLastModified & "</p>"
Response.Write "<p>Size: " & f.Size & " bytes</p>"
%>
</body>
</html>
Show example
Files
Just as with folders, you can use the FileSystem object to find the properties of a file.
In exactly the same way as above, we can find the same properties for the file you are
looking at now: http://www.html.net/tutorials/asp/lesson14.asp.
<html>
<head>
<title>File System object</title>
</head>
<body>
<%
' Variables
Dim fso, f, filespec
' Find the physical location of the file
filespec = Server.Mappath("/tutorials/asp/lesson4.asp")
' FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' File object
Set f = fso.GetFiles(filespec)
Find and write properties
Response.Write "<h1>The file: " & filespec & "</h1>"
Response.Write "<p>Was created: " & f.DateCreated & "</p>"
Response.Write "<p>Last edited: " & f.DateLastModified & "</p>"
Response.Write "<p>Size: " & f.Size & " bytes</p>"
%>
</body>
</html>
Show example
In the next lesson, we will continue to look at the FileSystem object. Among other things, we
will look at how to read from and write to a text file.
Lesson 15: Reading from a text file
In the previous lesson, we learned how to use the
FileSystemObject to access the
server's filesystem. In this lesson, we will use this learning to read from an ordinary text file.
Text files can be extremely useful for storing various kinds of data. They are not quite as
flexible as real databases, but text file typically don't require as much memory. Moreover,
text files are a plain and simple format that works on most systems.
Open the text file
We use the
OpenTextFile method to open a text file. The syntax is as follows:
Object.OpenTextFile(filename, mode)
filename
Name of the file to be opened.
Mode
Mode can set to 1 (ForReading), 2 (ForWriting) or 8 (ForAppending). In this lesson
we will only read from a file and, therefore, use ForReading. In the next lesson, we
will learn to write to a file.
The examples in this lesson use the text file unitednations.txt. This is a simple list of the
Programmes and Funds of the United Nations and their domains. You can either download
the file, or you can create your own file and test the examples with it.
First, let's try to open unitednations.txt:
<%
' Variables
Dim fso, f filespec
' FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Find the physical location of the text file
filespec = Server.Mappath("/tutorials/asp/unitednations.txt")
' Open the text file
Set f = fso.OpenTextFile(filespec,1)
' Close the text file
f.Close
%>
Example 1: Read a line from the text file
With the method
readline, we can read a line from the text file. This method reads until
the first line break (but not including the line break).
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<%
Dim fso, f, filespec
Set fso = CreateObject("Scripting.FileSystemObject")
filespec = Server.Mappath("/tutorials/asp/unitednations.txt")
Set f = fso.OpenTextFile(filespec,1)
' Read line from the text file and write the contents to the
client
Response.write f.readline
f.Close
%>
</body>
</html>
Show example
Example 2: Read all lines from the text file
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<%
Dim fso, f, filespec
Set fso = CreateObject("Scripting.FileSystemObject")
filespec = Server.Mappath("/tutorials/asp/unitednations.txt")
Set f = fso.OpenTextFile (filespec,1)
' Read line by line until end of file
Do While Not f.AtEndOfStream
Response.write f.ReadLine & "<br />"
Loop
f.Close
%>
</body>
</html>
Show example
In this case we chose to loop through all the lines, but we could have achieved the same
result with the method
ReadAll . If you work with very large text files, be aware that the
ReadAll method uses more resources than the ReadLine method. For smaller files, it makes
very little difference.
Example 3: Skip lines
You don't need to read all lines in a file. With the method
SkipLine, you can skip lines.
This is shown in the example below, where the first 5 lines in the file are skipped and
whereafter the sixth line is read:
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<%
Dim fso, f, filespec
Set fso = CreateObject("Scripting.FileSystemObject")
filespec = Server.Mappath("/tutorials/asp/unitednations.txt")
Set f = fso.OpenTextFile(filespec,1)
' Skip the first five lines
For intLine = 1 to 5
f.SkipLine
Next
' Write the sixth line
Response.write f.readline & "<br />"
f.Close
%>
</body>
</html>
Show example
Example 4: A simple link directory
As mentioned at the beginning of this lesson, text files can be an excellent data storage. This
is illustrated in the next example where we create a simple link directory from the contents of
the text file unitednations.txt.
The file is systematically written with the name of the program, then a comma, and then the
domain. As you can probably imagine, more information could easily be stored in this
comma-separated data file.
To get the information in each line, we use an array. See Lesson 8 for more information on
arrays.
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<%
Dim fso, f, filespec
Set fso = CreateObject("Scripting.FileSystemObject")
filespec = Server.Mappath("/tutorials/asp/unitednations.txt")
Set f = fso.OpenTextFile(filespec,1)
' Read line by line until end of file
Do While Not f.AtEndOfStream
' Make array using comma as delimiter
arrM = Split(f.readline ,",")
' Write links - get the data in the array
Response.write "<li><a href='http://" & arrM(1) & "'>" &
arrM(0) & "</a></li>"
Loop
f.Close
%>
</body>
</html>
Show example
Quite handy, right? In principle, you could now just expand the text file with hundreds of links
or perhaps expand your directory to also include address information.
In the next lesson, we will look at how to write to a text file.
Lesson 16: Writing to a text file
In the previous lesson, we learned to read from a text file. In this lesson, we will learn to write
to a text file.
The two methods are very similar, but there is one very important difference: You must have
write permissions to the file. This means that the file will have to be located in a folder where
you have the necessary permissions.
With most web hosts, you will normally have one folder with write permissions. It's often
called something like "cgi-bin", "log", "databases" or something similar. Read more on your
web host's support pages. If you work locally on your own computer, you can set the
permissions yourself: right-click on the folder and choose "Properties".
Note that it is the text file that needs to be in the folder with write permissions - not the ASP
file.
Open the text file for writing
In the same way as when reading from a text file, the
OpenTextFile method is used for
writing, but this time we set the mode to 2 (ForWriting) or 8 (ForAppending).
The difference between ForWriting and ForAppending is where the 'cursor' is located - either
at the beginning or at the end of the text file.
In the examples in this lesson we use an empty text file called textfile.txt - but you can, of
course, make your own text file if you like.
First, let us try to open the text file for writing:
<%
' Variables
Dim fso, f, filespec
' FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Find the physical location of the text file
filespec = Server.Mappath("/tutorials/asp/textfile.txt")
' Open the text file
Set f = fso.OpenTextFile(filespec,2)
'Close the text file
f.Close
%>
Example 1: Write a line to the text file
To write a line we must use the method
WriteLine, like this:
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<%
Dim fso, f, filespec
Set fso = CreateObject("Scripting.FileSystemObject")
filespec = Server.Mappath("/tutorials/asp/textfile.txt")
Set f = fso.OpenTextFile(filespec,2)
' Write a text line
f.WriteLine "VBScript and ASP is fun!"
'Open file for reading, and read the line
Set f = fso.OpenTextFile(filespec,1)
Response.write f.ReadLine
f.Close
%>
</body>
</html>
Show example
Since we opened the file "ForWriting", the line is added at the top, and thus overwrites the
existing line. If we instead open the file "ForAppending", the line is added at the bottom of the
text file, which then will increase by one line each time it's written to.
Example 2: Adding a text block to a text file
Of course, it is also possible to add an entire text block, instead of just a single line. This is
done with the method
Write, like this:
<html>
<head>
<title>Reading from text files</title>
</head>
<body>
<%
Dim fso, f, filespec
Set fso = CreateObject("Scripting.FileSystemObject")
filespec = Server.Mappath("/tutorials/asp/tekstfil.txt")
Set f = fso.OpenTextFile(filespec,2)
' Write text line
f.Write Request.Form("TextBlock")
' Open file for reading and read line by line
Set f = fso.OpenTextFile(filespec,1)
Do While Not f.AtEndOfStream
Response.write f.ReadLine & "<br />"
Loop
f.Close
%>
</body>
</html>
Show example
In the next lessons, we look at another way of storing data: databases.
Lesson 17: Databases
There are many different databases: MS Access, MS SQL Server, Oracle SQL Server,
MySQL and many others. In this tutorial, we will use the Microsoft Access database. Access
is the natural place to start when you want to use databases in ASP.
In this lesson, we will start by looking at the Access database that we will use in the next
lessons. Access is part of the Microsoft Office family and is included in some of the Office
suites. You need to have Microsoft Access installed on your computer in order to go through
this lesson and the next lessons. A trial version can be downloaded at
http://office.microsoft.com.
Below you can download the database used in the examples in this tutorial. In the examples,
Access 2010 is used but there are no significant differences in the screens that appear.
Download the database
About Microsoft Access
Once you've downloaded and opened the database, you will see a screen with a list of the
tables in the database. We will only use one table in the database. The table is named
"people" and contains names and birth dates.
You open the table by double clicking on it. There are many different ways you can work with
tables in Access. We will not go into depth with Access as a tool, but only look at the very
basics you need to know to use Access as a database for your ASP applications.
The table opens by default in Datasheet View. If you are used to working with spreadsheets,
or maybe has used Access before, the table view will look familiar to you with columns and
rows:
As you can see, in the table, we have listed some of the residents from Duckburg.
There are primarily two different ways of viewing a table in Access: Design View and
Datasheet View. Above, you see the table in Datasheet view, meaning that you see the table
with all the values. In the upper left corner of the program you can switch between the two
view types:
The Design View gives you an overview of the columns and the data types. In a database, it
does matter what type of content there is in a column. In our database, three different data
types are used: text, number and date. There are many different options in the Design View.
See the help feature in Access for more information.
This was a short introduction to Microsoft Access. In the beginning, you don't need to change
anything in the database and can use it as is. Later, you can create your own databases,
which is actually easy and straightforward.
In the next lesson, we will look at where to place the database and how to create a database
connection.
vsLesson 19: Get data from database
In the previous lessons, we have learned to create a database in Access and to make a
database connection. Now it is time to retrieve content from the database to our ASP pages.
This is really one of the most important lessons in this tutorial. Once you have read and
understood this lesson, you will realize why database-driven web solutions are so powerful,
and your views on web development will be expanded dramatically.
SQL queries
To retrieve data from a database, you use queries. An example of a query could be: "get all
data from the table 'people' sorted alphabetically" or "get names from the table 'people'."
To write such queries, you use the language Structured Query Language (SQL).
Fortunately, SQL is very easy to learn. Try looking at this simple example:
Get all data from the table 'people'
Will be written like this in SQL:
SELECT * FROM people
The syntax is pretty self-explanatory. Just read on and see how SQL statements are used in
the examples below.
Example 1: Retrieve data from a table
This example uses the database from lesson 17 and the database connection from lesson
18. Therefore, it is important that you read these lessons first.
The example shows how data in the table "people" is retrieved with a SQL query.
The SQL query returns a result in the form of a series of records. These records are stored
in a so-called recordset. A recordset can be described as a kind of table in the server's
memory, containing rows of data (records), and each record is subdivided into individual
fields (or columns).
A recordset can be compared to a table, as you know it from the Datasheet View in Access:
Viewed this way, each record can be compared to a row in the table. You can move around
in a recordset using the methods MoveNext (go to next record), MovePrevious (go to
previous record), MoveFirst (go to the first record), and MoveLast (go to the last record).
The code below shows how to use a recordset:
<html>
<head>
<title>Retrieve data from database </title>
</head>
<body>
<%
' Database connection - remember to specify the path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER = {Microsoft Access Driver (*. mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath ("/cgi-bin/database.mdb")
Conn.Open DSN
' SQL Query
strSQL = "SELECT * FROM people"
' Execute the query (the recordset rs contains the result)
Set rs = Conn.Execute(strSQL)
' Loop the recordset rs
Do
' Write the value of the column FirstName
Response.Write rs("FirstName") & "<br />"
' Move to next record in rs
rs.MoveNext
' Continue until end of recordset (EOF = End Of File)
Loop While Not rs.EOF
' Close the database connection
Conn.Close
Set Conn = Nothing
%>
</body>
</html>
Show example
Notice that for every record how we get the content of the column "FirstName" by typing
rs("FirstName"). Similarly, we can get the content of, for example, the column "Phone" by
writing rs("Phone").
The order of the recordset is exactly the same as in the table in the database. But in the next
example, it will be shown how to sort recordset.
Example 2: Sort the data alphabetically,
chronologically or numerically
Often it can be helpful if a list or table of data is presented alphabetically, chronologically or
numerically. Such sorting is very easy to do with SQL, where the syntax Order By
ColumnName is used to sort according to the column contents.
Look at the SQL statement from the example above:
strSQL = "SELECT * FROM people"
The records can, for example, be sorted alphabetically by the first name of the people this
way:
strSQL = "SELECT * FROM people ORDER BY FirstName"
Or chronologically by date of birth like this:
strSQL = "SELECT * FROM people ORDER BY BirthDate"
The sorting can be charged from ascending to descending by adding DESC:
strSQL = "SELECT * FROM people ORDER BY BirthDate DESC"
In the following example the people are sorted by age:
<html>
<head>
<title>Retrieve data from database </title>
</head>
<body>
<%
' Database connection - remember to specify path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER={Microsoft Access Driver (*. mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")
Conn.Open DSN
' SQL Query
strSQL = "SELECT * FROM people ORDER BY BirthDate DESC"
' Execute the query (the recordset rs contains the result)
Set rs = Conn.Execute (strSQL)
' Loop the recordset (rs)
Do
' Write the contents of the columns FirstName and BirthDate
Response.Write rs("FirstName") & " " & rs("BirthDate") & "<br
/>"
' Move to the next record in rs
rs.MoveNext
' Continue until end of recordset (EOF = End Of File)
Loop While Not rs.EOF
' Close the database connection
Conn.Close
Set Conn = Nothing
%>
</body>
</html>
Show example
Try to change the SQL statement yourself and sort the records by first name, last name or
phone number.
Retrieve selected data
Until now, our SQL statement retrieves all rows from the table. But often you need to set
criteria in the SQL query for the data to be retrieved. For example, if we only want the rows
for those who had a particular phone number or a certain last name.
Say, we only want to retrieve people from the database who hav the phone number
"66554433". That could be done like this:
strSQL = "SELECT * FROM people WHERE Phone = '66554433 '"
There are six relational operators in SQL:
= Equals
< Less
> Greater Than
<= Less than or equal to
> = Greater than or equal to
<> Not equal to
In addition, there are some logical operators:
AND
OR
NOT
See lesson 6 for more information on how to set up conditions.
In the next example, we use conditions to set up a address book.
Example 3: Address book
In this example we will try to combine many of the things you have just learned. We will
make a list of the names from the database where each name is a link to further details
about the person.
For this, we need two files - liste.asp and people.asp - with the following code:
The code of list.asp
<html>
<head>
<title>Retrieve data from the database</title>
</head>
<body>
<ul>
<%
' Database connection - remember to specify path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER={Microsoft Access Driver (*. mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")
Conn.Open DSN
strSQL = "SELECT * FROM people ORDER BY FirstName DESC"
Set rs = Conn.Execute (strSQL)
Do
' Name of the person
strNavn = rs("FirstName") & " " & rs("LastName")
' Create a link to person.asp with the Id-value in the URL
strLink = "<a href = 'person.asp?id = " & rs("Id") & "'>" &
strNavn & "</a>"
'List link
Response.Write "<li>" & strLink & "</li>"
rs.MoveNext
Loop While Not rs.EOF
Conn.Close
Set Conn = Nothing
%>
</ul>
</body>
</html>
The code for person.asp
<html>
<head>
<title>Retrieve data from database</title>
</head>
<body>
<dl>
<%
' Database connection - remember to specify the path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER={Microsoft Access Driver (*. mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")
Conn.Open DSN
' Get data from the database depending on the value of the id in
the URL
strSQL = "SELECT * FROM people WHERE Id =" &
Request.QueryString("id")
Set rs = Conn.Execute(strSQL)
' Write the data of the person
Response.Write "<dt>Name:</dt><dd>" & rs("FirstName") & " " &
rs("LastName") & "</dd>"
Response.Write "<dt>Phone:</dt><dd>" & rs("Phone") & "</dd>"
Response.Write "<dt>Birthdate:</dt><dd>" &
FormatDateTime(rs("BirthDate"), vbLongDate) & "</dd>"
Conn.Close
Set Conn = Nothing
%>
</dl>
<p><a href="list.asp">Return to list</a></p>
</body>
</html>
Show example
The address book example is rather simple, but it shows the potential of working with ASP
and databases.
Imagine that the database had contained 10,000 products with detailed descriptions. By
making a few changes in the above files, you could easily create a product catalogue with
more than 10,000 pages with only one database and two ASP files.
Welcome to a world with extensive websites that are easy to develop and maintain. Once
you've learned to work with databases, your web solutions will never be the same again.
Lesson 20: Insert data into a database
When you have to insert new data in your Access database, you could download the entire
database, manually entering data and then uploading the entire database again. But there is
an easier way. In this lesson, we look at how you can insert data into the database directly
from your ASP scripts.
Insert data using SQL
You retrieve data from a database in the same way that you use SQL queries to insert data
into the database. The syntax of the SQL statement is:
INSERT INTO TableName(column1, column2, ...) VALUES(value1, value2, ...)
As you can see, you can update multiple columns in the SQL statement by specifying them
in a comma-separated list. But of course, it is also possible to specify just one column and
one value. The columns that are not mentioned in the SQL statement will just be empty.
Example: Insert a new person in the table
Again, we use the database from lesson 17 . Let's say we want to update the database with
an additional person. It could be the person Gus Goose with the phone
number 99887766 and 20-04-1964 as the date of birth.
The SQL statement would then look like this:
strSQL = "INSERT INTO person(FirstName,LastName,Phone,BirthDate)
VALUES('Cousin','Gus','99887766 ','20-04-1964')"
Conn.Execute(strSQL)
As you can see, SQL statements can get quit long, and you can easily lose track. Therefore,
it can be an advantage to write the SQL statement in a slightly different way:
strSQL = "INSERT INTO people ("
strSQL
strSQL
strSQL
strSQL
=
=
=
=
strSQL
strSQL
strSQL
strSQL
&
&
&
&
"FirstName, "
"LastName, "
"Telephone, "
"birth) "
strSQL = strSQL & "VALUES ("
strSQL = strSQL & "'cousin', "
strSQL = strSQL & "'Gus', "
strSQL = strSQL & "'99887766', "
strSQL = strSQL & "'20-04-1964')"
Conn.Execute(strSQL)
This way, the SQL statement is built up by splitting the sentence up into small parts and then
putting those parts together in the variable strSQL.
In practice, it makes no difference which method you choose, but once you start working with
larger tables, it's crucial that you always keep track.
Try running the following code to insert Gus Goose into the database:
<html>
<head>
<title>Enter data into database</title>
</head>
<body>
<%
' Database connection - remember to specify path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER = {Microsoft Access Driver (*. mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")
Conn.Open DSN
' The SQL statement is built
strSQL = "INSERT INTO people ("
strSQL = strSQL & "FirstName, "
strSQL = strSQL & "LastName, "
strSQL = strSQL & "Phone, "
strSQL = strSQL & "BirthDate) "
strSQL = strSQL & "VALUES("
strSQL = strSQL & "'Cousin', "
strSQL = strSQL & "'Gus', "
strSQL = strSQL & "'99887766', "
strSQL = strSQL & "'20-04-1964')"
' The SQL statement is executed
Conn.Execute (strSQL)
' Close the database connection
Conn.Close
Set Conn = Nothing
%>
<h1>The database is updated!</h1>
</body>
</html>
Save user input into a database
Often you want to save user input in a database.
As you've probably already figured out, this can be done by creating a form as described
in lesson 11 - where the values from the form fields can be inserted in the SQL statement.
Suppose you have a simple form like this:
<form action="insert.asp" method="post">
<input type="text" name="FirstName" />
<input type="submit" value="Save" />
</form>
The form submits to the file insert.asp where you, as shown in lesson 11, can get the user's
input by requesting the form content. In this particular example, an SQL statement could look
like this:
strSQL = "INSERT INTO people (FirstName) values('" &
Request.Form ("FirstName") & "')"
In the same way, it is possible to retrieve data from cookies, session, QueryString, etc.
Most common beginner mistakes
In the beginning, you will probably get a lot of error messages when you try to update your
databases. There is no room for the slightest inaccuracy when you work databases. A
misplaced comma can mean the database is not being updated, and you get an error
message instead. Below, we describe the most common beginner mistakes.
The field doesn't allow zero length
In Design View (see screenshot below), you can set the parameter "Allow Zero Length" for
each column. If this parameter is set to "No", and you attempted to insert a null value in this
column, it would not be possible to insert the record in the database.
Wrong data types
It is important that there is consistency between the type of data and column. Each column
can be set to a data type. The screenshot below shows the data types for table "people" in
our example.
An error occurs if you, for example, attempt to insert text or numbers in a date field.
Therefore, try to set the data types as precisely as possible.
Below is the most common data types listed:
Setting
Data Type
Text
(Default) Text or combinations of text and numbers. Can also be used for numbers that are
not used in calculations (e.g. phone numbers).
Memo
Longer pieces of text, or combinations of text and numbers.
Number
Numerical data for mathematical calculations.
Date/Time
Dates and times.
Currency
Currency values.
AutoNumber
A unique number (incrementing by 1) inserted by Microsoft Access whenever a new record is
added to the database. AutoNumber fields cannot be updated.
Yes/No
Fields that can contain only one of two values, such as Yes/No, True/False, On/Off.
OLE Object
An object (e.g. a Microsoft Excel spreadsheet, a Microsoft Word document, graphics, audio, or
other binary data).
SQL statements with single quotes ( ' )
If you allow users to type some text in a form, and this text contains the character ' (single
quote), the record cannot be inserted into the database. The solution is to replace a single
quote (') with double quote ('').
This can be done with the function
Replace this way:
<%
strTekst = Request.Form ("TextField")
strTekst = Replace(strTekst, "'", "''")
%>
All ' characters will be replaced with double ' characters, which will be interpreted as single
quotes by the database.
Lesson 21: Delete data from database
In the two previous lessons, you have learned to retrieve and insert data into a database. In
this lesson, we'll look at how to delete records in the database, which is considerably easier
than inserting data.
Delete data using SQL
The syntax for an SQL statement that deletes records is:
DELETE FROM TableName WHERE condition
Example 1: Delete a record
When deleting a record, you can use the unique AutoNumber field in the database. In our
database, it is the column named Id. Using this unique identifier ensures that you only delete
one record. In the next example, we delete the record where Id has the value 24:
<html>
<head>
<title>Delete data in the database</title>
</head>
<body>
<%
' Database connection - remember to specify the path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER={Microsoft Access Driver (*. mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")
Conn.Open DSN
' The SQL statement that deletes the record
strSQL = "DELETE FROM people WHERE Id = 24"
Conn.Execute(strSQL)
' Close the database connection
Conn.Close
Set Conn = Nothing
%>
<h1>Record is deleted!</h1>
</body>
</html>
Remember that there is no "Recycle Bin" when working with databases and ASP. Once you
have deleted a record, it is gone and cannot be restored.
Lesson 22: Update data in a database
In previous lessons, you have learned to retrieve, insert and delete data from a database. In
this lesson, we will look at how to update a database, i.e. edit the values of existing fields in
the table.
Update data with SQL
The syntax for an SQL statement that updates the fields in a table is:
Update TableName Set TableColumn='value' Where condition
It is also possible to update multiple cells at once using the same SQL statement:
Update TableName Set TableColumn1='value1', TableColumn2='value2' Where condition
With the knowledge you now have from the lessons 19, 20 and 21, it should be quite easy to
understand how the above syntax is used in practice. But we will of course look at an
example.
Example: Update cells in the table "people"
The code below updates Donald Duck's first name to D. and changes the phone number
to 44444444 The other information (last name and birthdate) are not changed. You can try to
change the other people's data by writing your own SQL statements.
<html>
<head>
<title>Update data in database</title>
</head>
<body>
<%
' Database connection - remember to specify the path to your
database
Set Conn = Server.CreateObject("ADODB.Connection")
DSN = "DRIVER={Microsoft Access Driver (*.mdb)}; "
DSN = DSN & "DBQ=" & Server.MapPath("/cgi-bin/database.mdb")
Conn.Open DSN
' The SQL statement is built
strSQL = "Update people set "
strSQL = strSQL & "FirstName= 'D.', "
strSQL = strSQL & "Phone= '44444444' "
strSQL = strSQL & "Where Id = 24"
' The SQL statement is executed
Conn.Execute(strSQL)
' Close the database connection
Conn.Close
Set Conn = Nothing
%>
<h1>The database is updated!</h1>
</body>
</html>
This example completes the lessons on databases. You have learned to retrieve, insert,
delete and update a database with ASP. Thus, you are actually now able to make very
advanced and dynamic web solutions, where the users can maintain and update a database
using forms.
If you want to see a sophisticated example of what can be made with ASP and databases,
try to join our community. It's free and takes approximately one minute to sign up. You can,
among other things, maintain your own profile using the form fields. Maybe you will get ideas
for your own site. (Note: HTML.net is coded in PHP but could have been made in ASP).
ASP gives you many possibilities for adding interactivity to your web site. The only limit is
your imagination - have fun!
Lesson 1: What is JavaScript?
By Maria Antonietta Perna
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:
"Is JavaScript the same as Java?".
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:


the difference between JavaScript and Java;
what JavaScript can and cannot do.
Are JavaScript and Java the same thing?
No, they are not.
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.
JavaScript is a scripting language, that is, a lightweight programming language that
is interpreted by the browser engine when the web page is loaded.
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.
Things you can't do with JavaScript
You can't force JavaScript on a browser.
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.
You can't access server resources with JavaScript.
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.
Zillion things you can do with JavaScript
With JavaScript you can:
Put text in an HTML page on-the-fly.
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.
Make your web pages responsive.
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.
Detect visitors' browsers.
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).
Validate web form data.
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).
And much ... much more.
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 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 isECMA. Now you know what
you cannot do with JavaScript, but also the great things that you can do with it.
At this point you might say:
"That's all well and good. I'm convinced, JavaScript is fantastic. But, how can I start using it
in my HTML page?"
That's easy: learn how this is done in the next lesson.
Lesson 2: Your First JavaScript
By Maria Antonietta Perna
Now that you know what JavaScript is and what you can do with it, it's time to get to the
practical stuff.
In this lesson you are going to learn:




how to embed your JavaScript in the HTML page;
how to reference your JavaScript from a separate file;
how to comment your JavaScript code and why it is recommended;
how to create your first JavaScript-powered web 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!
Let's start with a basic HTML page, like this one:
<!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.
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."
You can do this either in the <head> section, as follows:
<!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.
Comments, comments, comments
One final thing to note about both code snippets above is the two forward slashes // before
the text "JavaScript code goes here". This is how youcomment a one-line JavaScript
code.
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:
<!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!
Insert JavaScript in a separate file
If your script is longer than a few lines, or you need to apply the same code to several pages
in your website, then packaging your JavaScript code into a separate file is your best bet.
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.
Here's how it's done:
<!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.
Your first JavaScript-powered page: Hello
World
Without further ado, let's see if JavaScript works in your browser.
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.
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!
Lesson 3: Events
By Maria Antonietta Perna
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.
By the end of this lesson you will know:


what events are;
what JavaScript can do with events and how.
What are events?
Events are occurrences taking place in the context of the interactions between web
server, web browser, and web user.
For instance, if you're on a web page and click on a link, there are at least 3 important events
being triggered:
1. onClick event: triggered by you as you click the link;
2. onUnload event: triggered by the web browser as it leaves the current web page;
3. onLoad event: triggered by the browser as the new web page content is loaded.
Which events should I focus on from a
JavaScript point of view?
It all depends on the JavaScript program you're writing, that is, on the objectives you want to
achieve with your script.
However, the most common events you're likely to deal with in your JavaScript are:





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.
What do I do with events from a JavaScript
point of view?
As you write a JavaScript program, events become interesting because they give your script
a hook for gaining control on what happens in the web page.
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.
Hey, an onClick event going on!
Conclusion: events bend to JavaScript commands by means of event handlers. These are
statements in your JavaScript script that are appropriatelyattached to those events.
How does JavaScript handle events?
In this tutorial you've already hooked an event handler to an event. More precisely, you
attached the alert() command to the onLoad event.
The alert() command is a command which is part of the JavaScript language. The JavaScript
interpreter in the browser translates it along these lines:
"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?
Try out: handle an onClick event with
JavaScript
The browser already has its own ways of handling events. For instance, when a page has
loaded, the browser fires the onLoad event and displays the page contents; when a user
clicks a link, the browser communicates to the server to access the requested page, etc.
These are called default actions.
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>
<a href="http://html.net">Click Me!</a>
</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>
<h1>Lesson 3: Events and Event Handlers</h1>
<a href="http://html.net" onclick="alert('Going anywhere? Not
so fast!'); return false;">Click Me!</a>
</body>
</html>
Go ahead, run the page in the browser, and ... you're stuck! JavaScript is in control!
What's just happened there?
That's how easy it was to take control of a link with JavaScript! All you did was to insert a
couple of JavaScript statements to the onclick attribute of the HTML <a> tag.
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.
sLesson 4: Variables and Constants
By Maria Antonietta Perna
Variables and constants are like containers where you store data and values for processing
in JavaScript.
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 unchangedthroughout the script. In all
circumstances where you reasonably foresee that the original value is modified through
the script, by all means use avariable as your storage room. In fact, you're going to use
variables most of the times.
In this lesson, you're going to learn:




how to create variables and constants;
how to assign values to variables and constants;
how to use variables in your code;
how to name variables and constants correctly.
How to create variables and constants
You declare, that is, create variables and constants in a similar way.
Here's how you declare a variable:
/*To declare a variable you give it a name preceded
by the JavaScript keyword var*/
var amountDue;
In the sample code above you declare a variable named 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).
Here's how you declare a constant:
/*To declare a constant you give it a name preceded
by the JavaScript keyword const
Also take note: const is not supported by Internet Explorer
use var instead: it's safer*/
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.
How to assign values to variables
After you create a variable, you must assign (give) a value to it (or said in Geeeky
talk "initialize a variable") . The ( = ) equal sign is calledassignment operator: you assign
the value of what is on the right side of the = sign to whatever is on the left side of the =
sign. Notice: you cannot perform operations with empty variables.
Ready to fire off your text editor? Let's get coding!
Prepare a basic HTML document with the JavaScript code illustrated below:
<!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;
/* Assign a value to it:
you do not know the value yet
so for now it is 0 */
amountDue = 0;
/* Create 2 more vars and assign
a value to each at the same time */
var productPrice = 5;
var quantity = 2;
/* Assign a value to amountDue by
multiplying productPrice by quantity */
amountDue = productPrice * quantity;
/* Notice how the value of amountDue has
changed from 0 to 10 -Alert the result to check it is OK
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.
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:
1) The first character must be a letter, an ( _ )
underscore, or a ( $ ) dollar sign:
5total is wrong: var name cannot start with a number
2) Each character after the first character can be a letter,
an ( _ ) underscore, a ( $ ) dollar sign, or a number:
3) Spaces and special characters other than ( _ ) and
$ are not allowed anywhere:



to tal is wrong: spaces are not allowed;
total# is wrong: # character is not allowed;
total£ is wrong: £ character is not allowed.
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.
Take a break and get ready for lesson 5.
Lesson 5: Smarter Scripts with
Operators
By Maria Antonietta Perna
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.
In this lesson you are going to learn how to use:




arithmetic operators;
the + sign to concatenate text (concatenation operator);
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.
If x = 20, y = 5, and z = result, we have:
Operator
Java Script Example
Result
Addition: +
z=x+y
z = 25
Subtraction: -
z=x-y
z = 15
Multiplication: *
z=x*y
z = 100
Division: /
z=x/y
z=4
Modulus: %
z=x/y
z=0
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 ( -- ) decrementoperators.
Modulus: the remainder left over after division.
Increment: take a number and add 1 to it.
Decrement: take a number and subtract 1 from it.
Time to get coding! Get your hands on the text editor and prepare a new HTML document
like the one below:
Try out: add 2 values and print the result
<!DOCTYPE html>
<html>
<head>
<title>Lesson 5: Operators and Comparisons</title>
</head>
<body>
<h1>Lesson 5: Operators and Comparisons</h1>
<script type="text/javascript">
//Create and initialize your variables
var result = 0;
var firstNum = 20;
var secondNum = 5;
//Addition: result = 25
result = firstNum + secondNum;
//write result on the page
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).
Try out: concatenate strings and print a message on the
page
<!DOCTYPE html>
<html>
<head>
<title>Lesson 5: Operators and Comparisons</title>
</head>
<body>
<h1>Lesson 5: Operators and Comparisons</h1>
<script type="text/javascript">
//Create and initialize your variables
var firstText = "Hello";
var secondText = "World!";
//Resulting value of assignment is Hello World!
var message = firstText + ' ' + secondText;
//write result on the page
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 (' ') inbetween each piece of text or variable.
Now get some practice concatenating strings before moving on.
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:
Operator
What is it?
Example
==
equal to
x == 5 is false
===
exactly equal to value and type
x === 10 is true
x === "10" is false
!=
not equal
x != 2 is true
>
greater than
x > 20 is false
<
less than
x < 20 is true
>=
greater than or equal to
x >= 20 is false
<=
less than or equal to
x <= 20 is true
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.
Here come logical operators to the rescue. Given that x = 10 and y = 5:
Operator What is it?
Example
&&
and
(x < 20 && y > 1) is true
both conditions must be satisfied
||
or
(x == 5 || y == 5) is true
at least 1 condition must be satisfied
!
not
!(x == y) is true
Questions, questions, questions
The tables above are self-explanatory, except for the following 2 questions:
1. When you talk about === , what do you mean by equality of value and type?
2. What's the difference between ( = ), ( == ), and ( === ) ?
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;
In the code snippet above, the variable price has value 5.
What's the type?
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;
//this is true: both values are 4
//and both values are of type number
firstNum === secondNum;
//let's use a string data type. A string uses ' '.
var stringNum = '4';
//Now === is false: 4 and '4' are different types
firstNum === stringNum;
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.
In the next lesson you keep adding intelligence to your JavaScript with if ...
else and switch statements.
Take a break and get ready for it!
Lesson 6: Even Smarter Scripts with
if…else and switch
By Maria Antonietta Perna
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 the condition in brackets is true
if (condition)
{
//do some stuff here
}
Let's translate the code
Translated into English, the if statement above says:
"Hey browser, if the condition in the round brackets is true, execute the commands between
those odd curly braces. If the condition is not true, then ignore everything and move on!"
Important: do not forget either the brackets ( ) or the braces { }.
if ... else statement
Use this statement to execute a command if the condition is true and another command
if the condition is false. Here's its structure:
//if the condition is true
if (condition)
{
//do this stuff
}
//otherwise
else
{
//do this other stuff
}
if ... else if ... else statement
Use this statement if you want your code to evaluate several conditions on the basis of
which to execute the appropriate commands. Here's its structure:
//if the condition is true
if (condition)
{
// do this stuff
}
//if this other condition is true instead
else if (condition)
{
// do this other stuff
}
//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)
{
//in this case do this
case 1:
execute code block 1
//stop here: no need to keep going
break;
//in this other case do that
case 2:
execute code block 2
//stop here: no need to keep going
break;
//otherwise fall back on this
default:
code to execute when all previous conditions evaluate to false
}
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!
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">
//store 5% discount value in a var
var discountRate = 0.05;
//store price of 1 apple in a var with a value of 2
var applePrice = 2;
//store quantity value in a var
var quantity = 5;
//declare a var for the discounted total value
//because we don't know the value we initialize it with 0
var discountedTotal = 0;
//store the value of the total in a var
//you use the ( * ) multiplication operator to calculate the
total
//and the ( = ) assignment operator to assign the value to the
var
var total = quantity * applePrice;
//use if to check the total is entitled to a discount
//if total is greater or = to 10 it's entitled
if (total >= 10)
{
alert("You're entitled to a discount!");
//apply 5% discount on the total
//and assign it to discountedTotal var
//Take note: multiplication is in brackets because it has to
be
//performed before subtraction (remember the good old school
math?)
discountedTotal = total - (discountRate * total);
//create a var to store text to display to user
var infoText = "You'll get your delicious apples at $" +
discountedTotal;
//you add more text to the same infoText var with a shortcut
assignment operator
//this technique is useful when you have long text strings to
manipulate
infoText += " instead of at $" + total;
//display message to the user
document.write(infoText);
}
</script>
</body>
</html>
Save your work, run the page in the browser, and enjoy your discount!
Questions, questions, questions
It's almost like I can hear you saying something like:
Hey, what's going on there? What's that += sign all about?
Here's the answer:
Shortcut operators
When you add several values to a variable, a shortcut operator is very handy.
The expression x += 2 is the same as x = x + 2.
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.
Handy shortcuts are also available to all other mathematical operators:




-=
*=
/=
%=
Try out: check product price with if ... else
Just after the closing curly brace } from the previous example, add the following snippet.
else
{
alert("Sorry, you're not entitled to a discount");
var infoText = "Your delicious apples cost $" + total;
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.
//if the total equals to 8
else if (total == 8)
{
alert("Just add a couple more apples and get your discount!");
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.
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">
//pick a day of the week and store it in a var
var today = "Friday";
//check today var value and act accordingly
switch(today)
{
//in case value corresponds to Saturday or to Sunday do this:
case "Saturday":
case "Sunday":
alert("It's the weekend: great!");
document.write("Today is " + today);
//no need to keep going:
break;
//in case value corresponds to Friday do this
case "Friday":
alert("Almost weekend time!");
document.write("Today is " + today);
//no need to keep going
break;
//in all other cases do this instead
default:
alert("Just an ordinary weekday: keep up the good work");
document.write("Today is " + today);
}
</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.
Lesson 7: Leave Boring Repetitive Stuff
to JavaScript with loops
By Maria Antonietta Perna
Your JavaScript scripts can do all sort of clever stuff like calculating discounts, comparing
values, and making choices. However, don't forget we're dealing with machine language,
and machines are very good at doing some things us humans would keep a mile off if only
we could.
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.
Here's what you will learn in this lesson:



the for loop;
the while loop;
the do ... while loop.
In the process, you will also learn how to:



use getElementById(element Id) to manipulate an HTML element with JavaScript;
generate random numbers with random() and floor(number);
insert HTML mark-up dynamically with innerHTML.
This is going to be a meaty lesson. Get ready for it!
Loops
At times you will have to repeat some piece of code a number of times:
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.
Any loop is made of 4 basic parts:
1. the start value
An initial value is assigned to a variable, usually called i (but you can call it anything
you like). This variable acts as counter for the loop.
2. the end value or test condition
The loop needs a limit to be set: either a definite number (loop 5 times) or a truth
condition (loop until this condition evaluates to true). Failing this, you run the risk of
triggering an infinite loop. This is very bad: it's a never-ending repetition of the same
code that stops users' browsers from responding. Avoid infinite loops at all costs by
making sure you set a boundary condition to your loops;
3. the action or code to be executed
You type a block of code once and it'll be executed the number of times
between your start value and end value;
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.
The for Loop
This kind of loop, well ... loops through a block of code a set number of times. Choose a for
loop if you know in advance how many times your script should run.
Here's its basic structure:
//loop for the number of times between start value
//and end value.
Increment the value each time
//the limit has not been reached.
for (var=startvalue; var<=endvalue; var=var+increment)
{
//code to be executed
}
The while Loop
If you don't know the exact number of times your code is supposed to execute, use a while
loop.
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.
Here's its basic structure:
//loop while initial value is less than or equal to end value
//Take note: if the condition evaluates to false from the
start,
//the code will never be executed
while (variable <= endvalue)
{
//code to be executed
}
do ... while Loop
This kind of loop is similar to the while loop. The difference between the two is this:
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.
Here's the basic structure of a do ... while loop:
//the command is given before the test condition is checked
do
{
//code to be executed
}
//condition is evaluated at this point:
//if it's false the loop stops here
while (variable <= endvalue)
Try out: add random number of images with
a for loop
Time to get coding: prepare a fresh HTML document with a div tag and an id of "wrapper"
and add the following JavaScript magic:
<!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">
//Grab the html div by its id attribute
//and store it in a var named container
var container = document.getElementById("wrapper");
//use Math.random to generate a random number
//between 0 and 1. Store random number in a var
var randomNumber = Math.random();
//use Math.floor() to round off the random number
//to an integer value between 0 and 10 and store it in a var
var numImages = Math.floor(randomNumber * 11);
//just for testing purposes, lets alert the resulting random
number
alert(numImages);
//the loop will run for the number of times indicated
//by the resulting random number
for (var i=1; i <= numImages; i++)
{
//code to be executed:
//create a var and store a string made of a new HTML img
element
//and the iteration variable i (use + concatenation operator):
//i contains the iteration number
//Take note:make sure the img src corresponds to a real image
file
var newImage = '<img src="loop.gif" alt="#" />' + i;
//use the container var that stores the div element
//and use innerHTML to insert the string stored in the
newImage var
//Use shortcut assignment += so previous values do not get
wiped off
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.
Questions, questions, questions
I know, there's a lot to ask about the code sample above. More specifically: 1) What's
this document.getElementById(element Id)? 2) What areMath.random() and
Math.floor(number)? And finally, 3) what's innerHTML? Let's tackle each question in turn:
1. Get hold of HTML elements
with document.getElementById(element Id)
JavaScript can perform all sorts of magic on any HTML element once it gets hold of
it. This can be done in more than one way. However, the most straightforward way is
by using 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.
2. Generate random numbers with Math.random() and
Math.floor(number)
JavaScript has built-in commands to perform complex mathematical operations
quickly and easily.
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.
Math.floor(number) rounds a number downwards to the nearest integer, and
returns the result. The JavaScript interpreter reads it as follows:
"Hey browser, take the number in brackets and round it down to the nearest integer
number."
Try it out on your own by typing var roundedNumber = Math.floor(6.2);
alert(roundedNumber); inside a <script> tag. Keep changing the number in brackets
and see how JavaScript returns the corresponding integer number.
In the previous example, you used Math.floor() together with Math.random(number)
to generate a random integer number between 0 and 10 (you typed 11 rather than 10
because the round number returned by Math.random() starts at 0 not 1).
3. Add new mark-up inside HTML elements with innerHTML
A JavaScript script can make HTML elements appear and disappear, change place
or color, and much more.
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.
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">
//Grab the html div by its id attribute
//and store it in a var named container
var container = document.getElementById("wrapper");
//create the var containing the counter
//and give it an initial value of 0
var numImages = 0;
//start the loop: while the number of images is less than or
//equal to 10 (loop starts at 0 not 1, so type 9 not 10),
//keep cycling and increase the counter by 1
while (numImages <= 9)
{
//this is the block of code to be executed:
//build the string to insert in the HTML document
//and store it in the newImage var
//Take note:make sure the img src corresponds to a real image
file
var newImage = '<img src="loop.gif" alt="#" />' + numImages;
//use the container var that stores the div element
//and use innerHTML to insert the string stored in the
newImage var
//Use shortcut assignment += so previous values do not get
wiped off
container.innerHTML += newImage;
//increase the counter by 1 using the increment operator
numImages ++;
}
</script>
Show example
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.
Run a while loop with a false condition
Now make just a small change to the code above: replace var numImages = 0; with var
numImages = 12;. Now the initial condition is false from the start: the counter is a
number greater than 10.
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.
Try out: add images to the page with a do ...
while loop
Use the same HTML document as the previous example. Also, the JavaScript code is very
similar to the previous example: simply move the while (condition) outside the action block
and type do in its place, like the example below:
<script type="text/javascript">
var container = document.getElementById("wrapper");
var numImages = 0;
do
{
//this block gets executed first:
var newImage = '<img src="loop.gif" alt="#" />' + newImage;
container.innerHTML += newImage;
numImages ++;
}
//here's the condition to evaluate:
//the first cycle has already executed.
while (numImages <= 9);
</script>
Show example
Save your work and run the page in the browser. You should see something similar to the
example page indicated in the link above.
Run a do ... while loop with a false condition
Make just a small change to the code above: once again, replace var numImages =
0; with var numImages = 12;. Now the initial condition is false from the start: the counter
is a number greater than 10.
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.
Lesson 8: Package your JavaScript
Code with Functions
By Maria Antonietta Perna
You can already add quite a bit of JavaScript functionality to web pages, and that's great.
However, what if you decide to implement the same kind of functionality on more than one
page, or in different places on the same page?
This is where JavaScript functions come into play.
In this lesson, you will learn:




what functions are and how they are used in JavaScript;
how to retrieve information from functions;
how to give information to functions;
what variable scope is all about.
In the process you will also learn how to:


get today's date dynamically;
change the value of an HTML button element dynamically.
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.
This suggests that there are 2 distinct phases to a function:
1. The phase where the function is declared (created);
2. The phase where the function is called (used).
Let's go through each phase in turn.
Declare a function
The basic structure of a JavaScript function looks like this:
//keyword function followed by your
//chosen name for the function
//Don't forget the round brackets!
function functionName()
//the code block is inside curly braces
{
//code you want to run goes here
}
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:
//Type the function name (without the keyword function)
//Don't forget the round brackets!
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!
Try out: declare your function
Prepare a simple HTML page like the one below. The program we're going to build has the
following goals:



to get today's date dynamically when the user clicks a button;
to display today's date on the web page;
to change the value attribute of the button after it's clicked: to have the button still
displaying Get Date after the date has been displayed looks a bit confusing to the
user.
<!DOCTYPE html>
<html>
<head>
<title>Lesson 8: Declare a function</title>
</head>
<body>
<h1>Lesson 8: Declare a function</h1>
<div>
<h2>Today's date is:</h2>
<span id="calendar"></span>
<input type="button" id="myButton" value="Get Date" />
</div>
<script type="text/javascript">
//Declare your function here
function showDate()
{
//the block of code starts here:
//First get all your vars ready
//This is how JavaScript retrieves today's date
var today = new Date();
//get hold of the calendar span element
//where today's date will be inserted
var myCalendar = document.getElementById("calendar");
//get hold of the button:you need this when it comes
//to change its value attribute
var myButton = document.getElementById("myButton");
//insert the date in the span element.
//toDateString() changes the date just retrieved
//into a user-friendly format for display
myCalendar.innerHTML = today.toDateString();
//change the value attribute of the button
//to say something more appropriate once the date is displayed
myButton.value = "Well done!";
}
</script>
</body>
</html>
Try out: call your function
If you review your program's goals as set out at the beginning, you'll see that all the action
takes place after the user clicks the button on the page. This tells us that we need
to handle the button's onclick event.
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 theHTML element onclick attribute.
Just add an onclick attribute to the button element and plug your showDate() function right in
there, like so:
<input type="button" id="myButton" value="Get Date"
onclick="showDate();" />
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.
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.
1. What's new Date() all about?
The new keyword creates a new instance of a JavaScript object, in this case a
Date object based on the user's computer clock. Objects are the topic of the next
lesson, and the Date object is the topic of lesson 11. Therefore, I keep things really
short at this point.
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.
2. Why did I use toDateString() with the date?
Following on from the previous point, toDateString() is only one of the numerous
methods you can use with the Date object. The JavaScript interpreter reads it as
follows:
"Hey browser, take the date you've been attached to and make it a bit more humanfriendly!"
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):
Sun Nov 06 2011 14:45:30 GMT+0000 (GMT Standard Time)
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():
Sun Nov 06 2011.
Much better, less scary, and far more readable for us humans.
Feed information to and retrieve information
from a function
Functions manipulate data: the alert() function has messages to display as its data, the
write() function has text to write on the web page as its data, etc.
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.
Here's what the basic structure looks like:
function functionName(arg1, arg2, arg3)
{
//body of the function goes here
}
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 andreturns 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.
Declare a function with a parameter
Prepare a simple HTML page and type the following JavaScript code within <script> ...
</script> tags:
<!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">
//declare a function with two arguments of type number
function addNumbers(num1, num2)
{
//this is a simple function:
// just return the sum of the two number arguments
return num1 + num2;
//your function ends here
}
</script>
</body>
</html>
Call your function and use its return value
Continue on from the previous code. Outside your function, just after the } closing curly
brace, type the following:
//Call your function: create a var
//and assign the value returned by your function to it
//Also, give a value to the number arguments
//by typing 2 comma-separated numbers within brackets
var total = addNumbers(3, 5);
//Display the returned data on the page
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.
Variables inside and outside functions: scope
A variable can have local or global scope on the basis of whether it's declared inside or
outside a function block.. But, what does this mean exactly?
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:
//create 2 global variables
var message = "outside global message";
var otherGlobalVariable = "other global variable";
//create a function with a local variable
//having the same name as the first global variable
function getMessage()
{
var message = "inside local variable";
//the function alerts the message variable
alert(message);
//and it also alerts the second global variable
alert(otherGlobalVariable);
//the function ends here
}
//call the function
getMessage();
//alert the message variable
//(which one will it be, local or global?)
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.
Lesson 9: A Gentle Introduction to
Objects
By Maria Antonietta Perna
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.
Here is what you will learn:



the concept of object in web programming;
what object properties are;
what object methods are.
What is an object in Geeky talk?
Real world objects are things like books, cars, balls, etc. We humans deal with the world
around us by interacting with and manipulating things, that is, objects.
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.
Properties and methods
But how exactly does JavaScript manipulate objects?
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 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.
How do you associate an object with a
property or a method?
If you wondered what that odd-looking ( . ) dot notation
in document.write() or Math.random(), and so on, meant in previous lessons, here's the
answer.
You use the object.property and object.method syntax to interact with JavaScript objects.
//use the random() method of the Math object
Math.random();
//use the write() method of the document object
document.write();
//use the length property of the string object
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.
Lesson 10: JavaScript Objects - Strings
By Maria Antonietta Perna
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 String object
You've had plenty of practice with the string object through this tutorial. In fact, the
JavaScript interpreter reads any piece of text enclosed in quotes ' ' (or double quotes " ") as
an instance of the string object. This puts the magic of all the properties and methods
belonging to the string object in our hands.
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, nothow 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.
Let's have a taste of such power.
How to use length
The length property of the string object contains the number of characters (including
spaces) in the text value of a string.
Here's a basic code snippet to demonstrate its use:
//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the length property to the string
document.write(myString.length);
//JavaScript will print 16:
//spaces are included in the count
//If the string is empty length returns 0
Try out for yourself: insert the code above between enclosing <script> tags and have fun
experimenting with it.
How to use toUpperCase()
The toUpperCase() method of the string object turns the text value of a string into, well ...
uppercase letters. Its companion toLowerCase() does the opposite: it turns the text value of
a string into lowercase letters.
Here's a basic code snippet to demonstrate its use:
//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the toUpperCase() method to the string
document.write(myString.toUpperCase());
//JavaScript will print HELLO JAVASCRIPT
//Try using myString.toLowerCase() on your own
Have a try: insert the code above between enclosing <script> tags and switch uppercase into
lowercase.
How to use match()
The match() method of the string object is used to search for a specific value inside a
string.
Here's a basic code snippet to demonstrate its use:
//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the match() method to the string.
//match(stringToMatch) takes the value to search for as
argument
document.write(myString.match("JavaScript"));
//JavaScript will print JavaScript
//If no match is found the method returns null
Experiment on your own: insert the code above between enclosing <script> tags and try
matching different string values.
How to use replace()
The replace() method of the string object is used to replace a value for another value
inside a string.
Here's a basic code snippet to demonstrate its use:
//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the replace() method to the string.
//replace() takes 2 arguments and returns the new string
value:
//replace(valueToReplace, newValue)
document.write(myString.replace("JavaScript", "World"));
//JavaScript will print Hello World
Have a go: insert the code above between enclosing <script> tags and try replacing different
string values.
How to use indexOf()
The indexOf() method of the string object is used to know the position of the first found
occurrence of a value inside a string.
Here's a basic code snippet to demonstrate its use:
//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the indexOf() method to the string.
//indexOf() takes in the value to look for in the string as
argument
//and returns the position number (index)
//indexOf(valueToFind)
document.write(myString.indexOf("Java"));
//JavaScript will print 6
//indexOf() includes spaces and starts counting at 0
//if no value is found the method returns -1
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.
Try out: guessing game
You're going to build a simple guessing game application using all the new knowledge you've
acquired in this lesson. Your application is expected to check a name entered by the user
and respond accordingly:
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>
<h2>What's the name of the wizard boy in J.K. Rowling's
novels?</h2>
<p>Your answer: <input type="text" id="txtName" /></p>
<p><input type="button" value="Submit your answer"
id="btnAnswer" />
<p id="message"></p>
</body>
</html>
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:
//This is the function that initializes our program
function init()
{
//Store a reference to the HTML button element in a variable:
//use the id of the HTML button element to do this
var myButton = document.getElementById("btnAnswer");
//use the onclick event of the button
//and assign the value of the getAnswer() function to it.
//This function performs the main job in your application
//and runs after the user clicks the button on the page.
//Take note: getAnswer is assigned without brackets.
//This is so because otherwise getAnswer() would be called
//as soon as the page loads (and we don't want that).
myButton.onclick = getAnswer;
//the init function ends here
}
//Assign the init() function to the onload event:
//this event fires when the HTML page is loaded in the
browser.
//Take note: init is assigned without brackets
onload = init;
//Now write the getAnswer() function
function getAnswer()
{
//Create all the vars you need to manipulate your data:
//secretName stores the correct answer the user is expected to
guess:
var secretName = "Harry Potter";
//Turn the value of secretName into lower case:
//you do this because you're going to compare this value
//to the value entered by the user of your application.
//Given that users might type the answer either in upper or
lower case,
//reducing the relevant text values to the same casing
automatically
//ensures that only the content and not also the letter case
plays a role in the comparison.
var secretNameLower = secretName.toLowerCase();
//Get the value the user types into the textbox
var myTextBox = document.getElementById("txtName");
var name = myTextBox.value;
//Also turn the value entered by the user to lower case
var nameLower = name.toLowerCase();
//Get a reference to the HTML paragraph that will display your
result
//after the script has run by storing its id value in a var
var message = document.getElementById("message");
//These are the test cases your application needs to evaluate
//and respond to: if the user clicks the button but did not
//enter any value in the textbox:
if(nameLower.length <= 0)
{
alert("I didn't quite catch your answer.
Please enter an
answer");
}
//If the user gets right the first half but not the latter
half of the name:
//Take note of the use of the logical operator &&
//(go back to lesson 5 if you need to revise logical
operators)
else if(nameLower.indexOf("harry") == 0 &&
nameLower.indexOf("potter") == -1)
{
alert("Almost there: think again");
}
//If the secret name and the name entered by the user match:
else if(nameLower.match(secretNameLower))
{
alert("You got it!");
message.innerHTML = "Congratulations, you win!";
}
//Default case - if the user types in the wrong answer:
else
{
alert("Wrong!");
message.innerHTML = "Sorry.
The correct answer is: ";
message.innerHTML += name.replace(name, "Harry Potter");
}
//the getAnswer() function ends here
}
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 corresponding value inside the string), you get an alert letting you know that
your answer is almost right.
If you enter the correct answer, well you'll get a prize.
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.
Lesson 11: JavaScript Objects - Date
Object
By Maria Antonietta Perna
In the previous lesson, you had a go at manipulating text by taking advantage of
the powerful properties and methods of the String object.
Here we continue to explore the power of JavaScript objects: we will be looking into the
magical virtues of the Date object.
Here's what you will do in this lesson:



create a Date object;
set dates;
compare dates.
The Date object
In lesson 8 you learned how to retrieve the current date and display it on the web page in
user-friendly format. This could be done dynamically thanks to the JavaScript goodness
offered by the Date object.
The Date object exposes plenty of methods to manipulate dates and times, some of which
we're going to examine here.
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.
Create a Date object
You create a date object by using one of the following ways:
//First way:
//the var today is initialized with a Date object
//containing the current date and time
//on the basis of the user's computer
//use toLocaleDateString() to adjust the date
//to the local time zone and format it
automatically
var today = new Date().toLocaleDateString();
//Second way:
//you pass a millisecond argument that starts at
1970/01/01:
//new Date(milliseconds)
var date = new Date(1000).toLocaleDateString();
//On my system this outputs: 01 January 1970
//Third way:
//You pass a string as argument:
//new Date(dateString)
var date = new Date("10 November,
2011").toLocaleDateString();
//On my system this outputs: 10 November 2011
Fourth way:
//new Date(year, month, day, hours, minutes,
seconds, milliseconds)
//only year and month are required,
//the others are optional arguments and
//where not present 0 is passed by default
//Below you pass the year in a 4-digit format,
and the month in number form:
//months are represented by numbers from 0
(January) to 11 (December)
var date = new Date(2011,
10).toLocaleDateString();
//On my system this outputs: 01 November 2011
After a Date object is created, you can use its methods to get and set dates and times.
Use getDate() to retrieve a date
//Create a Date object containing the current date and
time
var myDate = new Date();
//use getDate() to extract the
day of the month
document.write(myDate.getDate());
//At the time of writing, this prints 11
//days of the month range from 1 to 31
Use getTime() to retrieve a time
//Create a Date object containing the current date and
time
var myTime = new Date();
//use getTime() to extract the
time
document.write(myTime.getTime());
//At the time of writing, this prints 1321021815555
//This is the millisecond representation of the current
//date object: the number of milliseconds between
//1/1/1970 (GMT) and the current Date object
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.
Use getFullYear() to extract the year component
//Create a Date object containing the current date and
time
var myDate = new Date();
//extract the year component and print it on the page
document.write(myDate.getFullYear());
//At the time of writing, this prints 2011
Use getMonth() to extract the month component
//Create a Date object containing the current date and
time
var myDate = new Date();
//extract the month component and print it on the page
document.write(myDate.getMonth());
//At the time of writing, this prints 10
//which represents the month of November - months are
represented
//with numbers starting at 0 (January) and ending with
11 (December)
Use getDay() to extract the day component
//Create a Date object containing the current date and
time
var myDate = new Date();
//extract the day component and print it on the page
document.write(myDate.getDay());
//At the time of writing, this prints 5
//which represents Friday - days are represented
//with numbers starting at 0 (Sunday) and ending with 6
(Saturday)
Use getHours() and getMinutes() to extract time
components
//Create a Date object containing the current date and
time
var myDate = new Date();
//extract the hours component
var hours = myDate.getHours();
//extract the minutes component
var minutes = myDate.getMinutes();
//format and display the result on the page:
//check the minutes value is greater than 1 digit
//by being less than 10
if (minutes < 10)
{
//If it's just a one digit number, then add a 0 in front
minutes = "0" + minutes;
}
var timeString = hours + " : " + minutes;
document.write(timeString);
//Based on my computer clock, this prints:
//14 : 44
Set dates
You can also set dates and times as easily as calling the appropriate methods. Here are a
few examples.
Use setFullYear() to set a specific date
In this demo, you will set a specific date and then retrieve its day component for display
//Create a Date object containing the current date and
time
var myDate = new Date();
//set the Date object to a specific date: 31 October,
2011
var mySetDate = myDate.setFullYear(2011, 9, 31);
//Now retrieve the newly set date
var mySetDay = myDate.getDay(mySetDate);
//mySetDay will contain a number between 0 - 6 (Sunday Saturday).
//Use mySetDay as test case for a switch statement
//to assign the corresponding week day to the number
value
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;
}
//display the result on the page
document.write("The 31st October 2011 is a " +
mySetDay);
//If you check the date on a calendar, you'll find that
//the 31st Oct 2011 is indeed a Monday
Compare 2 dates
In this demo you will compare 2 Date objects.
//Create a Date object
var myDate = new Date();
//set the Date object to a specific date: 31 October,
2011
var mySetDate = myDate.setFullYear(2011, 9, 31);
//Create a second Date object
var now = new Date();
//Make the comparison: if the set date is bigger than
today's date
if (mySetDate > now);
{
//the set date is in the future
document.write("The 31st October is in the future");
}
//if the set date is smaller than today's date, it's in
the past
else
{
document.write("The 31st October is in the past");
}
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.
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.
In this lesson you will use:


Math.PI to calculate the circumference of a circle;
Math.sqrt() to calculate a square root value.
In the process, you will learn how to use:


parseInt()/parseFloat() to convert strings to numbers;
isNaN() to check whether a value is or is not a number;
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:



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.
PI is the ratio of the circumference of a circle to the diameter.
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:
//store and display the value of PI:
var pi = Math.PI;
document.write(pi);
Try out: use Math.PI to find out the
circumference of a circle
It's time for this lesson's first try out exercise. We're going to build a simple application where
the user enters a number representing the radius of a circle, clicks a button, and the program
calculates the circumference and displays it on the page.
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).
First things first: prepare an HTML document like this one:
<!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>Enter length of radius: <input type="text"
id="txtRadius" /></p>
<p><input type="button" id="btnSubmit" value="Calculate
circumference" /></p>
<p id="result"></p>
</body>
</html>
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.
//init() function binds the processAnswer() function
//to the onclick event of the button
function init()
{
var myButton = document.getElementById("btnSubmit");
myButton.onclick = processAnswer;
}
/*********************************************/
//Bind the init function to the onload event
onload = init;
/*********************************************/
//This function checks the user's input,
//calls the function that performs the calculation,
//and displays the result
function processAnswer()
{
//store a reference to the inputbox
var inputBox = document.getElementById("txtRadius");
//get the radius value entered in the inputbox
//make sure to convert the string (text) to a number:
//calculations can only be performed with numbers,
//and the value in the inputbox is processed as string.
//parseInt(string) and parseFloat(string)
//take a string as input and return an integer
//or a floating point number respectively.
var radius = parseInt(inputBox.value);
//get a reference to the paragraph to display result
var result = document.getElementById("result");
//create and initialize a var to store the result
var resultString = "";
//Perform some validation on the user's input:
//if the value entered by the user is not a number
//alert the user.
isNaN(value) takes
//a value as input and returns true if the value is not
a number,
//it returns false if the value is a number.
//the expression below is short for:
//if (isNaN(radius) == true)
if (isNaN(radius))
{
alert("Please, enter a number");
}
else
{
//if the user has correctly entered a number,
//call the function that performs the calculation
//and display the result on the page
var circ = getCircumference(radius);
resultString = "Circumference is: " + circ;
result.innerHTML = resultString;
}
}
/*********************************************/
//This is the function that performs the calculation:
//it takes the radius as input and returns the
circumference
function getCircumference(rad)
{
var circumference = 2 * (Math.PI * 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:
var squareRoot = Math.sqrt(25);
document.write("The square root of 25 is: " +
squareRoot);
//This should print:
//The square root of 25 is: 5
Try out: square root calculator
You will build a simple square root calculator. Here are the requirements for this little
application:



the user will be able to enter a number value into an inputbox;
the user will be able to click a button that calculates the square root of the number
entered into the inputbox;
the result will be displayed on the web page.
Create a fresh HTML page with an inputbox, 1 button, and a paragraph where the result will
be displayed. These HTML elements contain id attributesthat 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>Enter a number: <input type="text" id="txtNumber"
/></p>
<p><input type="button" id="btnSubmit" value="Calculate
square root" /></p>
<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.
//write the function to initialize the script
function init()
{
//Bind function that processes the result to
//the onclick event of the button
var myButton = document.getElementById("btnSubmit");
myButton.onclick = displaySquare;
}
/**************************************************/
//Bind the init() function to the onload event
onload = init;
/**************************************************/
//Here we call the function that performs
//the square root calculation, then we format and
//display the result
function displaySquare()
{
//we store the value from the inputbox into a var.
//Notice how we concatenate several methods
//in one statement (be careful with those brackets).
//If you find it a bit confusing, store a reference to
the inputbox
//in its own var and then use it to extract its value
property
//and finally pass it as argument of parseInt(), like
so:
//var inputBox = document.getElementById("txtNumber");
//var inputVal = parseInt(inputBox.value);
var inputVal =
parseInt(document.getElementById("txtNumber").value);
//we store a reference to the paragraph
//where the result will be displayed
var result = document.getElementById("result");
//we create the var that stores the result message
var resultMessage = "";
//we ensure the input value is a number:
//if the user did not enter a number, we send an alert
if (isNaN(inputVal))
{
alert("Please, enter a number");
}
else
{
//If the input is in correct format, we call
//the function that performs the calculation
var squareVal = calculateSquare(inputVal);
//this is a nested if statement: it's inside another
//if statement to perform further checks:
//if squareVal stores a value (if the calculation was
successful) //- this is short for: if (squareVal == true)
if (squareVal)
{
//we build this message to the user:
resultMessage = "Square root of " + inputVal + " is " +
squareVal;
}
//else, that is, if the calculation was not successful
else
{
//we build a different message to the user:
resultMessage = "Sorry, an error occurred";
}
}
//finally, we display the message using innerHTML
result.innerHTML = resultMessage;
}
/**************************************************/
//This function calculates the square root:
//it takes in the number entered by the user
//and returns the result of the calculation
function calculateSquare(input)
{
var squareVal = Math.sqrt(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.
Lesson 13: JavaScript Objects - Arrays
By Maria Antonietta Perna
Just using a few properties and methods of common JavaScript objects has opened your
eyes to the amazing things that Object Oriented Programming enables you to accomplish
with a few lines of code. In this lesson, you will learn to use what is a very powerful object in
most programming languages, including JavaScript of course: the Array object.
In particular, in this lesson you will learn:



what the Array object is for;
how to create arrays;
how to access, sort, add, and remove data inside an array.
In the process, you will learn how to use the for ... in loop to access data inside an array.
What is the Array object for?
An object's job is that of storing and allowing for the easy manipulation of data. We can
safely say that the Array object performs both tasks wonderfully.
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.
How do you create an Array object?
You create an array in 1 of 3 ways:
1) use new Array()
This is the most verbose approach. It works as follows:
var colors = new Array();
colors[0] = "green";
colors[1] = "red";
2) use new Array(item0, item1, item2 ...)
This approach also employs the new Array() constructor, but does so using a more concise
formulation. Here's what it looks like:
var colors = new Array("green", "red");
3) use the literal array approach
This is the shortest way of creating and populating an array, and it's the most widely used
approach. It looks like this:
var colors = ["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.
Here's what I mean.
How do I access data inside the Array object?
Arrays are great to store several values using only 1 variable. However, they wouldn't be so
great if you couldn't also access those values quickly and easily. Here's how it's done:
//"green" is at index position 0, "red" is at index
position 1, etc.
var colors = ["green", "red", "yellow", "orange",
"blue"];
var red = colors[1];
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.
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:
//use the array from the previous example
var colors = ["green", "red", "yellow", "orange",
"blue"];
//use a for loop to access each item in colors
//The array object has a length property
//that contains the size of the array: you can use it in
the for loop
for (var i=0; i < colors.length; i++)
{
//You use the counter i to access the index position
document.write(colors[i] + "<br />");
}
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:
//use the array from the previous example
var colors = ["green", "red", "yellow", "orange",
"blue"];
for (color in colors)
{
//color is the variable that marks the index position
document.write(colors[color] + "<br />");
}
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.
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:
var colors = ["green", "red", "yellow", "orange",
"blue"];
colors[2] = "pink";
//Now you've replaced the item at index position 2,
//the third item called "yellow",
//with "pink"
document.write(colors);
//The code should print:
//green,red,pink,orange,blue ("pink" has replaced
"yellow")
Can I sort array items?
You can do amazing stuff with values stored inside an array. For example, you can sort
items alphabetically, in descending or ascending order, or numerically. Let's see how this is
done.
You sort array elements with a fantastic method most appropriately called sort(). Here it is in
action:
//sort the colors array alphabetically and ascending:
var colors = ["green", "red", "yellow", "orange",
"blue"];
var ascendingColors = colors.sort();
//display each value
document.write(ascendingColors);
//This should print:
//blue, green, orange, red, yellow
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:
//build a new array containing number values
var myNumbers = [4, 2, 10, 6, 9];
//build your custom function: this is a simple formula
function sortAscending(a, b)
{
//the formula return a - b sorts the numbers
//from the smaller to the bigger,
//the formula return b - a sorts numbers in descending
order,
//that is, from the bigger to the smaller number
return a - b;
}
//pass the sortAscending function as argument to sort()
var sortedAscending = myNumbers.sort(sortAscending);
//print result on the page
document.write(sortedAscending);
//This should print:
//2,4,6,9,10 .
Now try sorting in descending order on
your own.
How do I add data to the Array object?
You can add new items inside an array in different ways. Which method you choose
depends largely on your program's requirements.
Add items to the end of the array with push()
What feels more like the natural order of things, that is, adding an item to the end of an array,
is easily achieved using the push() method. Here's how it works:
//use our old colors array
var colors = ["green", "red", "yellow", "orange",
"blue"];
//use push() to add the color "pink" at the end
colors.push("pink");
//print the enlarged array
document.write(colors);
//This should print:
//green,red,yellow,orange,blue,pink
Add items to the beginning of an array with unshift()
Use unshift() to add new items to the start index position of an array. This is easily done.
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.
How do I remove data from the Array object?
If you want to remove the last item in an array you use pop(). If you want to remove the first
item in an array you use shift().
var colors = ["green", "red", "yellow", "orange",
"blue"];
//remove "blue" from colors
colors.pop();
document.write(colors);
//This prints: green,red,yellow,orange
//remove "green" from colors
colors.shift();
document.write("<br />" + colors);
//This prints: red,yellow,orange
//on a new line break
Have fun experimenting with the examples above and come back to our try out challenge as
soon as you're ready.
Try out: Username registration
You will build a mock Username registration program with the following requirements:



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.
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.
The HTML document
<!DOCTYPE html>
<html>
<head>
<title>Lesson 13: JavaScript Objects - Arrays</title>
<script type="text/javascript"
src="lesson13_tryout.js"></script>
</head>
<body>
<h1>Lesson 13: Register with us</h1>
<p>Register a Username: <input type="text" id="txtName"
/></p>
<p><input type="button" id="btnSubmit" value="Register"
/></p>
<p id="result"></p>
</body>
</html>
The JavaScript file: lesson13_tryout.js
Your program contains:



a global array called userNames used to store Usernames;
a function called init() used to bind the main function to the onclick event of the
button;
and a function called registerName() that performs all the main program tasks.
//global array: it's outside any function
var userNames = ["harry potter", "donald duck", "shrek",
"supercoder"];
/*******************************/
//init() function
function init()
{
var myButton = document.getElementById("btnSubmit");
myButton.onclick = registerName;
}
//assign init() function to onload event
onload = init;
/********************************************/
//registerName() function: it executes when user clicks
the button
function registerName()
{
//set up main vars: Username entered by user,
//a message string to communicate with the user,
//a reference to the paragraph used to display the
message,
//and a boolean var (true/false) used as flag:
//if the registration is successful, this is set to
true,
//if registration fails, this is set to false. It's
initialized as false.
//Notice how you chain getElementById(), value, and
toLowerCase
//to store the value entered by the user in lowercase
var newName =
document.getElementById("txtName").value.toLowerCase();
var message = "";
var result = document.getElementById("result");
var success = false;
//If the user clicks the button but the inputbox is
empty
//we alert the user and stop further program execution:
if (newName == "")
{
alert("Please, enter a Username");
return false;
}
//we loop over each Username stored in the array
//to make sure the Username is not already in existence
for (var i = 0; i < userNames.length; i++)
{
//if we find a Username equal to the newly entered name,
//it means the Username already exists and we can't
//proceed with registration
if (userNames[i] == newName)
{
already exists.
message = "Sorry, the Username " + userNames[i] + "
Try again";
result.innerHTML = message;
//set the success flag to false so the rest of the
program knows
//that registration failed
success = false;
//stop further program execution
return false;
}
//else - if the Username entered by the user
//is not already stored in the application, register new
user:
else
{
message = "Great, you've successfully registered with us
as " + newName;
result.innerHTML = message;
//set the success flag to true, so the program knows
//the new Username can be added
success = true;
}
}
//Now you're out of the loop
//if registration was successful (success flag is true),
//add new Username to the array with push()
if (success)
{
userNames.push(newName);
}
//display Usernames sorted alphabetically on a new line
result.innerHTML += "<br />" + userNames.sort();
}
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, thebrowser.
Lesson 14: JavaScript Living Space the Browser Environment
By Maria Antonietta Perna
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.
In particular, you will learn about:



the Browser Object Model (BOM);
the Document Object Model (DOM);
accessing, adding, and removing DOM elements and attributes.
What is the Browser Object Model (BOM)?
The BOM is a a collection of objects that represent the browser and the computer screen.
These objects are accessible through the global objectswindow and window.screen.
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).
What is the Document Object Model (DOM)?
One of the most interesting children of the window object, certainly from the point of view of
JavaScript, is the Document object. This gives access to the all the elements that make up
your HTML document.
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:
//Set up your variables to represent
//bits of info about your document:
var myTitle = document.title;
var myUrl = document.URL;
var myLastModification = document.lastModified;
var myInfoString = "The title of my document is: " +
myTitle + "<br />";
myInfoString += "My document's URL is: " + myUrl + "<br
/>";
myInfoString += "My document was last modified on: " +
myLastModification;
document.write(myInfoString);
That's so cool. Let's have a look at how the HTML page is represented in the DOM.
What does a DOM representation of an HTML
page look like?
The DOM represents HTML elements in a top-down tree-like structure. For instance, let's
consider the following simple HTML document:
<html>
<head>
<title>Lesson 14: DOM</title>
</head>
<body>
<p>Lorem ipsum ...</p>
<p>Lorem ipsum ...</p>
<p>link <a href="http://html.net">HTML.net</a></p>
</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:
1. The <html> node
The <html> element or node, is parent to all other nodes. In fact, all other DOM
nodes are nested inside the <html> node;
2. <head> and <body> nodes
Next, we find 2 elements: the <head> and the <body>. These have a parent/child
relationship with the <html> element (the parent). Because both are on the same
level, they're siblings with respect to each other;
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.
How do I access DOM elements?
Use one of the 2 following methods of the document object to access DOM elements.
Get the DOM element by its id attribute
The most widely used method of the document object to access DOM elements is
certainly our old friend document.getElementById(elementId). This is the most appropriate
way of accessing 1 HTML element at a time.
var inputBox = document.getElementById("txtHello");
alert(inputBox);
//if you run this code in an HTML page containing
//an input element called txtHello, you should see
//[object HTMLInputElement] displayed in an alert box.
Get DOM elements by tag name
Another popular way of accessing DOM elements is by using their tag name in the HTML
mark-up. This is a handy way of grabbing all HTML elements in one go that have a tag name
in common, such as images, links, list items, etc. You can store a reference to these
elements in an array and manipulate them via JavaScript.
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:
//Retrieve all 3 list items and store them in an array
var listElems = document.getElementsByTagName("li");
//loop over each list item and access the style property
for (var i = 0; i < listElems.length; i++)
{
//Notice how you write backgroundColor,
//NOT background-color as you would in CSS:
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.
How do I add DOM elements?
In previous lessons you used the practical and easy innerHTML property of an HTML
element to add new stuff to your web page, be it new mark-up or new text.
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:
//First create a <p> element with
createElement(element):
var newParagraph = document.createElement("p");
//Then add <p> to the <body> tag with appendChild():
document.body.appendChild(newParagraph);
//Now create the text that goes inside the new <p>
element
//with createTextNode():
var newTextPara = document.createTextNode("Hello DOM
standard");
//Finally, add the new text inside the <p> tag:
newParagraph.appendChild(newTextPara);
You can also add attributes to the newly created DOM nodes with setAttribute(attrType,
attrName), and later retrieve them withgetAttribute(attrType). Using the code snippet
above, you can add an id called newParagraph to the newly created paragraph like so:
var newParagraph = document.createElement("p");
//setAttribute has 2 string arguments: the attribute we
want to set
//and the name we want to apply to the attribute.
//Here we create an id attribute called newParagraph:
newParagraph.setAttribute("id", "newParagraph");
document.body.appendChild(newParagraph);
var newTextPara = document.createTextNode("Hello DOM
standard");
newParagraph.appendChild(newTextPara);
//getAttribute() has one string argument: the type of
attribute
//we want to retrieve:
alert("The Id of the new paragraph is: " +
newParagraph.getAttribute("id"));
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 standardcompliant.
How do I remove DOM elements?
That's pretty simple stuff. First grab the DOM node you want to remove, then
use removeChild(elementToRemove).
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>
<p id="remove">I'm going to be removed.</p>
<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()
{
//retrieve the element you want to remove:
var remove = document.getElementById("remove");
//use removeChild(elementToRemove) to delete the element
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 standardcompliant 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.
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 this lesson, you will learn:



what a cookie is;
how you can store cookies on your website visitors' computer;
how you can retrieve the cookie and use the values stored in it on the web page.
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.
This is where cookies enter the scene.
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.
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, thatexpires after a minute starting
from the time of its creation:
//If no cookie is present, we create one
if (! document.cookie)
{
var cookieName = "Test Cookie";
//escape the string to make sure there are
//no unallowed characters
var myCookie = escape(cookieName);
//set the expiry date to 1 minute from creation date:
//get current date and add 1 minute reduced to
milliseconds:
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (60 * 1000));
//create the myCookie cookie and add it
//to the cookie property of the document object:
//in name=value pairs separated by ;
document.cookie = "myCookie=" + myCookie + ";" +
"expires=" + expiryDate.toGMTString() + ";";
//leave a message to the user:
document.write("Thank you, " + cookieName + " is your
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.
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.
//continue from the previous code snippet
else
{
var myCookieString = unescape(document.cookie);
//create a comma-separated array of substrings from the
string
//containing the cookie values by using
//split() with "=" as separator.
//Remember name/value pairs in the cookie
//string are separated by an = sign:
var dataList = myCookieString.split("=");
//check that the name at index position 0 is
//"myCookie" (remember the cookie name from previous
example):
if (dataList[0] === "myCookie")
{
//let's extract the value of myCookie
//by using split() once again.
Now the items in
//dataList array are separated by " , ".
//This will be our separator in the split() method.
//Item 1 (index 0) is the cookie name,
//item 2 (index 1) is the value, which is what we need:
var data = dataList[1].split(",");
//Now we have a new array of strings called data.
//containing only the cookie value ("Test Cookie"),
//which is at index 0.
We extract it:
var cookieName = data[0];
}
//Now we display a personalized greeting
document.write("Welcome back, here's your cookie, " +
cookieName);
}
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
Lesson 16: Useful Tasks (II) – Form
Validation
By Maria Antonietta Perna
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.
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.
In this lesson, you will learn how to:


make sure users fill out all required form fields;
make sure users enter a valid email.
How do I validate empty form fields?
In previous lessons you already performed some validation tasks. For example, you
used isNaN() to make sure users entered a number data type. You also checked users didn't
submit an empty value by using something like if (inputboxValue == "") { alert user...}.
Let's see what else you could do to prevent users from submitting an empty form field.
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>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">First Name:</label>
<input type="text" id="txtName" name="txtName" />
</p>
<p><input type="submit" value="Submit"
onclick="validate()" /></p>
</fieldset>
</form>
<script type="text/javascript">
</script>
</body>
</html>
In between <script> tags write the validate() function as follows:
function validate()
{
var userName = document.getElementById("txtName").value;
//if the length of the string value is 0,
//it means the user has entered no value:
if (name.length == 0)
{
alert("Please, enter your name");
return false;
}
else
{
alert("Thank you, " + userName);
}
}
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.
How do I validate email addresses?
Email addresses present a characteristic pattern. We know that they have one @
character and at least a dot ( . ) character.
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>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtEmail">Email:</label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit"
onclick="validate()" /></p>
</fieldset>
</form>
<script type="text/javascript">
</script>
</body>
</html>
Now, change the validate() function as follows:
function validate()
{
var email = document.getElementById("txtEmail").value;
//still check user entered a value
if (email.length == 0)
{
alert("Please, enter an email address");
return false;
}
//if the index position of the @
or . characters
//is -1 (any value bigger than this, including 0,
//means the character is present)
else if (email.indexOf("@") == -1 || email.indexOf(".")
== -1)
{
alert("Please, enter a valid email address");
return false;
}
//if we get here, all went well
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.
Try out: form validation demo
In this try out you will build a JavaScript program that checks user input (name and email)
before web form submission. Prepare an HTML page containing a form with 2 inputboxes
and a button, and add a paragraph with an id attribute called result to display messages to
the user, like the one below:
<!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>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">Name:</label>
<input type="text" id="txtName" name="txtName" />
<p><label for="txtEmail">Email:</label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<p id="result"></p>
</body>
</html>
Now create the lesson16.js file. This contains 5 functions:
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()
{
var myForm = document.getElementById("myForm");
myForm.onsubmit = validate;
}
/********************************/
//bind init() function to onload event
onload = init;
/******************************************/
//validate() checks answers from validateRequired()
//and validateEmail() and displays appropriate messages.
//If an error occurs program execution is stopped:
function validate()
{
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
//validateRequired() and validateEmail()
//return true/false values: create
//variables to store the result
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
//create variable that holds message to display
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
//if all values are valid, prepare thank you message
//and allow form submission
if (isRequiredNameSet && isRequiredEmailSet &&
isEmailValid)
{
message = "Thank you, your details have been
successfully posted!";
}
//if the name field is empty, write message to user and
stop submission:
else if (! isRequiredNameSet)
{
message = "Please, enter a name";
writeMessage(message);
return false;
}
//If the email field is empty, write message to user and
stop submission:
else if (! isRequiredEmailSet)
{
message = "Please, enter an email";
writeMessage(message);
return false;
}
//If the email is not in a valid format (no @ or .
characters),
//we write a message to the user and stop program
execution:
else if (! isEmailValid)
{
message = "Please, enter a valid email";
writeMessage(message);
return false;
}
//If we are here validation is successful:
//display the thank you message with an alertbox:
alert(message);
}
/***********************************************/
//This function takes an argument
//that represents the input element and checks
//that it's not empty - it returns true if input is
valid
//and false if input is not valid:
function validateRequired(input)
{
var isValid = false;
if (input.length == 0)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
/**********************************************/
//validateEmail(email) checks the email is in valid
//format and returns true if it is, false if it isn't:
function validateEmail(email)
{
var isValid = false;
if (email.indexOf("@") == -1 || email.indexOf(".") == 1)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
/**********************************************/
//writeMessage(text) has the message to
//display to the user as argument, clears any previous
//content from the paragraph with the id of result
//and inserts the appropriate message for display
//using DOM compliant techniques (lesson 14):
function writeMessage(text)
{
var paragraph = document.getElementById("result");
//The content inside the paragraph is the paragraph's
//first child.
We check if there is any content and
remove it:
if (paragraph.firstChild)
{
paragraph.removeChild(paragraph.firstChild);
}
//Now we can create and append the new
//message to display to the user:
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.
Lesson 17: JavaScript Timing Events
By Maria Antonietta Perna
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.
In this lesson, you will learn about:




setTimeout();
clearTimeout();
setInterval();
clearInterval().
In the process, you will also learn how to preload images with JavaScript and how to build
a simple photo gallery application.
How do I use setTimeout()?
If your program has a chunk of code that needs to be executed after a specified time,
then setTimeout(actionToExecute, timeInMilliseconds) is your function.
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:
//Package the code to insert in the
//timer in a simple function:
function sayHello()
{
alert("Hello");
}
//Package the timer into its own function
function timeGreeting()
{
//assign the timer to a variable:
//you need to do this so the timer can be
//referenced by another function when you want
//to stop it:
var greeting = setTimeout(sayHello, 2000);
//Notice how the time is set in milliseconds.
}
//Now call the timer function
timeGreeting();
Save your work and run it in a browser. After 2 seconds, an alertbox should pop up to greet
you.
How do I use setInterval()?
If you need to execute a chunk of code at specified time intervals,
then setInterval(codeToExecute, timeIntervalInMilliseconds) is your function.
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.
How do I stop the timer?
JavaScript offers 2 handy methods to get rid of timers: clearTimeout(timerVariable) if your
timer uses setTimeOut(), andclearInterval(timerVariable) if your timer uses setInterval().
Let's put clearInterval() to good use right away by stopping that annoying alertbox. First of
all, add an inputbox to your HTML page, like so:
<input type="button" value="Stop timer" onclick="stopTimer()" />
Next, rewrite the preceding JavaScript code and then add the new function as follows:
//Make the variable holding the timer
//global, so that it can be accessed both
//by the function setting the timer and by the function
//stopping the timer:
var greeting;
//sayHello() remains unchanged from the previous example
function sayHello()
{
alert("Hello");
}
//we increase the time interval
//to give more time to the user to
//click the button that stops the alert:
function timeGreeting()
{
greeting = setInterval(sayHello, 5000);
}
timeGreeting();
//package the code that cancels the timer
//in its own function that will be called when
//the button on the page is clicked:
function stopTimer()
{
//you call clearInterval() and pass the variable
//containing the timer as argument
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.
Try out: a photo gallery application
JavaScript timers are often used to produce animation effects on the web. Photo galleries
are one of those widely used applications that often employ JavaScript timers.
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 ownimages folder.
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">
<img src="images/1.jpg" alt="Photo gallery image"
id="photo" />
<input type="button" id="btnStart" value="Restart
gallery" />
<input type="button" id="btnStop" value="Stop gallery"
/>
</div>
<script type="text/javascript"
src="lesson17.js"></script>
</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.
//Global variables: a reference to the
//photo currently displayed on the page,
var curImage = document.getElementById("photo");
//a variable to store the timer,
var galleryStarter;
//a variable to store a true/false value indicating
//to the program whether the gallery is on or off,
var isGalleryOn = true;
//an array containing 4 strings representing the
filepaths
//to the image files in the images folder,
var images = ["images/1.jpg", "images/2.jpg",
"images/3.jpg", "images/4.jpg"];
//an empty array that will be filled with 4 preloaded
//image objects: the src property of these image objects
will correspond
//to the filepaths contained in the images[] array,
var preloadedImgs = [];
//a variable that works as our counter to
//advance from one image to the next.
It starts at 0.
var counter = 0;
/**************************************/
//Init() starts with the image preloading routine.
//First fill the preloadedImgs[] array with a
//number of image objects corresponding to the length
//of the images[] array:
function init()
{
for (var i = 0; i < images.length; i++)
{
preloadedImgs[i] = new Image();
}
//now assign the value of the strings contained in the
//images[] array to the src property of each image
object
//in the preloadedImgs[] array, using one more loop:
for (var i = 0; i < preloadedImgs.length; i++)
{
preloadedImgs[i].src = images[i];
}
//Now, assign event handlers to the 2 buttons
//to restart and stop the gallery:
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
btnStart.onclick = startGallery;
btnStop.onclick = stopGallery;
//Finally, check the isGalleryOn flag is true.
If it is
//call the function that starts the gallery:
if (isGalleryOn)
{
startGallery();
}
}
/*********************************************/
//Assign the init() function to the onload event
onload = init;
/***********************************************/
//startGallery() contains the functionality
//to extract the photos from the preloadedImgs[] array
//for display and to set the timer in motion:
function startGallery()
{
//extract the image filepath using the counter
//variable as array index and assign it to the src
//property of the curImage variable:
curImage.src = preloadedImgs[counter].src;
//advance the counter by 1:
counter ++;
//if the counter has reached the length of the
//preloadedImgs[] array, take it back to 0, so the
//photo gallery redisplays the images from the start:
if (counter == preloadedImgs.length)
{
counter = 0;
}
//Set the timer using this same function as one
//of the arguments and 2000 (2 milliseconds) as the
other argument.
galleryStarter = setTimeout("startGallery()", 2000);
//Signal that the gallery is on to the rest of the
program:
isGalleryOn = true;
}
/**************************************************/
//stopGallery() uses clearTimeout()
//to stop the gallery
function stopGallery()
{
clearTimeout(galleryStarter);
//signal that the gallery has stopped to the
//rest of the program:
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.
Questions, questions, questions
I imagine you might be wondering what this business of preloading images is all about.
Well, here's a short explanation.
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.
This is the image preloading routine simplified to the bare minimum:
//Create an Image object:
var myNewImage = new Image();
//assign the filepath of your desired image
//to the src property of the newly created image object:
myNewImage.src = "images/testimage.jpg";
//Now myNewImage has been preloaded: your
//JavaScript can use it, display it, etc. without fear
of
//having to wait too long for a server request.
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.
Lesson 18: Making AJAX Calls
By Maria Antonietta Perna
One core feature of 21st century web applications is their fantastic responsiveness. A
pioneer in the business of making the web more and more similar to a desktop application
has been Google: as soon as you start typing a character in a Google box, all kinds of
suggestions and search results keep popping up to speed up your search; and again, just
type something using Google maps, and you're instantly catapulted to almost any street on
the planet.
Behind this amazing feat of human cleverness is the coming together of a few technologies
collectively known as AJAX.
In this lesson you will learn:



what AJAX stands for and what it is all about;
how to make an AJAX request;
how to handle an AJAX response.
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.
What's AJAX all about?
The acronym AJAX stands for Asynchronous JavaScript And XML.
In actual fact, it's a combination of internet standards made up of:





standards-based presentation using HTML and CSS;
dynamic display using the DOM;
data interchange and manipulation using XML;
asynchronous data retrieval using the XMLHttpRequest object;
JavaScript magic to orchestrate the whole process.
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);
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.
AJAX helps in at least 2 respects: piecemeal page updates and asynchronous
communication between server and client.
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.
How do I make an AJAX request?
An AJAX request is made using the XMLHttpRequest object and its open() and send()
methods. This is supported by all major browsers. However, older browsers, namely older
varsions of Microsoft Internet Explorer (vesions 5 and 6), support an ActiveXObject. This
little hurdle is easily overcome by testing for feature support in the script.
The open(retrievalMethod, url, bool) method has 3 arguments:
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:





0) the request is uninitialized because open() has not been called;
1) the request is specified, but send() has not been called yet;
2) the request is being sent, because now send() has been called;
3) the response is being received, but not yet completed;
4) the response is complete and data is available for manipulation and display.
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:
//Global variable to store the XMLHttpRequest object
var myRequest;
//Package the request into its own function
function getData()
{
//Feature-testing technique to make sure the browser
//supports the XMLHttpRequest object
if (window.XMLHttpRequest)
{
//create a new instance of the object
myRequest = new XMLHttpRequest();
}
//else - the XMLHttpRequest object is not supported:
//create an instance of ActiveXObject
else
{
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
//Use the open(retrievalMethod, "myDataFile.txt", bool)
method
myRequest.open("GET", url, true);
//Use send() with a null argument - we have nothing to
send:
myRequest.send(null);
//attach a function to handle onreadystatechange,
//that is, the response from the server:
myRequest.onreadystatechange = getData;
}
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.
Here's a code snippet that illustrates this in practice.
//Package the response-handling code in a function
function getData()
{
//Make sure the response is at the completion stage (4):
if (myRequest.readyState ===4)
{
//if it is, make sure the status code is 200 (success):
if (myRequest.status === 200)
{
//if all is well, handle the response:
var text = myRequest.responseText;
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.
AJAX request - response example: plain text
response
To follow along, you need a server and 1 simple text file uploaded to the same server that
hosts your JavaScript code.
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.
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>
<h2 id="myHeader">Click the button to call your
data</h2>
<input type="button" value="Click Me!"
onclick="getText('lesson18_test.txt')" />
</div>
<script type="text/javascript">
//JavaScript AJAX code here
</script>
</body>
</html>
Here's the JavaScript code that goes in enclosing <script> tags in the HTML page above:
//Prepare the global variable for the request
var myRequest;
//Write the getText(url) function
function getText(url)
{
//check support for the XMLHttpRequest object
if (window.XMLHttpRequest)
{
myRequest = new XMLHttpRequest();
}
//else, create an ActiveXObject for IE6
else
{
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
//Call the open() method to make the request
myRequest.open("GET", url, true);
//Send the request
myRequest.send(null);
//Assign the getData() function to the
//onreadystatechange property to handle server response
myRequest.onreadystatechange = getData;
}
/**********************************************/
//This function handles the server response
function getData()
{
//Get a reference to the header element where
//the returned result will be displayed
var myHeader = document.getElementById("myHeader");
//Check the response is complete
if (myRequest.readyState ===4)
{
//Check the status code of the response is successful
if (myRequest.status === 200)
{
//Store the response
var text = myRequest.responseText;
//Assing the returned text to the nodeValue
//property of the header element (you can also use
//innerHTML here if you feel it simplifies your task)
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.
AJAX request - response example: XML
format response
The page you're going to build in this second example allows the user to click a button to
display a series of programming languages coming from an XML file using AJAX.
To follow along in this exercise, prepare a simple XML document and an HTML page.
Here's what my XML document looks like:
<?xml version="1.0" ?>
<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.
Here's the 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">
<h2>Click the button to get a list of programming
languages</h2>
<input type="button" value="Click Me!"
onclick="loadXml('lesson18_test.xml')" />
</div>
<script type="text/javascript">
//JavaScript AJAX code here
</script>
</body>
</html>
Now proceed with the JavaScript code as follows:
var myRequest;
//The greatest part of the loadXML() function
//is similar to the previous example:
function loadXML(url)
{
if (window.XMLHttpRequest)
{
myRequest = new XMLHttpRequest();
}
else
{
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
myRequest.open("GET", url, true);
myRequest.send(null);
myRequest.onreadystatechange = getData;
}
/******************************************/
function getData()
{
//Get a reference to the div element
//where the returned data will be displayed:
var myDiv = document.getElementById("test");
//The part of the code that checks the response
//is the same as the previous example:
if (myRequest.readyState ===4)
{
if (myRequest.status === 200)
{
//Use the responseXML property to catch
//the returned data, select the xml tag
//called language, and store returned
//language items in an array variable:
var languages =
myRequest.responseXML.getElementsByTagName("language");
//Loop over each array item containing the data
//and create a <p> element to contain each returned
//piece of data.
Notice the use of firstChild.data
//to retrieve the value of the XML <language> tag:
for (var i = 0; i < languages.length; i++)
{
var paragraph = document.createElement("p");
myDiv.appendChild(paragraph);
paragraph.appendChild(document.createTextNode(languages[i].first
Child.data));
//You can also assign the returned result to
myDiv.innerHTML
//if you feel it would be simpler.
}
}
}
}
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 serverside 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.
Lesson 19: Short Introduction to jQuery
By Maria Antonietta Perna
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.
In this lesson you will learn:






about the benefits of using jQuery;
how to include jQuery in your project;
about jQuery selectors to manipulate DOM elements in code;
how jQuery handles events;
how to use anonymous functions with jQuery;
how to add and remove DOM elements with jQuery.
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.
How do I include jQuery in my website?
Including jQuery in your project is fast and easy. You have the choice of downloading a copy
of the library and save it locally, or you can use a Content Delivery Network (CDN) to serve
jQuery to your website on the Internet.
Go to the jQuery website download page
How to include a local copy of jQuery
If you prefer having a local copy of jQuery:
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>
<script type="text/javascript"
src="js/yourscript.js"></script>
</head>
<body>
<h1>Lesson 19: Introduction to jQuery</h1>
</body>
</html>
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.
How to include a hosted copy of jQuery
If you decide to opt for a CDN to serve up a copy of jQuery to your website, then follow these
easy steps:
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.
That's it, you're done!
How to make sure jQuery is working
Now the jQuery library can be used in your project. To make sure things work as expected,
create a text file and call it jquery_test.js. Enter the following code:
//Most of your code goes inside
//the jQuery ready() function:
$(document).ready(function()
{
alert("jQuery is working!");
});
//Make sure you keep track of braces, brackets, and
semi-colons ( ; )
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.
.ready(function() { //JavaScript code here ... } );
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.
How do I access DOM elements using
jQuery?
jQuery appeals so much to web designers also because it enables us to select DOM
elements in code just like we do with CSS. Let's see it in action.
Select html elements by id
Remember our old document.getElementById()? Well, jQuery makes selection by id much
shorter. Here's how it's done:
$(document).ready(function()
{
var myDiv = $("#myDiv");
});
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.
Select html elements by tag name
You also came across document.getElementsByTagName(). This method allows us to grab
all html elements by their tag.
Look how jQuery makes it a lot snappier:
$(document).ready(function)
{
//store all images on the page in an array
var images = $("img");
});
As you can see, the magic $ does most of the talking.
Select html elements by class name
A quick way to target html elements that share the same class is as follows:
$(document).ready(function()
{
var redElements = $(".classRed");
});
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.
Select html elements using jQuery filters
jQuery enables you to be as precise as a surgeon when targeting html elements and
attributes on the page. jQuery offers a filtering syntax to query the DOM that is both simple
and efficient.
Here's a list of the most common filters:
Filter
Description
:first
The first item in a matched set
$(‘p:first’) returns the first paragraph.
:last
The last item in a matched set
$(‘p:last’) returns the last paragraph.
:odd
The odd-indexed items in a matched set
$(‘tr:odd’) returns table rows indexed at 1, 3, etc.
:even
The even-indexed items in a matched set
$(‘tr:even’) returns table rows indexed at 0, 2, etc.
:has
finds elements having the child element specified
$(‘p:has(span)’) returns all paragraphs containing a span element.
:eq
:contains(x)
returns the element with the matched index
$(‘p:eq(1)’) returns the second paragraph starting to count at 0.
Returns all elements containing the text x
$(‘div:contains(foo)’) targets all divs with the text 'foo'.
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.
How do I assign event handlers using jQuery?
Event handlers are code blocks, usually functions, that specify what your application should
do when a specified event like, for example, a button click, occurs.
So far, you've used 2 approaches:
1. hard-wiring a function to the html element itself: <input
type="button" onclick="doSomething()" />
2. assigning a function to the DOM object's appropriate
property: myElement.onclick = doSomething;
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.
The bind() method
bind(eventType, handler) works as follows.
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()
{
//create the sayHello function
function sayHello()
{
alert("Hello jQuery");
}
//Attach the handler using .bind():
myElement.bind('click', sayHello);
});
You can find more details on the bind() method on http://api.jquery.com/bind/.
The ready-made approach
jQuery offers some ready-made handlers corresponding to JavaScript events. Here's a list of
the most widely used ones:
Handler
Description
click()
Binds a handler to an onclick event.
hover()
Binds a handler to the onmouseover and onmouseout events.
change()
Binds a handler to the onchange event (when the content of a field
changes).
select()
Binds a handler to the onselect event (when text is selected).
submit()
Binds a handler to the onsubmit event of a form element.
focus()
Binds a handler to the onfocus event (when an element gets focus).
keypress()
Binds a handler to the onkeypress event (when a key on the computer
keyboard is pressed).
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
With this latest version of jQuery (v.1.7), a brand new method to handle events has been
introduced.
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:
myElement.on('click', sayHello);
More details on the on() method can be found on http://api.jquery.com/on/.
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");
});
/********************************/
//Using click(), we have:
myElement.click(function()
{
alert("Hello jQuery");
});
/**************************************/
//Using on(), we have:
myElement.on('click', function()
{
alert("Hello jQuery");
});
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.
Add new DOM elements
You can both retrieve html elements and add new html elements to the page using
jQuery's .html() method. When you don't pass any arguments, html() retrieves a DOM
element, if you pass a string argument, html() adds that string to the page.
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()
{
//Use html() to retrieve content:
var pageParagraph = $('p').html();
//the alert should display <p>'s content
alert(pageParagraph);
});
/**************************************************/
//Now let's change the div's content
//by adding a new paragraph.
var newParagraph = $('#myElement').html('<p>Hello new
Paragraph!</p>');
//close off all your brackets:
});
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.
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 onhttp://api.jquery.com/html/, and on .text()
can be found on http://api.jquery.com/text/.
Remove DOM elements
A simple way of doing this is with jQuery's remove() method. Let's put it to the test.
Use the same HTML page from the previous example and add a button element with an id
of btnDelete.
In a fresh JavaScript file, add the following code:
$(document).ready(function()
{
//use a click handler and an anonymous function
//to do the job
$('#btnDelete').click(function()
{
//delete all <p> elements
$('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.
More on .remove() can be found on http://api.jquery.com/remove/.
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!
Lesson 20: Cool Animation Effects with
jQuery
By Maria Antonietta Perna
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 this lesson you will learn how to:




add effects by dynamically manipulating styles;
use jQuery's show()/hide()/toggle() methods;
use jQuery's fadeIn()/fadeOut()/fadeToggle() methods;
use jQuery's slideUp()/slideDown()/slideToggle() methods.
In the process, you will build a simple sliding menu and get more practice with the new
jQuery approach.
How do I add and remove CSS classes with
jQuery?
jQuery enables you to manipulate CSS styles in code with $.css(styleName, styleValue). It
also enables you to add and remove CSS classes in relation to DOM elements.
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()
{
//Store a reference to the div in a variable using its
id:
var myDiv = $('#myDiv');
//Attach a click handler to manipulate the CSS classes:
myDiv.click(function()
{
//Remove the existing CSS class and replace it with the
new one.
//Because the element is the same, chain both methods:
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()
{
var myDiv = $('#myDiv');
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.
How do I use jQuery show()/hide()?
If you want to show/hide HTML elements on a page, you can do so easily with
jQuery's show()/hide(). You can also modulate the way elements are revealed or hidden by
adding the 'slow' or 'fast' arguments, or even the number of milliseconds you'd like the
transition to last.
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()
{
var myDiv = $('#myDiv');
myDiv.click(function()
{
//Replace 'slow' with 2000 for a slower transition.
$('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()
{
var myDiv = $('#myDiv');
myDiv.click(function()
{
$('p').toggle('slow');
});
});
How do I make DOM elements fade in and out
of the page?
For a more sophisticated fading effect, use $.fadeIn()/$.fadeOut()/$.fadeToggle(). You use
these methods the same way as you used $.show()/$.hide()/$.toggle() in the previous
examples.
Here's the paragraph from the previous code sample toggling between visible and hidden
using $.fadeToggle().
$(document).ready(function()
{
var myDiv = $('#myDiv');
myDiv.click(function()
{
$('p').fadeToggle('slow');
});
});
The effect is very similar to that of $.toggle('slow'). Just try it out.
How do I make DOM elements slide up and
down with jQuery?
You can easily make DOM elements appear and disappear with a sliding effect
using $.slideUp()/$.slideDown()/$.slideToggle(). You implement these methods similarly to
the previous ones.
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()
{
var myDiv = $('#myDiv');
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.
Try out: sliding menu
Here we are at our jQuery try out exercise. You will build a simple sliding menu similar to
what you might have already seen on many websites.
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.
Let's start from the HTML page:
<!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>
<script type="text/javascript"
src="lesson20_ex.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 submenu items are vertically stacked under their parent li element (take a peek at the example
page if you like).
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.
Prepare your lesson24_ex.js file and write the following code.
$(document).ready(function()
{
//retrieve the menu subitems (div element child of the
list element)
//with the powerful jQuery selectors
//and store them in a variable
var subItems = $('ul li div');
//retrieve the main menu items that
//have the retrieved subitems as children.
//Notice the handy .has() method:
var mainItems = $('ul li').has(subItems);
//Hide all subitems on page load
subItems.hide();
//Attach the .hover() function to the main
//menu items:
$(mainItems).hover(function()
{
//Apply .slideToggle() to the sub-menu
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 submenu 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.
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.
Lesson 21: Easy AJAX Calls with jQuery
By Maria Antonietta Perna
jQuery provides a rich set of handy methods you can use to Ajaxify your web pages.
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.
In this lesson, you will learn how to use:

$.load() to request content from an HTML page;



the shorthand $.get() method;
the shorthand $.post() method;
the full-blown $.ajax() method.
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.
How do I load HTML content with jQuery
AJAX?
jQuery offers a very simple approach to loading HTML content on your web page
asynchronously. Just use the $.load() function and you're done.
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.
Here's how this is done in practice.
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.
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>
<p><a href="#">Click here to fetch HTML content</a></p>
<div id="result">
</div>
<script type="text/javascript">
//JavaScript AJAX code here
</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 ofcontent. 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()
{
//Attach a handler to the click event
//of the link on the page:
$('a').click(function()
{
//Target the div with id of result
//and load the content from the specified url
//and the specified div element into it:
$('#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.
How do I use $.get()?
As nice and simple as $.load() is, it can't perform all types of content requests. A more
flexible approach is offered by the $.get() method.
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 URLin the PHP tutorial on
HTML.net for a great introduction to query strings).
$.get(url, {dataKey1 : 'dataValue1', dataKey2 : 'dataValue2'}, optionalSuccessFunction) takes
in 3 arguments:
1. theURL where the data you want to retrieve is stored;
2. optionally, some data, if you want to send data to the server with the request. This is
done using either a string or what is called object literal or map, that is, commaseparated key:value pairs inside curly braces. For instance: {'First Name' : 'John',
'Last Name' : 'Smith'} sends the First Name and Last Name values to the server
together with the AJAX GET request;
3. and a function that deals with the returned data if you want to display or
process the successful response in any way.
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()
{
//Store the URL value in a variable
var url = "content.xml";
/*************************************/
//Package the result-handling code
//in its own function: it's more readable
function processData(data)
{
//This variable will hold the result
//converted into a string for display
var resultStr = "";
//use jQuery .find() to extract the language
//element from the returned data
//and store it in an array
var items = $(data).find('language');
//loop over each language item with
//jQuery .each() function
$(items).each(function(i)
{
//extract the text of each language item and
//add it to the resultStr variable with a line break.
//Notice the use of $(this)
//to refer to the item currently being
//inspected by the loop
resultStr += $(this).text() + '<br />';
//add the final string result to div element
//with the id of result using .html()
$('#result').html(resultStr);
});
}
/****************************************/
//Attach a click handler to the link element:
//when the user clicks on the link, the AJAX
//request is sent to the server:
$('a').click(function()
{
//use $.get() passing the url variable and
//the name of the result-handling 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.
More details on $.each() can be found on http://api.jquery.com/each/.
How do I use $.post()?
If you want to use POST instead of GET in your AJAX calls, you can use $.post().
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.
How do I use $.ajax()?
If you need greater flexibility, the full-blown $.ajax() function offers a great number of
settings.
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:
1.
2.
3.
4.
5.
the request must be an HTTP GET;
the page from which the result is returned must not be in the browser's cache;
the response returned by the server is of data-type XML;
the request is made in html;
there must be a function that handles the returned result if all goes well;
6. and, finally, there must be a function that handles errors in case the request is not
successful.
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:
//Package the code that handles
//error message in case the request
//is not successful:
function errorAlert(e, jqxhr)
{
alert("Your request was not successful: " + jqxhr);
}
/*************************************/
//Attach a click handler to the
//link element on the page
$('a').click(function()
{
//Prepare the AJAX request that
//will be sent when the user clicks the link:
$.ajax(
{
type: "GET",
cache: false,
url: url,
dataType: "xml",
contentType: "text/html",
success: processData,
error: errorAlert
}); //end of $.ajax
}); //end of click handler
});
//end of $.ready function
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.
More on $.ajax() can be found on http://api.jquery.com/jQuery.ajax/.
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.
Download