Computer Networks Lecture Notes: Course Code - Course Name
Computer Networks Lecture Notes: Course Code - Course Name
Computer Networks Lecture Notes: Course Code - Course Name
Lecture Notes
Course Code - BCS 415
0
BCS-415 INTERNET & WEB TECHNOLOGY-II (3-1-0)Cr.-4
TCP/ IP:
TCP/IP Overview, TCP/IP and Internet, Layers of TCP/IP, Network Layer: Addressing,
Sub netting, concepts of ARP, RARP, ICMP, IGMP. Transport Layer: UDP & TCP,
Application Layer: Client server model, BOOTP, DHCP, DNS, TELNET, FTP, SMTP model,
HTTP, idea of WWW and CGI.
Core JAVA:
Advanced JAVA:
CGI Programming
Introduction to Web Architecture, Apache Web Server, Perl programming, CGI
programming with Perl.
Network Security:
Network security basics and needs, cryptography, encryption and decryption,
Ciphertext, types of cryptography: symmetric and asymmetric, RSA algorithm, Digital
Signature, Organizational security issues and firewall architecture.
Reference Books:
1. TCP/IP Forouzan (TMH)
2. Internet and World Wide Web, How to Program, Dietel and Dietel, Pearson Education.
3. Complete Reference JAVA - Naughton Schildt
Internet: The Internet is a global system of interconnected computer networks that use
the standard Internet Protocol Suite (TCP/IP) to serve billions of users worldwide. It is a
network of networks that consists of millions of private, public academic, business, and
government networks.
WWW: The World Wide Web, abbreviated as WWW and commonly known as the Web,
is a system of interlinked hypertext documents accessed via the Internet. With a web
browser, one can view web pages that may contain text, images, videos, and other
multimedia and navigate between them via hyperlinks.
Emergence of Web: Between the summers of 1991 and 1994, the load on the first Web
server ("info.cern.ch") rose steadily by a factor of 10 every year.
In 1992 academia, and in 1993 industry, was taking notice. World Wide Web Consortium
is formed in September 1994, with a base at MIT is the USA, INRIA in France, and now
also at Keio University in Japan.
With the dramatic flood of rich material of all kinds onto the Web in the 1990s, the first
part of the dream is largely realized, although still very few people in practice have access
to intuitive hypertext creation tools.
The second part has yet to happen, but there are signs and plans which make us confident.
The great need for information about information, to help us categorize, sort, pay for own
information is driving the design of languages for the web designed for processing by
machines, rather than people. The web of human readable document is being merged with
a web of machine-understandable data. The potential of the mixture of humans and
machines working together and communicating through the web could be immense.
WEB Servers: To view and browse pages on the Web, all you need is a web browser. To
publish pages on the Web, you need a web server. A web server is the program that runs
on a computer and is responsible for replying to web browser requests for files. You need
a web server to publish documents on the Web. When you use a browser to request a page
on a website, that browser makes a web connection to a server using the HTTP protocol.
The browser then formats the information it got from the server. Server accepts the
connection, sends the contents of the requested files and then closes.
WEB Browsers:
A web browser is the program you use to view pages and navigate the World Wide Web.
A wide array of web browsers is available for just about every platform you can imagine.
Microsoft Internet Explorer, for example, is included with Windows and Safari is
included with Mac OS X. Mozilla Firefox, Netscape Navigator, and Opera are all
available for free.
What the Browser Does The core purpose of a web browser is to connect to web servers,
request documents, and then properly format and display those documents. Web browsers
can also display files on your local computer, download files that are not meant to be
displayed. Each web page is a file written in a language called the Hypertext Markup
Language (HTML) that includes the text of the page, a description of its structure, and
links to other documents, images, or other media.
Protocols: In computing, a protocol is a set of rules which is used by computers to
communicate with each other across a network. A protocol is a convention or standard
that controls or enables the connection, communication, and data transfer between
computing endpoints.
Internet Protocol Suite: The Internet Protocol Suite is the set of communications
protocols used for the Internet and other similar networks. It is commonly also known as
TCP/IP named from two of the most important protocols in it: The Transmission Control
Protocol (TCP) and the Internet Protocol (IP), which were the first two networking
protocols defined in this standard.
Building Web sites: It's a good idea to first think about and design your site. That way,
you'll give yourself direction and you'll need to reorganize less later.
To design your site:
1. Figure out why you're creating this site. What do you want to convey?
2. Think about your audience. How can you tailor your content to appeal to this audience?
For example, should you add lots of graphics or is it more important that your page
download quickly?
3. How many pages will you need? What sort of structure would you like it to have? Do
you want visitors to go through your site in a particular direction, or do you want to make
it easy for them to explore in any direction?
4. Sketch out your site on paper.
Devise a simple, consistent naming system for your pages, images and other external
files.
HTML
Planning for designing web pages:
Breaking Up Your Content into Main Topics
With your goals in mind, try to organize your content into main topics or sections,
chunking related information together under a single topic.
Ideas for Organization and Navigation
At this point, you should have a good idea of what you want to talk about as well as a list
of topics. The next step is to actually start structuring the information you have into a set
of web pages. Before you do that, however, consider some standard structures that have
been used in other help systems and online tools. This section describes some of these
structures, their various features, some important considerations, including the following
Model and Structure of a Web site:
You need to know what the following terms mean and how they apply to the body of
work you're developing for the Web:
Website: A collection of one or more web pages linked together in a meaningful way
that, as a whole, describes a body of information or creates an overall effect.
Web server: A computer on the Internet or an intranet that delivers Web pages and other
files in response to browser requests.
Web page: A single document on a website, usually consisting of an HTML document
and any items that are displayed within that document such as inline images.
Home page: The entry page for a website, which can link to additional pages on the same
website or pages on other sites.
Developing websites:
Designing a website, like designing a book outline, a building plan, or a painting, can
sometimes be a complex and involved process. Having a plan before you begin can help
you keep the details straight and help you develop the finished product with fewer false
starts. Today, you learned how to put together a simple plan and structure for creating a
set of web pages, including the following:
Deciding what sort of content to present
Coming up with a set of goals for that content
Deciding on a set of topics
Organizing and storyboarding the website
Basic HTML: HTML stands for Hypertext Markup Language. The idea here is that most
documents have common elements for example, titles, paragraphs, and lists. Before you
start writing, therefore, you can identify and define the set of elements in that document
and give them appropriate names.
How Markup Works
HTML is a markup language. Writing in a markup language means that you start with the
text of your page and add special tags around words and paragraphs. The tags indicate the
different parts of the page and produce different effects in the browser. HTML has a
defined set of tags you can use. You can't make up your own tags to create new styles or
features.
What HTML Files Look Like
Pages written in HTML are plain text files (ASCII), which means that they contain no
platform- or program-specific information. Any editor that supports text can read them.
HTML files contain the following:
The text of the page itself
HTML tags that indicate page elements, structure, formatting, and hypertext links to
other pages or to included media. Most HTML tags look something like the following:
<thetagname>affected text</thetagname>
The tag name itself (here, thetagname) is enclosed in brackets (< >). HTML tags
generally have a beginning and an ending tag surrounding the text they affect. The
beginning tag "turns on" a feature (such as headings, bold, and so on), and the ending tag
turns it off. Closing tags have the tag name preceded by a slash (/). The opening tag (for
example, <p> for paragraphs) and closing tag (for example, </p> for paragraphs)
compose what is officially called an HTML element.
Text Formatting and HTML
When an HTML page is parsed by a browser, any formatting you might have done by
hand that is, any extra spaces, tabs, returns, and so on is ignored. The only thing that
specifies formatting in an HTML page is an HTML tag. If you spend hours carefully
editing a plain text file to have nicely formatted paragraphs and columns of numbers but
don't include any tags, when a web browser loads the page, all the text will flow into one
paragraph. All your work will have been in vain.
The advantage of having all white space (spaces, tabs, returns) ignored is that you can put
your tags wherever you want. The following examples all produce the same output. Try
them!
<h1>If music be the food of love, play on.</h1>
<h1>
If music be the food of love, play on.
</h1>
<h1>
If music be the food of love, play on. </h1>
<h1> If music be the food of love,
play on. </h1 >
Structuring Your HTML
The DOCTYPE Identifier
Although it's not a page structure tag, the XHTML 1.0 recommendation includes one
additional requirement for your web pages. The first line of each page must include a
DOCTYPE identifier that defines the XHTML 1.0 version to which your page conforms,
and the document type definition (DTD) that defines the specification. This is followed
by the <html>, <head>, and <body> tags. In the following example, the XHTML 1.0
Strict document type appears before the page structure tags:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/strict.dtd">
<html>
<head>
<title>Page Title</title>
</head>
<body>
...your page content...
</body>
</html>
Three types of HTML 4.01 document types are specified in the XHTML 1.0
specification:
Strict, Transitional, and Frameset.
The <html> Tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
...your page...
</html>
The <head> Tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<title>This is the Title. It will be explained later on</title>
</head>
...your page...
</html>
The <body> Tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<title>This is the Title. It will be explained later on</title>
</head>
<body>
...your page...
</body>
</html>
The Title
Each HTML page needs a title to indicate what the page describes. It appears in the title
bar of the browser when people view the web page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<title>The Lion, The Witch, and the Wardrobe</title>
</head>
<body>
...your page...
</body>
</html>
Headings
Headings are used to add titles to sections of a page. HTML defines six levels of
headings.
Heading tags look like the following:
<h1>Movies</h1>
<h2>Action/Adventure</h2>
<h3>Caper</h3>
<h3>Sports</h3>
<h3>Thriller</h3>
<h3>War</h3>
<h2>Comedy</h2>
<h3>Romantic Comedy</h3>
<h3>Slapstick</h3>
<h2>Drama</h2>
<h3>Buddy Movies</h3>
<h3>Mystery</h3>
<h3>Romance</h3>
<h2>Horror</h2>
Paragraphs
As of the HTML 4.01 standard, paragraph tags are two-sided (<p>...</p>), and <p>
indicates the beginning of the paragraph. The closing tag is no longer optional, so rather
than using <p> to indicate where one paragraph ends and another begins, you enclose
each paragraph within a <p> tag.
Input
<p>The dragon fell to the ground, releasing an anguished cry and seething in pain. The
thrust of Enigern's sword proved fatal as the dragon breathed its last breath. Now Enigern
was free to release Lady Aelfleada from her imprisonment in the dragon's lair.
</p>
Image:
Images displayed on the Web should be converted to one of the formats supported by
most browsers: GIF, JPEG, or PNG. GIF and JPEG are the popular standards, and every
graphical browser supports them. PNG is a newer image format that was created in
response to some patent issue s with the GIF format.
The most important attribute of the <img> tag is src, which is the URL of the image you
want to include. Paths to images are derived in the same way as the paths in the href
attribute of links. So, to point to a GIF file named image.gif in the same directory as the
HTML document, you can use the following HTML tag:
<img src="image.gif" />
Input:
<p><img src="house.jpg" alt="House of Terror" /></p>
<h1>Welcome to The Halloween House of Terror!!</h1>
Output:
Links:
To create a link in an HTML page, you use the HTML link tag <a>...</a>. The <a> tag
often is called an anchor tag because it also can be used to create anchors for links.
Input
Go back to <a href="menu.html">
Main Menu</a>
Lists:
HTML 4.01 defines these three types of lists:
Numbered or ordered lists, which are typically labeled with numbers
Bulleted or unordered lists, which are typically labeled with bullets or some other
symbol
Glossary lists, in which each item in the list has a term and a definition for that term,
arranged so that the term is somehow highlighted or drawn out from the text
List Tags
All the list tags have the following common elements:
The entire list is surrounded by the appropriate opening and closing tag for the type
of list (for example, <ul> and </ul> for unordered lists, or <ol> and </ol> for ordered
lists).
Each list item within the list has its own tag:
<dt> and <dd> for the glossary lists, and <li> for all the other lists.
Input
<p>Installing Your New Operating System</p>
<ol>
<li>Insert the CD-ROM into your CD-ROM drive.</li>
<li>Choose RUN.</li>
<li>Enter the drive letter of your CD-ROM (example: D:\), followed by
SETUP.EXE.</li>
<li>Follow the prompts in the setup program.</li>
<li>Reboot your computer after all files are installed.</li>
<li>Cross your fingers.</li>
</ol>
Customizing Ordered Lists
You can customize ordered lists in two main ways: how they're numbered and the number
with which the list starts. HTML 3.2 provides the type attribute that can take one of five
values to de fine which type of numbering to use on the list:
"1" Specifies that standard Arabic numerals should be used to number the list (that
is, 1, 2, 3, 4, and so on)
"a" Specifies that lowercase letters should be used to number the list (that is, a, b, c,
d, and so on)
"A" Specifies that uppercase letters should be used to number the list (that is, A, B,
C, D, and so on)
"i" Specifies that lowercase Roman numerals should be used to number the list (that
is, i, ii, iii, iv, and so on)
"I" Specifies that uppercase Roman numerals should be used to number the list (that
is, I, II, III, IV, and so on)
You can specify types of numbering in the <ol> tag, as follows: <ol type="a">. By
default type="1" is assumed.
Input
<p>The Days of the Week in French:</p>
<ol type="I">
<li>Lundi</li>
<li>Mardi</li>
<li>Mercredi</li>
<li>Jeudi</li>
<li>Vendredi</li>
<li>Samedi</li>
<li>Dimanche</li>
</ol>
Input
<p>The Last Six Months of the Year (and the Beginning of the NextYear):</p>
<ol type="I" start="7">
<li>July</li>
<li>August</li>
<li>September</li>
<li>October</li>
<li>November</li>
<li>December</li>
<li type="1">January</li>
</ol>
Tables:
Table Parts
Before getting into the actual HTML code to create a table, let's look at the following
terms so that we both know what we're talking about:
The caption indicates what the table is about: for example, "Voting Statistics" or "Toy
Distribution Per Room" Captions are optional.
The table headings label the rows, columns, or both. Usually they're in an emphasized
font that's different from the rest of the table. They're optional.
Table cells are the individual squares in the table. A cell can contain normal table data
or a table heading.
Table data is the values in the table itself. The combination of the table headings and
table data makes up the sum of the table.
The <table> Element
The to create a table in HTML, you use <table>...</table> element to enclose the code
for an optional caption, and then add the contents of the table itself:
<table>
...table caption (optional) and contents...
</table>
Rows and Cells
The cells within each row are created using one of two elements:
<th>...</th> elements are used for heading cells. Generally, browsers center the contents
of a <th> cell and render any text in the cell in boldface.
<td>...</td> elements are used for data cells. TD stands for table data.
Input
<tr>
<th>Name</th>
<td>Alison</td>
<td>Tom</td>
<td>Susan</td>
</tr>
<tr>
<th>Height</th>
<td>5'4"</td>
<td>6'0"</td>
<td>5'1"</td>
</tr>
<tr>
<th>Weight</th>
<td>140</td>
<td>165</td>
<td>97</td>
</tr>
<tr>
<th>Eye Color</th>
<td>Blue</td>
<td>Blue</td>
<td>Brown</td>
</tr>
Setting Table Widths
To make a table as wide as the browser window, you add the width attribute to the table,
as shown in the following line of code:
<table border="1" width="100%">
Changing Table Borders
You can change the width of the border drawn around the table. If border has a numeric
value, the border around the outside of the table is drawn with that pixel width. The
default is border="1". border="0" suppresses the border, just as if you had omitted the
border attribute altogether.
Input
<table border="10" width="100%">
Cell Padding
The cell padding attribute defines the amount of space between the edges of the
cells and the content inside a cell.
Input
<table cellpadding="10" border="1">
Cell Spacing
Cell spacing is similar to cell padding except that it affects the amount of space between
cells that is, the width of the space between the inner and outer lines that make up the
table border.
Input
<table cellpadding="10" border="4" cellspacing="8">
Spanning Multiple Rows or Columns
The tables you've created up to this point all had one value per cell or the occasional
empty cell. You also can create cells that span multiple rows or columns within the table.
Those spanned cells then can hold headings that have subheadings in the next row or
column or you can create other special effects within the table layout.
Input
<html>
<head>
<title>Row and Column Spans</title>
</head>
<body>
<table border="1" summary="span example">
<tr>
<th colspan="2">Gender</th>
</tr>
<tr>
<th>Male</th>
<th>Female</th>
</tr>
<tr>
<td>15</td>
<td>23</td>
</tr>
</table>
</body>
</html>
Forms:
Using the <form> Tag
To accept input from a user, you must wrap all of your input fields inside a <form> tag.
The purpose of the <form> tag is to indicate where and how the user's input should be
sent. First, let's look at how the <form> tag affects page layout. Forms are block-level
elements.
Input
<p>Please enter your username <form><input /> and password <input /></form> to log
in.</p>
The two most commonly used attributes of the <form> tag are action and method. Both of
these attributes are optional. The following example shows how the <form> tag is
typically used:
<form action="someaction" method="get or post">
content, form controls, and other HTML elements
</form>
action specifies the URL to which the form is submitted. Again, remember that for the
form to be submitted successfully, the script must be in the exact location you specify and
must work properly.
The method attribute supports two values: get or post. The method indicates how the form
data should be packaged in the request that's sent back to the server. The get method
appends the form data to the URL in the request.
Creating Text Controls
Text controls enable you to gather information from a user in small quantities. This
control type creates a single-line text input field in which users can type information, such
as their name or a search term.
Input
<p>Enter your pet's name:
<input type="text" name="petname" /></ p>
Creating Password Controls
The password and text field types are identical in every way except that the data entered
in a password field is masked so that someone looking over the shoulder of the person
entering information can't see the value that was typed into the field.
Input
<p>Enter your password: <input type="password" name="userpassword" size="8"
maxlength="8" /></p>
Creating Submit Buttons
Submit buttons are used to indicate that the user is finished filling out the form. Setting
the type attribute of the form to submit places a submit button on the page with the
default label determined by the browser, usually Submit Query. To change the button
text, use the value attribute and enter your own label, as follows:
<input type="submit" value="Send Form Data" />
Creating Reset Buttons
Reset buttons set all the form controls to their default values. These are the values
included in the value attributes of each field in the form (or in the case of selectable
fields, the values that are preselected). As with the Submit button, you can change the
label of a Reset button to one of your own choosing by using the value attribute, like this:
<input type="reset" value="Clear Form" />
Creating Check Box Controls
Check boxes are fields that can be set to two states: on and off. To create a check box, set
the input tag's type attribute to checkbox. The name attribute is also required, as shown in
the following example:
Input
<p>Check to receive SPAM email <input type="checkbox" name="spam" /></p>
Creating Radio Buttons
Radio buttons, which generally appear in groups, are designed so that when one button in
the group is selected, the other buttons in the group are automatically unselected. They
enable you to provide users with a list of options from which only one option can be
selected. To create a radio button, set the type attribute of an <input> tag to radio. To
create a radio button group, set the name attributes of all the fields in the group to the
same value. To cre ate a radio button group with three options, the following code is used:
Input
<p>Select a color:<br />
<input type="radio" name="color" value="red" /> Red<br />
<input type="radio" name="color" value="blue" /> Blue<br />
<input type="radio" name="color" value="green" /> Green<br />
</p>
Creating Menus with select and option
The select element creates a menu that can be configured to enable users to select one or
more options from a pull-down menu or a scrollable menu that shows several options at
once. The <select> tag defines how the menu will be displayed and the name of the
parameter associated with the field. The <option> tag is used to add selections to the
menu. The default appearance of select lists is to display a pull-down list that enables the
user to select one of the options. Here's an example of how one is created:
Input
<p>Please pick a travel destination:
<select name="location">
<option>Indiana</option>
<option>Fuji</option>
<option>Timbuktu</option >
<option>Alaska</option>
</select>
</p>
Frames for designing a good website:
The first HTML document you need to create is called the frameset document. In this
document, you define the layout of your frames, and the locations of the documents to be
initially loaded in each frame. Each of the three HTML documents other than the
frameset document, the ones that load in the frames, contain normal HTML tags that
define the contents of each separate frame area. These documents are referenced by the
frameset document.
The <frameset> Tag
To create a frameset document, you begin with the <frameset> tag. When used in an
HTML document, the <frameset> tag replaces the <body> tag, as shown in the following
code:
<html>
<head>
<title>Page Title</title>
</head>
<frameset>
.. your frameset goes here ...
</frameset>
</html>
It's important that you understand up front how a frameset document differs from a
normal HTML document. If you include a <frameset> tag in an HTML document, you
cannot include a <body> tag also.
The cols Attribute
When you define a <frameset> tag, you must include one of two attributes as part of the
tag definition. The first of these attributes is the cols attribute, which takes the following
form:
<frameset cols="column width, column width, ...">
Input
<html>
<head>
<title>Three Columns</title>
</head>
<frameset cols="100,50%,*">
<frame src="leftcol.html">
<frame src="midcol.html">
<frame src="rightcol.html">
</frameset>
</html>
The rows Attribute
The rows attribute works the same as the cols attribute, except that it splits the screen into
horizontal frames rather than vertical ones. To split the screen into two frames of equal
height, you would write the following:
Input
<html>
<head>
<title>Two Rows</title>
</head>
<frameset rows="50%,50%">
<frame src="toprow.html">
<frame src="botrow.html">
</frameset>
</html>
The <frame> Tag
After you have your basic frameset laid out, you need to associate an HTML document
with each frame by using the <frame> tag, which takes the following form:
<frame src="document URL">
For each frame defined in the <frameset> tag, you must include a corresponding <frame>
tag, as shown in the following:
Input
<html>
<head>
<title>The FRAME Tag</title>
</head>
<frameset rows="*,*,*">
<frame src="document1.html" />
<frame src="document2.html" />
<frame src="document3.html" />
</frameset>
</html>
Changing Frame Borders
Start with the <frame> tag. By using two attributes, bordercolor and frameborder, you can
turn borders on and off and specify their color. You can assign bordercolor any valid
color value, either as a name or a hexadecimal triplet. frameborder takes two possible
values:
1(to display borders) or 0 (to turn off the display of borders).
<html>
<head>
<title>Conflicting Borders</title>
</head>
<frameset frameborder="0" rows="*,*,*">
<frame frameborder="1" bordercolor="yellow" src="document1.html">
<frame bordercolor="#cc3333" src="document2.html">
<frame src="document3.html">
</frameset>
</html>
long questions:
1. What is internet? Want is WWW? What is the difference between them?
2. What are the different lists available explain briefly.
3. Explain the different tags and attributes available in table briefly.
4. What are the different tags available to create the elements of a form explain in detail.
Java Script, CSS and DOM
Java Script:
Programming Fundamentals:
1 <html>
2 <head><title>First JavaScript Sample</title></head>
3 <body bgcolor="yellow" text="blue">
4 <script language = "JavaScript" type="text/javascript">
4 document.writeln("<h2>Welcome to the JavaScript
World!</h1>");
5 </script>
6 <font size="+2">This is just plain old HTML stuff.</font>
7 </body>
8 </html>
Attributes
The <script> tag also has attributes to modify the behavior of the tag. The attributes are
language
type
src
<script language="JavaScript"
type="text/javascript"
src="directory/sample.js">
</script>
String Concatenation
Concatenation is caused when two strings are joined together. The plus (+) sign is used to
concatenate strings; for example:
"hot" + "dog or "San Francisco" + "</br>"
The write() and writeln() Methods
<html>
<head><title>Printing Output</title></head>
<body bgcolor="yellow" text="blue">
<b>Comparing the <em>document.write</em> and <em>document.writeln
</em> methods</b><br>
<script language="JavaScript">
document.write("<h3>One, "); // No newline
document.writeln("Two, ");
document.writeln("Three, ");
document.write("Blast off....<br>"); // break tag
document.write("The browser you are using is " +
navigator.userAgent + "<br>");
</script>
<pre>
<script language="JavaScript">
document.writeln("With the <em>HTML <pre>
</em> tags, ");
document.writeln("the <em>writeln</em> method produces a newline.");
document.writeln("Slam");
document.writeln("Bang");
document.writeln("Dunk!");
</script>
</pre>
</body></html>
Data Types
Primitive Data Types
Primitive data types are the simplest building blocks of a program. They are types that
can be assigned a single literal value such as the number 5.7, or a string of characters such
as "hello". JavaScript supports three core or basic data types:
numeric
string
Boolean
In addition to the three core data types, there are two other special types that consist of a
single value:
null
undefined
Variables
Variables are fundamental to all programming languages. They are data items that
represent a memory storage location in the computer. Variables are containers that hold
data such as numbers and strings. Variables have a name, a type, and a value. JavaScript
variables can be assigned three types of data:
numeric
string
Boolean
Operators:
Data objects can be manipulated in a number of ways by the large number of operators
provided by JavaScript. Operators are symbols, such as +, , =, >, and <, that produce a
result based on some rules.
Precedence and associativity
Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Bitwise left shift
>> Bitwise right shift
>>> Bitwise zero-filled, right shift
&& Logical AND Left to right
Logical OR Left to right
? : Ternary, conditional Right to left
= += = *= /= %= <<= >>= Assignment Right to left
, (comma)
Types of Operators:
Arithmetic Operators
Arithmetic operators.
Operator/Operands Function
x+y Addition
xy Subtraction
x*y Multiplication
x/y Division
x%y Modulus
To make programs easier to read, to simplify typing, and, at the machine level, to produce
more efficient code, the auto increment (++) and auto decrement ( ) operators are
provided. Auto increment and auto decrement operators.
As shown in previous examples, the + sign is used for concatenation and addition. The
concatenation operator, the + sign, is a string operator used to join together one or more
strings. In fact, the concatenation operator is the only operator JavaScript provides to
manipulate strings.
+= x ="cow"; x+= "boy"; Concatenates two strings and assigns the result to x; x becomes
"cowboy".
Comparison Operators
Operator/Operands Function
x == y x is equal to y
x != y x is not equal to y
x>y x is greater than y
x >= y x is greater than or equal to y
x<y x is less than y
x <= y x is less than or equal to y
x===y x is identical to y in value and type
x != = y x is not identical to y
Logical Operators
Operator/Operands Function
num1 && num2 True, if num1 and num2 are both true. Returns num1 if evaluated to
false; otherwise returns num2. If operands are Boolean values, returns true if both
operands are true; otherwise returns false.
FORMAT
conditional expression ? expression : expression
Examples:
x ?y : z If x evaluates to true, the value of the expression becomes y, else the value of the
expression becomes z
Bitwise Operators
Operator Function Example What It Does
&Bitwise AND x & y Returns a 1 in each bit position if both corresponding bits are 1.
Bitwise OR x y Returns a 1 in each bit position if one or both corresponding bits are 1.
^ Bitwise XOR x ^ y Returns a 1 in each bit position if one, but not both, of the
corresponding bits are 1.
<< Left shift x << y Shifts x in binary representation y bits to left, shifting in zeros from
the right.
>> Right shift x >> y Shifts x in binary representation y bits to right, discarding bits
shifted off.
>>> Zero-fill right x shift >>> b Shifts x in binary representation y bits to the right,
discarding bits shifted off, and shifting in zeros from the left.
Popup boxes:
JavaScript uses dialog boxes to interact with the user. The dialog boxes are created with
three methods:
alert()
prompt()
confirm()
<html>
<head><title>Dialog Box</title></head>
<body bgcolor="yellow" text="blue">
<b>Testing the alert method</b><br>
<script language="JavaScript">
document.write("<font size='+2'>");
document.write("It's a bird, ");
document.write("It's a plane, <br>");
alert("It's Superman!");
</script>
</body></html>
Since JavaScript does not provide a simple method for accepting user input, the prompt
dialog box and HTML forms are used. The prompt dialog box pops up with a simple text
field box. After the user enters text into the prompt dialog box, its value is returned.
FORMAT
prompt(message);
prompt(message, defaultText);
Example:
prompt("What is your name? ", "");
prompt("Where is your name? ", name);
The confirm dialog box is used to confirm a user's answer to a question. A question mark
will appear in the box with an OK button and a Cancel button. If the user presses the OK
button, true is returned; if he presses the Cancel button, false is returned. This method
takes only one argument, the question you will ask the user.
Example
<html>
<head>
<title>Using the JavaScript confirm box</title>
</head>
<body>
<script language = "JavaScript">
document.clear // Clears the page
if(confirm("Are you really OK?") == true){
alert("Then we can proceed!");
}
else{
alert("We'll try when you feel better? ");
}
</script>
</body>
</html>
Control Statements:
Conditionals
if (condition){
statements;
}
Example:
if ( age > 21 ){
alert("Let's Party!"); }
if/else
if (condition){
statements1;
}
else{
statements2;
}
Example:
if ( x > y ){
alert( "x is larger");
}
else{
alert( "y is larger");
}
Example
<html>
<head>
<title>Conditional Flow Control</title>
</head>
<body>
<script language=javascript>
<!-- Hiding JavaScript from old browsers document.write("<h3>");
var age=prompt("How old are you? ","");
if( age >= 55 ){
document.write("You pay the senior fare! ");
}
else{
document.write("You pay the regular adult fare. ");
}
document.write("</h3>");
//-->
</script>
</body>
</html>
if/else if
if (condition) {
statements1;
}
else if (condition) {
statements2;
}
else if (condition) {
statements3;
}
else{
statements4;
}
Switch/case
switch (expression){
case label :
statement(s);
break;
case label :
statement(s);
break;
...
default : statement;
}
Example:
switch (color){
case "red":
alert("Hot!");
break;
case "blue":
alert("Cold.");
break;
default:
alert("Not a good choice.");
break;
}
Example
<html>
<head>
<title>The Switch Statement</title>
</head>
<body>
<script language=javascript>
<!--
var color=prompt("What is your color?","");
switch(color){
case "red":
document.bgColor="color";
document.write("Red is hot.");
break;
case "yellow":
document.bgColor=color;
document.write("Yellow is warm.");
break;
case "green":
document.bgColor="lightgreen";
document.write("Green is soothing.");
break;
case "blue":
document.bgColor="#RRGGBB";
document.write("Blue is cool.");
break;
default:
document.bgColor="white";
document.write("Not available today. We'll use white");
break;
}
//-->
</script>
</body>
</html>
Loops
Loops are used to execute a segment of code repeatedly until some condition is met.
JavaScript's basic looping constructs are
while
for
do/while
The while statement executes its statement block as long as the expression after the while
evaluates to true; that is, non-null, non-zero, non-false. If the condition never changes and
is true, the loop will iterate forever (infinite loop). If the condition is false control goes to
the statement right after the closing curly brace of the loop's statement block. The break
and continue functions are used for loop control.
while (condition) {
statements;
increment/decrement counter;
}
Example
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>While Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
vari=0; // Initialize loop counter
while ( i< 10 ){ // Test
document.writeln(i);
i++; // Increment the counter
} // End of loop block
</script>
</body>
</html>
do
{ statements;}
while (condition);
Example
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>Do While Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
vari=0;
do{
document.writeln(i);
i++;
} while ( i< 10 )
</script>
</body>
</html>
The for Loop
The for loop consists of the for keyword followed by three expressions separated by
semicolons and enclosed within parentheses. Any or all of the expressions can be omitted,
but the two semicolons cannot. The first expression is used to set the initial value of
variables and is executed just once, the second expression is used to test whether the loop
should continue or stop, and the third expression updates the loop variables; that is, it
increments or decrements a counter, which will usually determine how many times the
loop is repeated.
for(Expression1;Expression2;Expression3)
{statement(s);}
for (initialize; test; increment/decrement)
{statement(s);}
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>For Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
for(vari = 0; i< 10; i++ ){
document.writeln(i);
}
</script>
</body>
</html>
It is very important that the errors thrown must be catched or trapped so that they can be
handled more efficiently and conveniently and the users can move better through the web
page.
try block
catch block
In the try block, the code contains a block of code that is to be tested for errors. The catch
block contains the code that is to be executed if an error occurs. The general syntax of
try..catch statement is as follows:
try
{
When, in the above structure, an error occurs in the try block then the control is
immediately transferred to the catch block with the error information also passed to the
catch block. Thus, the try..catch block helps to handle errors without aborting the
program and therefore proves user-friendly.
<html>
<head>
<script type="text/javascript">
try
{
document.write(junkVariable)
}
catch(err)
{
document.write(err.message + "<br/>")
}
</script>
</head>
<body>
</body>
</html>
throw in JavaScript:
There is another statement called throw available in JavaScript that can be used along
with trycatch statements to throw exceptions and thereby helps in generating. General
syntax of this throw statement is as follows:
throw(exception)
exception can be any variable of type integer or boolean or string.
for example:
<html>
<head>
<script type="text/javascript">
try
{
varexfor=10
if(exfor!=20)
{
throw "PlaceError"
}
}
catch(err)
{
if(err == "PlaceError")
document.write ("Example to illustrate Throw
Statement: Variable exfor not equal to 20.
<br/>")
}
</script>
</head>
<body>
</body>
</html>
In the above example program, the try block has the variable exfor initialized to 10. Using
the if statement, the variable value is checked to see whether it is equal to 20. Since exfor
is not equal to 20, the exception is thrown using the throw statement. This is named Place
Error and the control transfers to the catch block. The error catched is checked and since
this is equal to the PlaceError, the statement placed inside the error message is displayed
and the output is displayed as above.
The following array is called array_name and its size is not specified.
vararray_name = new Array();
In the next example, the size or length of the array is passed as an argument to the Array()
constructor. The new array has 100 undefined elements.
vararray_name = new Array(100);
And in the next example, the array is given a list of initial values of any data type:
vararray_name = new Array("red", "green", "yellow", 1 ,2, 3);
Example
<html>
<head><title>The Array Object</title>
<h2>An Array of Books</h2>
<script language="JavaScript">
var book = new Array(6); // Create an Array object
book[0] = "War and Peace"; // Assign values to its elements
book[1] = "Huckleberry Finn";
book[2] = "The Return of the Native";
book[3] = "A Christmas Carol";
book[4] = "The Yearling";
book[5] = "Exodus";
</script>
</head>
<body bgcolor="lightblue">
<script language="JavaScript">
document.write("<h3>");
for(vari in book){
document.write("book[" + i + "] "+ book[i] + "<br>");
}
</script>
</body>
</html>
Array Properties and Methods
The Array object only has three properties. The most used is the length property which
determines the number of elements in the array, that is, the size of the array.
constructor References the object's constructor length Returns the number of elements in
the array prototype Extends the definition of the array by adding properties and methods
Array Methods
Whether you have an array of colors, names, or numbers, there are many ways you might
want to manipulate the array elements. For example, you might want to add a new name
or color to the beginning or end of the array, remove a number from the end of the array,
or sort out all the elements, reverse the array, and so on. JavaScript provides a whole set
of methods for doing all of these things and more
concat() Concatenates elements from one array to another array join() Joins the elements
of an array by a separator to form a string pop() Removes and returns the last element of
an array push() Adds elements to the end of an array reverse() Reverses the order of the
elements in an array sort() Sorts an array alphabetically, or numerically toString() Returns
a string representation of the array
Example
var Date = new Date(); // The new constructor returns a Date object.
var Date = new Date("July 4, 2004, 6:25:22");
var Date = new Date("July 4, 2004");
var Date = new Date(2004, 7, 4, 6, 25, 22);
var Date = new Date(2004, 7, 4);
var Date = new Date(Milliseconds);
Using the Date Object Methods
Method What It Does
<html>
<head><title>Time and Date</title></head>
<body bgcolor="lightblue"><h2>Date and Time</h2>
<script language="JavaScript">
var now = new Date(); // Now is an instance of a Date object
document.write("<font size='+1'>");
document.write("<b>Local time:</b> " + now + "<br>");
var hours=now.getHours();
var minutes=now.getMinutes();
var seconds=now.getSeconds();
var year=now.getFullYear();
document.write("The full year is " + year +"<br>");
document.write("<b>The time is:</b> " +
hours + ":" + minutes + ":" + seconds);
document.write("</font>");
</script>
</body>
</html>
The Math Object
The Math object allows you to work with more advanced arithmetic calculations, such as
square root, trigonometric functions, logarithms, and random numbers, than are provided
by the basic numeric operators. If you are doing simple calculations, you really won't
need it.
Method Functionality
Example
<html>
<head><title>The Math Object</title></head>
<body>
<h2>Math object Methods--sqrt(),pow()<br>
Math object Property--PI</h2>
<P>
<script language="JavaScript">
varnum=16;
document.write("<h3>The square root of " +num+ " is ");
document.write(Math.sqrt(num),".<br>");
document.write("PI is ");
document.write(Math.PI);
document.write(".<br>"+num+" raised to the 3rd power is " );
document.write(Math.pow(num,3));
document.write(".</h3></font>");
</script>
</body></html>
The Boolean Object
The Boolean object was included in JavaScript 1.1. It is used to convert a non-Boolean
value to a Boolean value, either true or false. There is one property, the prototype
property, and one method, the toString() method, which converts a Boolean value to a
string; thus, true is converted to "true" and false is converted to "false".
Example:
The inline integration method allows you to take any tag and add a style to it. Using inline
style gives you maximum control over a precise element of a web document, even just
one character. Say you want to control the look and feel of a specific paragraph. You
could simply add a style="x" attribute to the paragraph tag, and the browser would
display that paragraph using the style values you added to the code.
Example:
Inline style is useful for getting precise control over something in a single document, but
because it only applies to the element in question, you most likely wont be using inline
style as frequently as other integration methods.
Embedding allows for control of a full document. Using the style element, which you
place within the head section of a document, you can insert detailed style attributes to be
applied to the entire page.
Embedding is an extremely useful way of styling individual pages that may also have
other style methods influencing them. You can also style a single page or use multiple
embedded sheets. The latter is especially useful if youd like your document to have
different styles for different media types.
An external style sheet contains as many style rules as you like and helps to provide a
most powerful means for you to create master styles that you can apply to one page or
one billion pages.
An external style sheet is exactly thatall of the style is placed in an external file. You
can link to the style sheet from any document you wish, using the link element in the head
portion of those documents with which youd like to integrate the style.
The external style document is a text document that you can write in any editor or tool
that allows you to save a document as text. To create a linked style sheet, follow these
steps:
The next step is to link the document or documents you want to integrate with this style
sheet:
1. In your document, place a link element within the head section. Im using
XHTML, so my link element, which is an empty element, uses the trailing slash,
unlike HTML:
<link />
2. Add the rel attribute, which describes the integration relationship type, in this case,
a style sheet:
4. Include the media for which the sheet is intended. This can be any of the media
types described earlier: print, screen, Braille, aural, and so on. In this instance, Ill
use the screen value.
5. Reference the source file using the href attribute and the location of the source file.
In this case, both documents are residing in the same directory, so Ill reference it
relatively:
The XHTML Document and External Style Sheet Are Now Integrated
Class selectors
Working with HTML, authors may use the period (.) notation representing the class
attribute. The attribute value must immediately follow the "period" (.).
For example, we can assign style information to all elements with class="pastoral" as
follows:
Given these rules, the first H1 instance below would not have green text, while the second
would:
<H1>Not green</H1>
<H1 class="pastoral">Very green</H1>
For example, the following rule matches any P element whose "class" attribute has been
assigned a list of space-separated values that includes "pastoral" and "marine":
This rule matches when class="pastoral blue aqua marine" but does not match for
class="pastoral blue".
CSS gives so much power to the "class" attribute, that authors could conceivably design
their own "document language" based on elements with almost no associated presentation
(such as DIV and SPAN in HTML) and assigning style information through the "class"
attribute. Authors should avoid this practice since the structural elements of a document
language often have recognized and accepted meanings and author-defined classes may
not.
If an element has multiple class attributes, their values must be concatenated with spaces
between the values before searching for the class. As of this time the working group is not
aware of any manner in which this situation can be reached, however, so this behavior is
explicitly non-normative in this specification.
Div
Div (short for division) divides the content into individual sections. Each section can then
have its own formatting, as specified by the CSS. Div is a block-level container, meaning
that there is a line feed after the </div> tag.
For example, if we have the following CSS declaration:
large {
color: #00FF00;
font-family:arial;
font-size: 4pt;
}
The HTML code
<div class="large">
This is a DIV sample.
</div>
gets displayed as This is a DIV sample.
Span
Span is similar to div in that they both divide the content into individual sections. The
difference is that span goes into a finer level, so we can span to format a single character
if needed. There is no line feed after the </span> tag.
For example, if we have the following CSS declaration:
.largefont {
color: #0066FF;
font-family:arial;
font-size: 6px;
}
gets displayed as
block level
Span is not at the
DOM
What is the DOM?
The HTML DOM defines the objects and properties of all HTML elements, and the
methods (interface) to access them.
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
DOM Nodes
The HTML DOM views an HTML document as a tree-structure. The tree structure is
called a node-tree. All nodes can be accessed through the tree. Their contents can be
modified or deleted, and new elements can be created. The node tree below shows the set
of nodes, and the connections between them. The tree starts at the root node and branches
out to the text nodes at the lowest level of the tree:
Inner HTML
The most useful property of our web page objects that we can access is not a part of the
official standard at all. The innerHTML property was introduced by Microsoft in
Internet Explorer as a convenient way of being able to access the entire content of the
HTML container all at once. It turned out to be so convenient that all of the other
browsers quickly added support for this property.
We can use inner HTML either to retrieve the current content of the container or to insert
new content into that container. Let's look at some examples. Here are a couple of div
containers that we might have in our HTML.
<div id="first">
<p>Some text.</p>
<p>Some more text.</p></div>
<div id="second"></div>
The first of our example divs displays two paragraphs of text on the page while the
second displays nothing on the page and is simply a placeholder. We can retrieve the
content of the first div like this:
var content = document.getElementById('first') innerHTML;
The variable content now contains all of the text from the two paragraphs as well as the
paragraph tags themselves. We can now replace those paragraphs completely by
assigning a new value.
Dynamic HTML, or DHTML, is for a collection of technologies used together to create
interactive and animated by using a combination of a static markup language (such as
HTML), a client-side scripting language (such as JavaScript), a presentation definition
language (such as CSS), and the Document Object Model.
Animate text and images in their document, independently moving each element
from any starting point to any ending point, following a predetermined path or one
chosen by the user.
Embed a ticker that automatically refreshes its content with the latest news, stock
quotes, or other data.
Use a form to capture user input, and then process and respond to that data without
having to send data back to the server.
Include rollover buttons or drop-down menus.
DHTML FORMS
Forms are key components of all Web-based applications. But important as they
are, Web developers often present users with forms that are difficult to use. There
are three common problems:
Forms can be too long. A seemingly endless list of questions is sure to make the
user click the back button or jump to another site.
In many situations a specific user will need to fill out only some of the form
elements. If you present needless questions to a user, youll add clutter to your
page and encourage the user to go elsewhere.
Form entries often need to conform to certain formats and instructions. Adding
this information to a Web page can make for a cluttered and unappealing screen.
Choosing The Form You Want
A long form can be shortened in a number of ways. If you have multiple versions of a
form, the chief task becomes pointing people to the right form. Often, a simple set of
links will do: click here for the simple form, click here for the more complicated one.
Alternatively, a single page can show one of several forms that the visitor can choose
between using radio buttons.
This approach uses Dynamic HTML (DHTML), which has several benefits. First,
DHTML allows for more flexible formatting. You can apply background images, borders,
fonts, and all the other features youve learned to expect from HTML and Cascading
Style Sheets to
DHTML objects. Second, if someone fills out one form, switches to another, then
switches back, theres a good chance that the browser will lose the information that was
initially entered. This problem doesnt exist in the DHTML solution. Third, with DHTML
you can do tricky things like clipping and moving the form around the page.
Introduction to CGI:
The Common Gateway Interface (CGI) is a standard that defines how web server
software can delegate the generation of web pages to a stand-alone application, an
executable file. Such applications are known as CGI scripts; they can be written in any
programming language, although scripting languages are often used.
The common gateway interface (CGI) is a standard way for a Web server to pass a Web
user's request to an application program and to receive data back to forward to the user.
When the user requests a Web page (for example, by clicking on a hyperlink or entering a
Web site address), the server sends back the requested page. However, when a user fills
out a form on a Web page and sends it in, it usually needs to be processed by an
application program. The Web server typically passes the form information to a small
application program that processes the data and may send back a confirmation message.
This method or convention for passing data back and forth between the server and the
application is called the common gateway interface (CGI).
If you are creating a Web site and want a CGI application to get control, you specify the
name of the application in the uniform resource locator (URL) that you code in an HTML
file. This URL can be specified as part of the forms tags if you are creating a form. For
example, you might code:
<form method="POST" action="http://www.mybiz.com/cgi-bin/formprog.pl">
and the server at "mybiz.com" would pass control to the CGI application called
"formprog.pl" to record the entered data and return a confirmation message. (The ".pl"
indicates a program written in Perl but other languages could have been used.)
The common gateway interface provides a consistent way for data to be passed from the
user's request to the application program and back to the user. This means that the person
who writes the application program can make sure it gets used no matter which operating
system the server uses (Windows, Linux, Macintosh, UNIX, OS/390, or others). It's
simply a basic way for information to be passed from the Web server about your request
to the application program and back again.