Sunteți pe pagina 1din 80

––––

1
Course Structure
B.Com. (Computer Applications)
SRI KRISHNADEVARAYA UNIVERSITY : ANANTHAPURAMU
Revised Common Framework of CBCS for Colleges in Andhra Pradesh
(A.P. State Council of Higher Education) 2016-17
THIRD YEAR – VI SEMESTER
Web Technology

UNIT-I:
Introduction: HTML, XML, and WWW, Topologies, Bus, Star, Ring, Hybrid, Tree, Lan,Wan,Man.
HTML: Basic HTML, Document body, Text, Hyper links, Adding more formatting, Lists, Tables
using colors and images. More HTML: Multimedia objects, Frames, Forms towards interactive,
HTML document heading.

UNIT-II:
Cascading Style Sheets: Introduction, using Styles, simple examples, your own styles, properties and
values in styles, style sheet, formatting blocks of information, layers.

UNIT-III:
Introduction to JavaScript: What is DHTML, JavaScript, basics, variables, string manipulations,
mathematical functions, statements, operators, arrays, functions.

UNIT-IV:
Objects in JavaScript: Data and objects in JavaScript, regular expressions, exception handling, built-
in objects, events.

Unit-V:
DHTML with JavaScript: Data validation, opening a new window, messages and confirmations, the
status bar, different frames, rollover buttons, moving images, multiple pages in single download, text
only menu system.

========25031984========

2
UNIT-I:
Introduction

HTML:
HyperText Markup Language (HTML) is a simple markup system used to create hypertext documents
that are portable from one platform to another. HTML documents are SGML documents with generic
semantics that are appropriate for representing information from a wide range of applications. HTML
markup can represent hypertext news, mail, documentation, and hypermedia; menus of options;
database query results; simple structured documents with in-lined graphics; and hypertext views of
existing bodies of information.

HTML has been in use by the World-Wide Web (WWW) global information initiative since 1990.
The HTML 3.0 specification provides a number of new features, and is broadly backwards compatible
with HTML 2.0. It is defined as an application of International Standard ISO ISO8879:1986 Standard
Generalized Markup Language (SGML). This specificiation will be proposed as the Internet Media
Type (RFC 1590) and MIME Content Type (RFC 1521) called "text/html; version=3.0".

XML:
XML is a highly versatile markup language from WWW Consortium, W3C. While the normal web
markup language, HTML only helps display the data on a browser, XML goes one step deeper, by
defining the actual organization of the data and how it is stored on a file.
XML, as evidenced by its name, is an extensible markup scheme—it may be extended to include your
custom elements or tags. XML provides you the ability to display data as well as serialize it (i.e., store
in a particular format).
The most important property of XML is that it allows you to define your own tags (elements), while
HTML or any other markup scheme for that matter has its own built-in tags, and you cannot invent
new tags. XML doesn’t come with any built-in tags, you can create what tags you wish to use.
WWW:
The "Web," short for "World Wide Web" (which gives us the acronym www), is the name for one of
the ways that the internet lets people browse documents connected by hypertext links.

The concept of the Web was perfected at CERN (Conseil Européen pour la Recherche Nucléaire, or
the European Organization for Nuclear Research) in 1991 by a group of researchers which included
Tim-Berners Lee, the creator of the hyperlink, who is today considered the father of the Web.
Introduction to the Internet:
The principle of the Web is based on using hyperlinks to navigate between documents (called web
pages) with a program called a browser. A web page is a simple text file written in a markup language
(called HTML) that encodes the layout of the document, graphical elements, and links to other
documents, all with the help of tags.
Besides the links which connect formatted documents to one another, the web uses the HTTP protocol
to link documents hosted on distant computers (called web servers, as opposed to the client
represented by the broswer). On the internet, documents are identified with a unique address, called a
URL, which can be used to locate any resource on the internet, no matter which server may be hosting
it.
What is a website?

3
A website (also called an internet site or a home page in the case of a personal site) is a
group of HTML files that are stored on a hosting computer which is permanently connected
to the internet (a web server).
A website is normally built around a central page, called a welcome page, which offers links to a
group of other pages hosted on the same server, and sometimes "external" links, which lead to pages
hosted by another server.
A URL looks something like this:
http://en.kioskea.net/www/www-intro.php3
Let's take a closer look at this address:
http:// indicates that we want browse the web using the HTTP protocol, the default protocol for
browsing the Web. There are other protocols for other uses of the internet.
www.commentcamarche.net corresponds to the address of the server that hosts the web pages. By
convention, web servers have a name that begins with www., to make it clear that they are dedicated
web servers and to make memorising the address easier. This second part of the address is called the
domain name. A website can be hosted on several servers, each belonging to the same name:
www.commentcamarche.net, www2.commentcamarche.net, intranet.commentcamarche.net, etc.
Topologies:
A network topology is the arrangement of a network, including its nodes and connecting lines. There
are two ways of defining network geometry:
• The physical topology
• The logical (or signal) topology.

The physical topology of a network is the actual geometric layout of workstations. There are
several common physical topologies, as described below and as shown in the illustration.

Bus Topology:In the bus network topology, every workstation is connected to a main cable called the
bus. Therefore, in effect, each workstation is directly connected to every other workstation in the
network.

Star Topology:In the star network topology, there is a central computer or server to which all the
workstations are directly connected. Every workstation is indirectly connected to every other through
the central computer.

Ring Topology:In the ring network topology, the workstations are connected in a closed loop
configuration. Adjacent pairs of workstations are directly connected. Other pairs of workstations are
indirectly connected, the data passing through one or more intermediate nodes.

Mesh Topology:The mesh network topology employs either of two schemes, called full mesh and
partial mesh. In the full mesh topology, each workstation is connected directly to each of the others.
In the partial mesh topology, some workstations are connected to all the others, and some are
connected only to those other nodes with which they exchange the most data.

Tree Topology:The tree network topology uses two or more star networks connected together. The
central computers of the star networks are connected to a main bus. Thus, a tree network is a bus
network of star networks.

4
Logical topology:

Logical (or signal) topology refers to the nature of the paths the signals follow from node to node. In
many instances, the logical topology is the same as the physical topology. But this is not always the
case. For example, some networks are physically laid out in a star configuration, but they operate
logically as bus or ring networks.

What is a Network?
A network consists of two or more computers that are linked in order to share resources (such as
printers and CDs), exchange files, or allow electronic communications. The computers on a network
may be linked through cables, telephone lines, radio waves, satellites, or infrared light beams. There
are mainly three types of networks:
1. Local Area Networks (LAN),
2. Metropolitan Area Networks (MAN),
3. Wide Area Networks (WAN).

Local Area Networks (LAN): A Local Area Network (LAN) is a network that is confined to a
relatively small area. It is generally limited to a geographic area such as a writing lab, school, or
building. Computers connected to a network are broadly categorized as servers or workstations.
Servers are generally not used by humans directly, but rather run continuously to provide "services" to
the other computers (and their human users) on the network. Services provided can include printing
and faxing, software hosting, file storage and sharing, messaging, data storage and retrieval, complete
access control (security) for the network's resources, and many others.

5
wide area network (WAN):A wide area network (WAN) is a network that exists over a large-scale
geographical area. A WAN connects different smaller networks, including local area networks
(LANs) and metro area networks (MANs). This ensures that computers and users in one location can
communicate with computers and users in other locations. WAN implementation can be done either
with the help of the public transmission system or a private network.

Metropolitan-area networks(MAN): A data network designed for a town or city. A metropolitan


area network (MAN) is similar to a local area network (LAN) but spans an entire city or campus.
MANs are formed by connecting multiple LANs. Thus, MANs are larger than LANs but smaller than
wide area networks (WAN).

MANs are extremely efficient and provide fast communication via high-speed carriers, such as fiber
optic cables.
HTML: Basic HTML:
HTML is not a programming language; it is a markup language that defines the structure of your
content. HTML consists of a series of elements, which you use to enclose, or wrap, different parts of
the content to make it appear a certain way, or act a certain way. The enclosing tags can make a word
or image hyperlink to somewhere else, can italicize words, and can make font bigger or smaller, and
so on.
Tags are instructions that are embedded directly into the text of a HTML document. Each
HTML tag describes that the browser should do something instead of simply displaying the text. In
HTML, the tags begin with (<) and end with (>)
HTML tags can be of two types. They are

6
1. Paired Tags
2. Unpaired Tags
Paired Tags:
A tag is said to be a paired tag if the text is placed between a tag and its companion tag. In paired tags,
the first tag is referred to as Opening Tag and the second tag is referred to as Closing Tag.
Example
<i>This text is in italics. </i>
Note: Here <i> is called opening tag. and </i> is called closing tag.
Unpaired Tags:
An unpaired tag does not have a companion tag or closing tag. Unpaired tags are also known as
Singular or Stand-Alone Tags.
Example:<br> , <hr>
etc. These tags does not require any companion tag.
HTML Files:
Every web page is actually a HTML file. Each HTML file is just a plain-text file, but with a .html file
extension instead of .txt, and is made up of many HTML tags as well as the content for a web page.
A web site will often contain many html files that link to each other. You can edit HTML files with
your favourite editor.
The main parts of our element are:
The opening tag: This consists of the name of the element, wrapped in opening and closing angle
brackets. This states where the element begins, or starts to take.
The closing tag: This is the same as the opening tag, except that it includes a forward slash before the
element name. This states where the element ends Failing to include a closing tag is one of the
common beginner errors and can lead to strange results.
The content: This is the content of the element, which in this case is just text.
The element: The opening tag, the closing tag, and the content together comprise the element.
Elements can also have attributes, which look like this:

Attributes contain extra information about the element that you don't want to appear in the actual
content. Here, class is the attribute name, and editor-note is the attribute value. The class attribute
allows you to give the element an identifier that can be later used to target the element with style
information and other things.
An attribute should always have:
A space between it and the element name (or the previous attribute, if the element already has one or
more attributes).The attribute name, followed by an equals sign.
Opening and closing quote marks wrapped around the attribute value.
Document body:
The <body> tag defines the document's body.The <body> element contains all the contents of
an HTML document, such as text, hyperlinks, images, tables, lists, etc.

BODY takes a number of attributes for specifying the background and colors of the document
on visual browsers. BGCOLOR suggests a background color, TEXT suggests a text color, LINK
suggests a link color, VLINK suggests a visited link color, and ALINK suggests an active link color
(when the link is selected.The BACKGROUND attribute suggests a background image for tiling on
the document canvas. To help ensure a readable document, the BGCOLOR, TEXT, LINK, VLINK,

7
and ALINK attributes should always be included when BACKGROUND is given. The BGCOLOR
will be used for those not loading images.
Example
A simple HTML document, with the minimum of required tags:

<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>
</html>

Text:
HTML Text is probably the first element. Text is the backbone of any web page. It plays an double
role; it provides content for web surfers to enjoy. but it also gives Search Engines and Spiders
keywords and meta data. It is because of text on web pages that we have a network of seemingly
endless information available at our fingers.
HTML - Paragraph Text
Any text containing more than a few lines (or sometimes even more) should exist inside of a
paragraph tag <p>. This tag is reserved specifically for blocks of text, such as those you would expect
to find inside your favorite novel.
HTML <p> Tag Code:
<html>
<head>
<title>My Web Page!</title>
</head>
<body>
<p>Avoid losing floppy disks with important school...</p>
<p>For instance, let's say you had a HUGE school...</p>
</body>
</html>
HTML - Headings
HTML has heading tags which can be used as headers or subheaders. By placing text inside of an
<h1> heading tag, for example, the text displays bold and the size of the text increases to a 24pt font
size. Heading tags are numbered 1 through 6, and they change size depending on which tag you
choose, with 1 being the largest font size at 24pt, and 6 being the smallest font size at 8pt.
HTML Heading Element:
<body>
<h1>Headings</h1>
<h2>are</h2>
<h3>great</h3>
<h4>for</h4>
<h5>titles</h5>
<h6>and subtitles</h6>

8
</body>
HTML - Formatting Text Element
As you begin to place more and more text elements onto your website, you may find yourself wanting
to incorporate bold or italic properties ing your text elements. HTML offers a handful of special tags
that can be utilized to do just that:
HTML Text Formatting Tags:
<p>An example of <b>Bold Text</b></p>
<p>An example of <em>Emphasized Text</em></p>
<p>An example of <strong>Strong Text</strong></p>
<p>An example of <i>Italic Text</i></p>
<p>An example of <sup>superscripted Text</sup></p>
<p>An example of <sub>subscripted Text</sub></p>
<p>An example of <del>struckthrough Text</del></p>
<p>An example of <code>Computer Code Text</code></p>

HTML Formatting Text:


An example of Bold Text
An example of Emphasized Text
An example of Strong Text
An example of Italic Text
An example of superscripted Text
An example of subscripted Text
An example of
An example of Computer Code Text
All of these tags add a pinch of flavor to HTML text elements, from paragraphs to lists and text links
Hyper links:
A webpage can contain various links that take you directly to other pages and even specific parts of a
given page. These links are known as hyperlinks.
Hyperlinks allow visitors to navigate between Web sites by clicking on words, phrases, and
images.When you move the mouse over a link, the mouse arrow will turn into a little hand.
Syntax:
In HTML, links are defined with the <a> tag:
<a href="url">link text</a>
The href attribute specifies the destination address of the link.
The link text is the visible part.
Clicking on the link text will send you to the specified address.
Example:
<a href="https://www.w3schools.com/html/">Visit our HTML tutorial</a>
Image Link:
It is common to use images as links:
Example:
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0;">
</a>

9
Adding more formatting,
Lists:Lists are used to group together related pieces of information so they are clearly associated
with each other and easy to read. HTML Lists are used to specify lists of information. All lists may
contain one or more list elements. There are three different types of HTML lists:

1. Ordered List or Numbered List (ol)


2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)

Ordered List or Numbered List:


In the ordered HTML lists, all the list items are marked with numbers. It is known as numbered list
also. The ordered list starts with <ol> tag and the list items start with <li> tag.
<ol>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ol>

Output:

1. Aries
2. Bingo
3. Leo
4. Oracle

Unordered List or Bulleted List:


In HTML Unordered list, all the list items are marked with bullets. It is also known as bulleted list
also. The Unordered list starts with <ul> tag and list items start with the <li> tag.
<ul>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ul>

Output:

• Aries
• Bingo
• Leo
• Oracle

Description List or Definition List

HTML Description list is also a list style which is supported by HTML and XHTML. It is also known
as definition list where entries are listed like a dictionary or encyclopedia.

10
The definition list is very appropriate when you want to present glossary, list of terms or other name-
value list.

The HTML definition list contains following three tags:

1. <dl> tag defines the start of the list.


2. <dt> tag defines a term.
3. <dd> tag defines the term definition (description).

Example:

<dl>
<dt>Aries</dt>
<dd>-One of the 12 horoscope sign.</dd>
<dt>Bingo</dt>
<dd>-One of my evening snacks</dd>
<dt>Leo</dt>
<dd>-It is also an one of the 12 horoscope sign.</dd>
<dt>Oracle</dt>
<dd>-It is a multinational technology corporation.</dd>
</dl>
Output:
Aries
-One of the 12 horoscope sign.
Bingo
-One of my evening snacks
Leo
-It is also an one of the 12 horoscope sign.
Oracle
-It is a multinational technology corporation.
Table Tag:The HTML tables allow web authors to arrange data like text, images, links, other tables,
etc. into rows and columns of cells.

The HTML tables are created using the <table> tag in which the <tr> tag is used to create table rows
and <td> tag is used to create data cells. The elements under <td> are regular and left aligned by
default:

Example
<body>
<table border = "1">
<tr>
<td>sno</td>
<td>sname</td>
</tr>
<tr>
<td>101 </td>
<td>sai </td>
</tr> </table>

11
Here, the border is an attribute of <table> tag and it is used to put a border across all the cells.
Cellpadding and Cellspacing Attributes
There are two attributes called cellpadding and cellspacing which you will use to adjust the white
space in your table cells. The cellspacing attribute defines space between table cells, while
cellpadding represents the distance between cell borders and the content within a cell.
<table border = "1" cellpadding = "5" cellspacing = "5">
Colspan and Rowspan Attributes

You will use colspan attribute if you want to merge two or more columns into a single column.
Similar way you will use rowspan if you want to merge two or more rows.
Example: <td rowspan = "2">
<body>
<table border = "1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>
Column 1 Column 2 Column 3
Row 1 Cell 2 Row 1 Cell 3
Row 1 Cell 1
Row 2 Cell 2 Row 2 Cell 3
Row 3 Cell 1

Tables Backgrounds
You can set table background using one of the following two ways −
• bgcolor attribute − You can set background color for whole table or just for one cell.
• background attribute − You can set background image for whole table or just for one cell.
You can also set border color also using bordercolor attribute.
<table border = "1" bordercolor = "green" bgcolor = "yellow">
<table border = "1" bordercolor = "green" background = "/images/test.png">

12
Table Height and Width
You can set a table width and height using width and height attributes. You can specify table width
or height in terms of pixels or in terms of percentage of available screen area.
<table border = "1" width = "400" height = "150">
Table Caption
The caption tag will serve as a title or explanation for the table and it shows up at the top of the table.
<table border = "1" width = "100%">
<caption>This is the caption</caption>

<tr>
<td>row 1, column 1</td><td>row 1, columnn 2</td>
</tr>
</table>

HTML – Tables:
The HTML tables allow web authors to arrange data like text, images, links, other tables, etc. into
rows and columns of cells.

The HTML tables are created using the <table> tag in which the <tr> tag is used to create table rows
and <td> tag is used to create data cells. The elements under <td> are regular and left aligned by
default

<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border = "1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>
</html>
Here, the border is an attribute of <table> tag and it is used to put a border across all the cells. If you
do not need a border, then you can use border = "0".

Table Heading

Table heading can be defined using <th> tag. This tag will be put to replace <td> tag, which is used to
represent actual data cell. Normally you will put your top row as table heading as shown below,
otherwise you can use <th> element in any row. Headings, which are defined in <th> tag are centered
and bold by default.

13
<html>
<head>
<title>HTML Table Header</title>
</head>
<body>
<table border = "1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>
</html>
Cellpadding and Cellspacing Attributes

There are two attributes called cellpadding and cellspacing which you will use to adjust the white
space in your table cells. The cellspacing attribute defines space between table cells, while
cellpadding represents the distance between cell borders and the content within a cell.

Example
<html>

<head>
<title>HTML Table Cellpadding</title>
</head>

<body>
<table border = "1" cellpadding = "5" cellspacing = "5">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>

</html>

14
Colspan and Rowspan Attributes

You will use colspan attribute if you want to merge two or more columns into a single column.
Similar way you will use rowspan if you want to merge two or more rows.

Example
<html>

<head>
<title>HTML Table Colspan/Rowspan</title>
</head>

<body>
<table border = "1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>

</html>
This will produce the following result −

Tables Backgrounds

You can set table background using one of the following two ways −

• bgcolor attribute − You can set background color for whole table or just for one cell.
• background attribute − You can set background image for whole table or just for one cell.

You can also set border color also using bordercolor attribute.

Note − The bgcolor, background, and bordercolor attributes deprecated in HTML5. Do not use these
attributes.

15
Example

<html>

<head>
<title>HTML Table Background</title>
</head>

<body>
<table border = "1" bordercolor = "green" bgcolor = "yellow">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>

</html>
Here is an example of using background attribute. Here we will use an image available in /images
directory.

<html>
<head>
<title>HTML Table Background</title>
</head>
<body>
<table border = "1" bordercolor = "green" background = "/images/test.png">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td><td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>

16
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>

</html>
Table Height and Width

You can set a table width and height using width and height attributes. You can specify table width
or height in terms of pixels or in terms of percentage of available screen area.

Example
<html>
<head>
<title>HTML Table Width/Height</title>
</head>
<body>
<table border = "1" width = "400" height = "150">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>
</html>
Table Caption

The caption tag will serve as a title or explanation for the table and it shows up at the top of the table.
This tag is deprecated in newer version of HTML/XHTML.

Example
<html>
<head>
<title>HTML Table Caption</title>
</head>
<body>
<table border = "1" width = "100%">
<caption>This is the caption</caption>
<tr>
<td>row 1, column 1</td><td>row 1, columnn 2</td>
</tr>
<tr>
<td>row 2, column 1</td><td>row 2, columnn 2</td>
</tr>
</table>
</body>
</html>

17
Table Header, Body, and Footer

Tables can be divided into three portions − a header, a body, and a foot. The head and foot are rather
similar to headers and footers in a word-processed document that remain the same for every page,
while the body is the main content holder of the table.

The three elements for separating the head, body, and foot of a table are −

• <thead> − to create a separate table header.


• <tbody> − to indicate the main body of the table.
• <tfoot> − to create a separate table footer.

A table may contain several <tbody> elements to indicate different pages or groups of data. But it is
notable that <thead> and <tfoot> tags should appear before <tbody>

Example
<html>
<head>
<title>HTML Table</title>
</head>
<body>
<table border = "1" width = "100%">
<thead>
<tr>
<td colspan = "4">This is the head of the table</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan = "4">This is the foot of the table</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</body>
</html>

Nested Tables
You can use one table inside another table. Not only tables you can use almost all the tags inside table
data tag <td>.
Example
Following is the example of using another table and other tags inside a table cell.
<html>
<head>
<title>HTML Table</title>
</head>

18
<body>
<table border = "1" width = "100%">
<tr>
<td>
<table border = "1" width = "100%">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</td>
</tr>

</table>
</body>

</html>
HTML - Images
Images are very important to beautify as well as to depict many complex concepts in simple way on
your web page. This tutorial will take you through simple steps to use images in your web pages.
Insert Image
You can insert any image in your web page by using <img> tag. Following is the simple syntax to use
this tag.
<img src = "Image URL" ... attributes-list/>
The <img> tag is an empty tag, which means that, it can contain only list of attributes and it has no
closing tag.
Example
To try following example, let's keep our HTML file test.htm and image file test.png in the same
directory −
<html>
<head>
<title>Using Image in Webpage</title>
</head>
<body>
<p>Simple Image Insert</p>
<img src = "/html/images/test.png" alt = "Test Image" />
</body>
</html>
You can use PNG, JPEG or GIF image file based on your comfort but make sure you specify correct
image file name in src attribute. Image name is always case sensitive.
The alt attribute is a mandatory attribute which specifies an alternate text for an image, if the image
cannot be displayed.
Set Image Location
Usually we keep all the images in a separate directory. So let's keep HTML file test.htm in our home
directory and create a subdirectory images inside the home directory where we will keep our image
test.png.

19
Example
Assuming our image location is "image/test.png", try the following example −
<html>
<head>
<title>Using Image in Webpage</title>
</head>
<body>
<p>Simple Image Insert</p>
<img src = "/html/images/test.png" alt = "Test Image" />
</body>
</html>
Set Image Width/Height
You can set image width and height based on your requirement using width and height attributes.
You can specify width and height of the image in terms of either pixels or percentage of its actual
size.
Example
<html>
<head>
<title>Set Image Width and Height</title>
</head>
<body>
<p>Setting image width and height</p>
<img src = "/html/images/test.png" alt = "Test Image" width = "150" height = "100"/>
</body>
</html>

Set Image Border


By default, image will have a border around it, you can specify border thickness in terms of pixels
using border attribute. A thickness of 0 means, no border around the picture.
Example
<html>
<head>
<title>Set Image Border</title>
</head>
<body>
<p>Setting image Border</p>
<img src = "/html/images/test.png" alt = "Test Image" border = "3"/>
</body>
</html>

Set Image Alignment


By default, image will align at the left side of the page, but you can use align attribute to set it in the
center or right.
Example
<html>
<head>
<title>Set Image Alignment</title>
</head>
<body>
<p>Setting image Alignment</p>
<img src = "/html/images/test.png" alt = "Test Image" border = "3" align = "right"/>
</body>
</html>

20
More HTML:
Frames:
HTML frames are used to divide your browser window into multiple sections where each section can
load a separate HTML document. A collection of frames in the browser window is known as a
frameset. The window is divided into frames in a similar way the tables are organized: into rows and
columns.
Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag. The <frameset> tag defines,
how to divide the window into frames. The rows attribute of <frameset> tag defines horizontal frames
and cols attribute defines vertical frames. Each frame is indicated by <frame> tag and it defines which
HTML document shall open into the frame.
Example
Following is the example to create three horizontal frames −
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows = "10%,80%,10%">
<frame name = "top" src = "/html/top_frame.htm" />
<frame name = "main" src = "/html/main_frame.htm" />
<frame name = "bottom" src = "/html/bottom_frame.htm" />
<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>
</html>
Example
Let's put the above example as follows, here we replaced rows attribute by cols and changed their
width. This will create all the three frames vertically −
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset cols = "25%,50%,25%">
<frame name = "left" src = "/html/top_frame.htm" />
<frame name = "center" src = "/html/main_frame.htm" />
<frame name = "right" src = "/html/bottom_frame.htm" />
<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>
</html>

Frame's name and target attributes


One of the most popular uses of frames is to place navigation bars in one frame and then load main
pages into a separate frame.
Let's see following example where a test.htm file has following code −
<html>
<head>
<title>HTML Target Frames</title>
</head>
<frameset cols = "200, *">
<frame src = "/html/menu.htm" name = "menu_page" />
<frame src = "/html/main.htm" name = "main_page" />
<noframes>

21
<body>Your browser does not support frames.</body>
</noframes>
</frameset>
</html>
Here, we have created two columns to fill with two frames. The first frame is 200 pixels wide and will
contain the navigation menu bar implemented by menu.htm file. The second column fills in
remaining space and will contain the main part of the page and it is implemented by main.htm file.
For all the three links available in menu bar, we have mentioned target frame as main_page, so
whenever you click any of the links in menu bar, available link will open in main page.
Following is the content of menu.htm file
<html>
<body bgcolor = "#4a7d49">
<a href = "http://www.google.com" target = "main_page">Google</a>
<br />
<br />
<a href = "http://www.microsoft.com" target = "main_page">Microsoft</a>
<br />
<br />
<a href = "http://news.bbc.co.uk" target = "main_page">BBC News</a>
</body>
</html>
Following is the content of main.htm file −

<html>
<body bgcolor = "#b5dcb3">
<h3>This is main page and content from any link will be displayed here.</h3>
<p>So now click any link and see the result.</p>
</body>
</html>

Forms towards interactive:


HTML Forms are required to collect different kinds of user inputs, such as contact details like name,
email address, phone numbers, or details like credit card information, etc.
Forms contain special elements called controls like inputbox, checkboxes, radio-buttons, submit
buttons, etc. Users generally complete a form by modifying its controls e.g. entering text, selecting
items, etc. and submitting this form to a web server for processing.
The <form> tag is used to create an HTML form. Here's a simple example of a login form:
Example
<form>
<fieldset>
<legend>Log In</legend>
<label>Username: <input type="text"></label>
<label>Password: <input type="password"></label>
<input type="submit" value="Submit">
</fieldset>
</form>
The following section describes different types of controls that you can use in your form.
Input Element
This is the most commonly used element within HTML forms.
It allows you to specify various types of user input fields, depending on the type attribute. An input
element can be of type text field, checkbox, password field, radio button, submit button, reset button,
etc. and several new input types introduced in HTML5.
The most used input types are described below.

22
Text Fields
Text fields are one line areas that allow the user to input text.
Single-line text input controls are created using an <input> element, whose type attribute has a value
of text. Here's an example of a single-line text input used to take username:
Example
<form>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</form>
Note: The <label> tag to define labels for <input> elements. If you want your user to enter several
lines you should use a <textarea> instead.
Password Field
Password fields are similar to text fields. The only difference is; characters in a password field are
masked i.e. shown as asterisks or dots. This is to prevent others from reading the password on the
screen. This is also a single-line text input controls created using an <input> element whose type
attribute has a value of password.
Here's an example of a single-line password input used to take user password:
Example
<form>
<label for="user-pwd">Password:</label>
<input type="password" name="user-password" id="user-pwd">
</form>
Radio Buttons
Radio buttons are used to let the user select exactly one option from a pre-defined set of options. It is
created using an <input> element whose type attribute has a value of radio.
Example
<form>
<input type="radio" name="sex" id="male">
<label for="male">Male</label>
<input type="radio" name="sex" id="female">
<label for="female">Female</label>
</form>
Note: If you want to allow your user to select more than one option at the same time you should use
the check boxes instead.
Checkboxes
Checkboxes allows the user to select one or more option from a pre-defined set of options. It is
created using an <input> element whose type attribute has a value of checkbox.
Example
<form>
<input type="checkbox" name="sports" id="soccer">
<label for="soccer">Soccer</label>
<input type="checkbox" name="sports" id="cricket">
<label for="cricket">Cricket</label>
<input type="checkbox" name="sports" id="baseball">
<label for="baseball">Baseball</label>
</form>
File Select box
The file fields allow a user to browse for a local file and send it as an attachment to the form data. It
normally rendered as a text box with a button that enables the user to browse for a file. However, the
user can also type the path and name of the file in the text box.
This is also created using an <input> element, whose type attribute value is set to file.

23
Example
<form>
<label for="file-select">Upload:</label>
<input type="file" name="upload" id="file-select">
</form>
Textarea
Textarea is a multiple-line text input control that allows a user to enter more than one line of text.
Multi-line text input controls are created using an <textarea> element.
Example
<form> <label for="address">Address:</label>
<textarea rows="3" cols="30" name="address" id="address"></textarea>
</form>
Select Boxes
A select box is a dropdown list of options that allows user to select one or more option from a pull-
down list of options. Select box is created using the <select> element and <option> element. The
option elements within the <select> element define each list item.
Example
<form>
<label for="city">City:</label>
<select name="city" id="city">
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
</select>
</form>
Submit and Reset Buttons
A submit button is used to send the form data to a web server. When submit button is clicked the form
data is sent to the file specified in the form's action attribute to process the submitted data. A reset
button resets all the forms control to default values.
Example
<form action="action.php" method="post" id="users">
<label for="first-name">First Name:</label>
<input type="text" name="first-name" id="first-name">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
Most frequently used form attributes are:
Attribute Description
name The name of the form.
action URL of the program that processes the information submitted via form.
The HTTP method that the browser uses to submit the form. Possible values are get and
method
post.
A name or keyword indicating the target page where the result of the script will be
target
displayed. The reserved keywords are _blank, _self, _parent and _top.

24
Unit-2
CASCADING STYLE SHEETS
Introduction to CSS:
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify
the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the text,
the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, layout designs,variations in display for different devices and
screen sizes as well as a variety of other effects.
Advantages of CSS
• CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages as
you want.
• Pages load faster − If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So
less code means faster download times.
• Easy maintenance − To make a global change, simply change the style, and all elements in
all the web pages will be updated automatically.
• Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you
can give a far better look to your HTML page in comparison to HTML attributes.
• Multiple Device Compatibility − Style sheets allow content to be optimized for more than
one type of device. By using the same HTML document, different versions of a website can
be presented for handheld devices such as PDAs and cell phones or for printing.
• Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to
make them compatible to future browsers.
USING STYLES:
CSS stands for Cascading Style Sheets.
CSS describes how HTML elements are to be displayed on screen, paper, or in other media.
CSS saves a lot of work. It can control the layout of multiple web pages all at once.
CSS can be added to HTML elements in 3 ways:
• Inline - by using the style attribute in HTML elements
• Internal - by using a <style> element in the <head> section
• External - by using an external CSS file
The most common way to add CSS, is to keep the styles in separate CSS files. However, here we will
use inline and internal styling, because this is easier to demonstrate, and easier for you to try it
yourself.
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
This example sets the text color of the <h1> element to blue:
Example
<h1 style="color:blue;">This is a Blue Heading</h1>
Internal CSS
An internal CSS is used to define a style for a single HTML page.
An internal CSS is defined in the <head> section of an HTML page, within a <style> element:
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}

25
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
External CSS
An external style sheet is used to define the style for many HTML pages.
With an external style sheet, you can change the look of an entire web site, by changing one file!
To use an external style sheet, add a link to it in the <head> section of the HTML page:
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An external style sheet can be written in any text editor. The file must not contain any HTML code,
and must be saved with a .css extension.
Here is how the "styles.css" looks:
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}
SIMPLE EXAMPLE OF CSS
1. Easy Paragraph Formatting
The cool thing about styling with CSS is that you don’t have to specify a style every time you create
an element. You can just say “all paragraphs should have this particular styling” and you’re good to
go. Here’s an example of how you might do that.
p{
font-size: 120%;
color: dimgray;
}
That’s all there is to it. Now, whenever the browser renders a <p> paragraph, the text will inherit the
size (120 percent of normal) and the color (“dimgray”).
2. Change Letter Case
Okay, so now that we’ve seen how to make a change to every paragraph, let’s look at how we can be
a bit more selective. Let’s create a designation for paragraphs that should be in small caps. Here’s
how we’d do that:

p.smallcaps {
font-variant: small-caps;
}

26
To make a paragraph that’s entirely in small caps, we’ll use a slightly different HTML tag. Here’s
what it looks like:
<p class="smallcaps">Your paragraph here.</p>
As you can see, adding a dot and a class name to any specific element in CSS specifies a sub-type of
that element defined by a class. You can do this with text, images, links, and just about anything else.
If you want to change the case of a set of text to a specific case, you can use these CSS lines:
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;
The last one capitalizes the first letter of every sentence.
3. Change Link Colors
Let’s try changing the style of something other than a full paragraph. There are four different colors a
link can be assigned: its standard color, its visited color, its hover color, and its active color (which it
displays while you’re clicking on it). Here’s how we might change those:
a:link {
color: gray;
}

a:visited {
color: green;
}

a:hover {
color: rebeccapurple;
}

a:active {
color: teal;
}
Note that each “a” is followed by a colon, not a dot.
Each one of those declarations changes the color of a link in a specific context. There’s no need to
change the class of a link to get it to change color. It will all be determined by the user and the state of
the link.

4. Remove Link Underlines


While underlined text pretty clearly indicates a link, it sometimes looks nicer to scrap that underline.
This is accomplished with the “text-decoration” attribute. Here’s how we’d get rid of underlines on
links:
a {
text-decoration: none;
}
Anything with the link (“a”) tag will remain un-underlined. Want to underline it when the user hovers
over it? Just add this below:
a:hover {
text-decoration: underline;
}
You could also add this text-decoration to active links to make sure the underline doesn’t disappear
when the link is clicked.

5. Make a Link Button


If you want to attract more attention to your link, using a link button is a great way to go about it. This
one requires a few more lines, but we’ll go over them each individually:
a:link, a:visited, a:hover, a:active {
background-color: green;

27
color: white;
padding: 10px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
By including all four link states, we ensure that the button doesn’t disappear when a user hovers or
clicks on it. You can also set different parameters for hover and active links, like changing the button
or text color, to add a bit of pop.
The background color is set with background-color, and text color with color. Padding defines the size
of box — the text is padded by 10px vertically and 25px horizontally. Text-align ensures that the text
is displayed in the center of the button, instead of off to one side. Text-decoration, as we saw in the
last example, removes the underline.
“display: inline-block” is a bit more complicated. In short, it lets you set the height and width of the
object, and ensures that it starts a new line when it’s inserted.
Your own styles in css:
User stylesheets are an exciting feature of Cascading Style Sheets (CSS). In CSS, the presentation of a
document is controlled by the combination of user and author style preferences. This mechanism is
needed [text only] to allow CSS to describe fully (and then extend) the current behavior of browsers.
Early implementations of CSS did not support user stylesheets. However, newer browsers, such as
MS Internet Explorer 4.0+, Opera 3.50+, and hopefully Netscape Navigator 5.0 (based on the Mozilla
project) all support user stylesheets.
CSS User Stylesheets
Some test may require special user style sheets to be applied in order for the case to be verified. In
order for proper indications and prerequisite to be displayed every user style sheet should contain the
following rules.

#user-stylesheet-indication
{
/* Used by the harness to display an indication there is a user
style sheet applied */
display: block!important;
}
The rule #user-stylesheet-indication is to be used by any harness running the test suite.

A harness should identify test that need a user style sheet by looking at their flags meta tag. It then
should display appropriate messages indicating if a style sheet is applied or if a style sheet should not
be applied.
Harness style sheet rules:
#userstyle
{
color: green;
display: none;
}

#nouserstyle
{
color: red;
display: none;
}
Harness userstyle flag found:
<p id="user-stylesheet-indication" class="userstyle">A user style
sheet is applied.</p>

28
Harness userstyle flag NOT found:

<p id="user-stylesheet-indication" class="nouserstyle">A user style


sheet is applied.</p>
Within the test case it is recommended that the case itself indicate the necessary user style sheet that is
required.

Examples:
#cascade /* ID name should match user style sheet file name */
{
/* Used by the test to hide the prerequisite */
display: none;
}
The rule #cascade in the example above is used by the test page to hide the prerequisite text. The
rule name should match the user style sheet CSS file name in order to keep this orderly.
Examples:
<p id="cascade">
PREREQUISITE: The <a href="support/cascade.css">
"cascade.css"</a> file is enabled as the user agent's user style
sheet.
</p>
The id value should match the user style sheet CSS file name and the user style sheet rule that is used
to hide this text when the style sheet is properly applied.
Properties and values in styles:
CSS Basic Properties
Here are some basic CSS properties to work with.

• Text Properties
• List Properties
• Border Properties
• Font Properties

Text Properties
Property Description Values

color Sets the color of a text RGB, hex, keyword

line-height Sets the distance between lines normal, number, length, %

Increase or decrease the space between


letter-spacing normal, length
characters

text-align Aligns the text in an element left, right, center, justify

text- none, underline, overline, line-


Adds decoration to text
decoration through

text-indent Indents the first line of text in an element length, %

none, capitalize, uppercase,


text-transform Controls the letters in an element
lowercase

29
List Properties

Property Description Values

Sets all the properties for a list in one list-style-type, list-style-position, list-style-
list-style
declaration image, inherit

list-style- Specifies an image as the list-item


URL, none, inherit
image marker

list-style- Specifies where to place the list-item


inside, outside, inherit
position marker

none, disc, circle, square, decimal, decimal-


leading-zero,
armenian, georgian, lower-alpha, upper-
list-style-type Specifies the type of list-item marker
alpha, lower-greek,
lower-latin, upper-latin, lower-roman, upper-
roman, inherit

Border Properties

Property Description Values

Sets all the border properties in


border border-width, border-style, border-color
one declaration

Sets all the bottom border border-bottom-width, border-bottom-style,


border-bottom
properties in one declaration border-bottom-color

border-bottom- Sets the color of the bottom


border-color
color border

border-bottom- Sets the style of the bottom


border-style
style border

border-bottom- Sets the width of the bottom


border-width
width border

color_name, hex_number, rgb_number,


border-color Sets the color of the four borders
transparent, inherit

Sets all the left border properties border-left-width, border-left-style, border-


border-left
in one declaration left-color

border-left-color Sets the color of the left border border-color

border-left-style Sets the style of the left border border-style

border-left-width Sets the width of the left border border-width

30
Sets all the right border properties border-right-width, border-right-style,
border-right
in one declaration border-right-color

border-right-color Sets the color of the right border border-color

border-right-style Sets the style of the right border border-style

border-right-width Sets the width of the right border border-width

none, hidden, dotted, dashed, solid, double,


border-style Sets the style of the four borders
groove, ridge, inset, outset, inherit

Sets all the top border properties border-top-width, border-top-style, border-


border-top
in one declaration top-color

border-top-color Sets the color of the top border border-color

border-top-style Sets the style of the top border border-style

border-top-width Sets the width of the top border border-width

border-width Sets the width of the four borders thin, medium, thick, length, inherit

Font Properties

Property Description Values

font-style, font-variant, font-weight, font-size/line-


Sets all the font properties in
font height, font-family, caption, icon, menu, message-
one declaration
box, small-caption, status-bar, inherit

Specifies the font family for


font-family family-name, generic-family, inherit
text

xx-small, x-small, small, medium, large, x-large, xx-


font-size Specifies the font size of text
large, smaller, larger, length, %, inherit

font-style Specifies the font style for text normal, italic, oblique, inherit

Specifies whether or not a text


font-variant should be displayed in a small- normal, small-caps, inherit
caps font

normal, bold, bolder, lighter,


font-weight Specifies the weight of a font 100, 200, 300, 400, 500, 600, 700, 800, 900, inherit
Careful, many of these are not supported!

31
Formatting blocks of information in style sheets:
Classes : A class is a definition of a set of styles which can be applied as you choose. Classes can be
applied to a single type of element, or may be anonymous and hence applicable to any element. The
following code shows the difference between the two types:
H1{
Color:red;
Border:thin groove;
}

H2.some {
Color:green;
Margin-left:60%;
}
Anyelement{
Text-align:right;
Color:purple;
}

CSS Division:
CSS Division (div) is a container element and it is used to group related items together. When ever
there is a situation that you need to collect various objects into a larger container for scripting or
styling purposes, div is the best solution. The use of < div > tag is straightforward.

CSS divisions to provide greater flexibility and mark out regions of the page. You can use divs by
referencing the selector in the opening tag using ID and CLASS
(e,g. id="myContainer" or class="myContainer").

The following source code shows how to implement div in an HTML document.

<html>
<head>
<style type="text/css">
#box {
width: 420px;
height:120;
border-width: 2px;
border-style:solid;
border-color:red;
background: #CCC;
}
</style>
</head>
<body>
<div id="box">
<h1>Box Model</h1>

32
<p>
The Box model determines how elements are positioned within the browser window. With the Box
Model, a developer can control the dimensions, margins, padding, and borders of an HTML element.
</p>
</div>
</body>
</html>

Output:

Nesting Div
The div element grouping a generic block of content that should be treated as a logical unit for
scripting or styling purposes. A div can contain a number of other divs ( child div ) like HTML
Tables . This is called Nesting Div .

The following example shows how to arrange a nesting Div in an HTML page.

<html>
<head>
<style type="text/css">
.parent {
width: 200px;
height:120;
border-width: 2px;
border-style:solid;
border-color:red;
padding:10px;
}
.child {
overflow : hidden;
background: #CCC;
}
</style>
</head>
<body>

33
<div class="parent">
<h1> Nesting Div</h1>
<div class="child">
<h2>Child Div 1</h2>
</div>
<div class="child">
<h2>Child Div 2</h2>
</div>
</div>
</body>
</html>

Output:

We can use align attribute to Div elements like align="left", align="center", align="right" etc. But
this align attribute is deprecated in XHTML and doesn`t work consistently in many browsers. So it is
better to avoid when you styling the content with Div element.

Like HTML Table, excessive use of Div is alomst bad when you structuring page content. So you
should add Div elements very carefully and use only when it is necessary for logical structure or
styling.

CSS Span

The CSS div element is used to indicate a block-level element , while the CSS span element is used
to indicate an inline element.

What is an Innline element ?

The inline elements do not force a new line (line break) before or after its placement, it will only take
up the space as it needs. In special cases we can change inline elemnt to block-level elements by
setting its display property to block.

What is a Block-level Elements ?

When you place a Block-level element in your HTML page , it will forces a line break before and
after the element. It will expand naturally to fill its parent container unless a width has been given to
them.

The difference

34
Output:

In the above code the h2 block level element forces a line break before and after the element, but in
the second line the inline element < b > doesnt force the line break.

Span

You can easily style a whole paragraph, but more often than not, you need to style a portion of a
paragraph or some specific words to highlight within a paragraph. In this case you can use CSS span
element , this will style only a specific portion, rather than the whole paragraph.

The span element offers all the same advantages as the div element, except it is used for inline
elements that do not force line breaks. So, if you have a part of a sentence or paragraph you want to
apply CSS style , you can use the < span > element.

e.g.

<html>
<head>
<style type="text/css">
#specialcolor {
color:red;
background: #CCC;
}
</style>
</head>
<body>
<p>
Span tis used to <span id="specialcolor"> styles </span> across
one or more <span id="specialcolor">inline</span> characters or
words.

35
</p>
</body>
</html>

In the above example, you can see the span element styles only two words (styles and inline).

Layers in css:
CSS provides users a good opportunity to make layers of different divisions. The CSS layers are
mentioned here to assign the z-index property to those elements that overlap/collide with one each
other.
The z-index property is utilized along with this position property to make an collision of layers. One
can assign, which element should get displayed on the top of the page and also which element to be
displayed at bottom.
The z-index property is used to aid user to make more complicated webpage layouts. Below is an
example which describes the method of creating layers in CSS.
<html>
<head>
</head>
<body>
<div style="background-color:red; width:300px; height:100px; position:relative; top:10px;
left:80px; z-index:2">
</div>
<div style="background-color:yellow; width:300px; height:100px; position:relative; top:-60px;
left:35px; z-index:1;">
</div>
<div style="background-color:green; width:300px; height:100px; position:relative; top:-220px;
left:120px; z-index:3;">
</div>
</body>
</html>

Elements can overlap for a variety of reasons, for instance relative positioning has nudged it over
something else. Negative margin has pulled the element over another. Absolutely positioned elements
overlap each other. All sorts of reasons.

36
Without any z-index value, elements stack in the order that they appear in the DOM (the lowest
one down at the same hierarchy level appears on top). Elements with non-static positioning will
always appear on top of elements with default static positioning.

Also note that nesting plays a big role. If an element B sits on top of element A, a child element of
element A can never be higher than element B.

END UNIT-2

37
UNIT-3
INTRODUCTION TO JAVASCRIPT

What is DHTML?
Dynamic HyerText Markup Language (DHTML) is a combination of Web development technologies
used to create dynamically changing websites. Web pages may include animation, dynamic menus
and text effects. The technologies used include a combination of HTML, XML JavaScript or VB
Script, CSS and the document object model (DOM).

Designed to enhance a Web user’s experience, DHTML includes the following features:
• Dynamic content, which allows the user to dynamically change Web page content
• Dynamic positioning of Web page elements
• Dynamic style, which allows the user to change the Web page’s color, font, size or content
What is java script? Or
Introduction to javascript.
JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing
the interaction of a user with the webpage. In other words, you can make your webpage more lively
and interactive, with the help of JavaScript. JavaScript is also being used widely in game development
and Mobile application development.
Javascript History
JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a popular browser
of that time. The language was initially called LiveScript and was later renamed JavaScript. There are
many programmers who think that JavaScript and Java are the same. In fact, JavaScript and Java are
very much unrelated. Java is a very complex programming language whereas JavaScript is only a
scripting language. The syntax of JavaScript is mostly influenced by the programming language C.
How to Run JavaScript?
Being a scripting language, JavaScript cannot run on its own. In fact, the browser is responsible
for running JavaScript code. When a user requests an HTML page with JavaScript in it, the script is
sent to the browser and it is up to the browser to execute it. The main advantage of JavaScript is that
all modern web browsers support JavaScript.
Tools You Need
To start with, you need a text editor to write your code and a browser to display the web pages you
develop. You can use a text editor of your choice including Notepad++, Visual Studio Code, Sublime
Text, Atom or any other text editor you are comfortable with. You can use any web browser including
Google Chrome, Firefox, Microsoft Edge, Internet Explorer etc.

38
A Simple JavaScript Program
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>

Summary

• JavaScript is a client-side scripting language developed by Brendan Eich.


• JavaScript can be run on any operating systems and almost all web browsers.
• You need a text editor to write JavaScript code and a browser to display your web page.

JavaScript Variable:
Declare, Assign a Value
Variables are used to store values (name = "John") or expressions (sum = x + y).
Declare Variables in JavaScript
Before using a variable, you first need to declare it. You have to use the keyword var to declare a
variable like this:
var name;
Assign a Value to the Variable
You can assign a value to the variable either while declaring the variable or after declaring the
variable.
var name = "John";
OR
var name;

name = "John";
Naming Variables
Though you can name the variables as you like, it is a good programming practice to give descriptive
and meaningful names to the variables. Moreover, variable names should start with a letter and they
are case sensitive. Hence the variables student name and studentName are different because the letter
n in a name is different (n and N).

<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");

39
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
String manipulations:

In JavaScript, the textual data is stored as strings. There is no separate type for a single character.
Strings can be enclosed within either single quotes, double quotes or backticks:
• let single = 'single-quoted';
• let double = "double-quoted";

• let backticks = `backticks`;


Single and double quotes are essentially the same.
Here is a list of all the basic JavaScript String Functions for your reference. They include functions for
basic string manipulation and are very useful for jQuery scripts.

Examples of the JavaScript string functions in action

1. charAt(x) Returns the character at the “x” position within the string.
//charAt(x)
var myString = 'jQuery FTW!!!';
console.log(myString.charAt(7));
//output: F
2. charCodeAt(x) Returns the Unicode value of the character at position “x” within the string.
//charAt(position)
var message="jquery4u"
//alerts "q"
alert(message.charAt(1))
3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into the existing one and
returns the combined string. Original string is not modified.
//concat(v1, v2,..)
var message="Sam"
var final=message.concat(" is a"," hopeless romantic.")
//alerts "Sam is a hopeless romantic."
alert(final)

4. fromCharCode(c1, c2,…) Returns a string created by using the specified sequence of Unicode
values (arguments c1, c2 etc). Method of String object, not String instance. For example:
String.fromCharCode().

//fromCharCode(c1, c2,...)
console.log(String.fromCharCode(97,98,99,120,121,122))
//output: abcxyz
console.log(String.fromCharCode(72,69,76,76,79))
//output: HELLO
//(PS - I have no idea why you would use this? any ideas?)

5. indexOf(substr, [start]) Searches and (if found) returns the index number of the searched
character or substring within the string. If not found, -1 is returned. “Start” is an optional argument
specifying the position within string to begin the search. Default is 0.

40
//indexOf(char/substring)
var sentence="Hi, my name is Sam!"
if (sentence.indexOf("Sam")!=-1)
alert("Sam is in there!")

6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of the searched
character or substring within the string. Searches the string from end to beginning. If not found, -1 is
returned. “Start” is an optional argument specifying the position within string to begin the search.
Default is string.length-1.

//lastIndexOf(substr, [start])
var myString = 'javascript rox';
console.log(myString.lastIndexOf('r'));
//output: 11

7. match(regexp) Executes a search for a match within a string based on a regular expression. It
returns an array of information or null if no match is found.

//match(regexp) //select integers only


var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';


var myInt = myNumber.match(intRegex);
console.log(isInt);
//output: 999

var myString = '999 JS Coders';


var myInt = myString.match(intRegex);
console.log(isInt);
//output: null

8. replace(regexp/substr, replacetext) Searches and replaces the regular expression (or sub string)
portion (match) with the replaced text instead.

//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
console.log(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders

//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
console.log(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders

9. search(regexp) Tests for a match in a string. It returns the index of the match, or -1 if not found.

//search(regexp)
var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';


var isInt = myNumber.search(intRegex);
console.log(isInt);
//output: 0

41
var myString = '999 JS Coders';
var isInt = myString.search(intRegex);
console.log(isInt);
//output: -1

10. slice(start, [end]) Returns a substring of the string based on the “start” and “end” index
arguments, NOT including the “end” index itself. “End” is optional, and if none is specified, the slice
includes all characters from “start” to end of string.

//slice(start, end)
var text="excellent"
text.slice(0,4) //returns "exce"
text.slice(2,4) //returns "ce"

11. split(delimiter, [limit]) Splits a string into many according to the specified delimiter, and returns
an array containing each element. The optional “limit” is an integer that lets you specify the maximum
number of elements to return.

//split(delimiter)
var message="Welcome to jQuery4u"
//word[0] contains "We"
//word[1] contains "lcome to jQuery4u"
var word=message.split("l")

12. substr(start, [length]) Returns the characters in a string beginning at “start” and through the
specified number of characters, “length”. “Length” is optional, and if omitted, up to the end of the
string is assumed.

//substring(from, to)
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"

13. substring(from, [to]) Returns the characters in a string between “from” and “to” indexes, NOT
including “to” inself. “To” is optional, and if omitted, up to the end of the string is assumed.

//substring(from, [to])
var myString = 'javascript rox';
myString = myString.substring(0,10);
console.log(myString)
//output: javascript

14. toLowerCase() Returns the string with all of its characters converted to lowercase.

//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
console.log(myString)
//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted to uppercase.

//toUpperCase()
var myString = 'javascript rox';

42
myString = myString.toUpperCase();
console.log(myString)
//output: JAVASCRIPT ROX

JavaScript Math Functions:


Mathematical operations are among the most fundamental and universal features of any
programming language. JavaScript supports many arithmetic operations as well as the following
math functions.

avaScript Math
Description
Functions
abs(x) It will return the Absolute value of a Given number
acos(x) It will return the ArcCosine value of a Given number
Used to return the Hyperbolic Arc Cosine (inverse Hyperbolic Cosine)
acosh(x)
value of a Given number
asin(x) It will return the Arc Sine value of a Given number
It will return the Hyperbolic Arc Sine (inverse Hyperbolic Sine) value of
asinh(x)
a Given number
atan(x) This returns the Arc Tangent value of a Given number
It will return the angle (in radius) from the X-Axis to the specified point
atan2(y, x)
(y, x).
cbrt(x) Used to find the Cube Root of a Given number
Returns the Hyperbolic Arc Tangent (inverse Hyperbolic Tangent) value
atanh(x)
of a Given number
It is used to return the smallest integer value which is greater than or
ceil(x)
equal to the specified expression or a number.
cos(x) This returns the Cosine value of a Given number
cosh(x) Return the Hyperbolic Cosine value of a Given number
It is used to calculate the power of E, Where E is Euler’s number
exp(x)
approximately equal to 2.71828.
This returns the largest integer value which is less than or equal to the
floor(x)
specified expression or a number.
hypot(value1,
It will extract the characters from a string based on the specified indices
value2,…..valueN)
log(x) It calculates the logarithmic value of given number with base E.
It is used to return the Maximum or Largest value from the specified set
max(1, 2, 3, …..n)
of expression
Return the Minimum or Smaller value from the specified set of
min(1, 2, 3, …..n)
expression
pow(x, y) It is used to calculate the Power of the specified expression
random() This function will return the random number between 0 and 1
It is used to round the specified expression or an individual number to the
round(x)
nearest integer.
It will return the sign of a Given number. For instance, Positive, Negative
sign(x)
or Zero
sin(x) Return the Sine value of a Given number

43
sinh(x) Return the Hyperbolic Sine value of a Given number
It is used to find the square root of a specified expression or an individual
sqrt(x)
number
tan(x) Return the Tangent value of a Given number
tanh(x) It will return the Hyperbolic Tangent value of a Given number
It is used to remove the decimal values from specified expression and
trunc(x)
return the integer value

Statements in javascript:

While writing a program, there may be a situation when you need to adopt one out of a given set of
paths. In such cases, you need to use conditional statements that allow your program to make correct
decisions and perform right actions.

JavaScript supports conditional statements which are used to perform different actions based on
different conditions. Here we will explain the if..else statement.

Flow Chart of if-else


The following flow chart shows how the if-else statement works.

JavaScript supports the following forms of if..else statement −


• if statement
• if...else statement
• if...else if... statement.
if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be not executed. Most of the times, you
will use comparison operators while making decisions.
Example
Try the following example to understand how the if statement works.
.

44
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Qualifies for driving
Set the variable to different value and then try...
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’
block, are executed. If the expression is false, then the given statement(s) in the else block are
executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for
driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Does not qualify for driving
Set the variable to different value and then try...
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.

45
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part of
the else clause of the previous statement. Statement(s) are executed based on the true condition, if
none of the conditions is true, then the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output
Maths Book
Set the variable to different value and then try...

You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway
branch. However, this is not always the best solution, especially when all of the branches depend on
the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and
it does so more efficiently than repeated if...else if statements.
Flow Chart
The following flow chart explains a switch-case statement works.
Syntax
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case against
the value of the expression until a match is found. If nothing matches, a default condition will be
used.
switch (expression) {
case condition 1: statement(s)
break;

46
case condition 2: statement(s)
break;
...

case condition n: statement(s)


break;

default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would
continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Example
Try the following example to implement switch-case statement.
.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;

case 'B': document.write("Pretty good<br />");


break;

case 'C': document.write("Passed<br />");


break;

case 'D': document.write("Not so good<br />");


break;

case 'F': document.write("Failed<br />");


break;

default: document.write("Unknown grade<br />")


}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following code that uses switch-
case statement without any break statement.

47
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...

While writing a program, you may encounter a situation where you need to perform an action over
and over again. In such situations, you would need to write loop statements to reduce the number of
lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The
purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is
true. Once the expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −

Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

48
document.write("Starting Loop ");

while (count < 10) {


document.write("Current Count : " + count + "<br
/>");
count++;
}

document.write("Loop stopped!");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of
the loop. This means that the loop will always be executed at least once, even if the condition is false.
Flow Chart
The flow chart of a do-while loop would be as follows −

Syntax
The syntax for do-while loop in JavaScript is as follows −
do {
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
Example
Try the following example to learn how to implement a do-while loop in JavaScript.
.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do {
document.write("Current Count : " + count + "<br
/>");

49
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...

The 'for' loop is the most compact form of looping. It includes the following three important parts −
• The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
• The test statement which will test if a given condition is true or not. If the condition is true,
then the code given inside the loop will be executed, otherwise the control will come out of
the loop.
• The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows −

Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
.
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>

50
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet,
you may not feel comfortable with this loop. But once you understand how objects behave in
JavaScript, you will find this loop very useful.
Syntax
The syntax of ‘for..in’ loop is −
for (variablename in object) {
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop continues till all
the properties of the object are exhausted.
Example
Try the following example to implement ‘for-in’ loop. It prints the web browser’s Navigator object.
.
<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>
Output
Navigator Object Properties
serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages

51
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Set the variable to different object and then try...

JavaScript provides full control to handle loops and switch statements. There may be a situation when
you need to come out of a loop without reaching its bottom. There may also be a situation when you
want to skip a part of your code block and start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements. These statements
are used to immediately come out of any loop or to start the next iteration of any loop respectively.
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a loop
early, breaking out of the enclosing curly braces.
Flow Chart
The flow chart of a break statement would look as follows −

Example
The following example illustrates the use of a break statement with a while loop. Notice how the loop
breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the
closing curly brace −
.
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20) {


if (x == 5) {
break; // breaks out of loop completely
}

52
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Output
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
We already have seen the usage of break statement inside a switch statement.
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip
the remaining code block. When a continue statement is encountered, the program flow moves to the
loop check expression immediately and if the condition remains true, then it starts the next iteration,
otherwise the control comes out of the loop.
Example
This example illustrates the use of a continue statement with a while loop. Notice how the continue
statement is used to skip printing when the index held in variable x reaches 5 −
.
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10) {


x = x + 1;

if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering the loop
2
3
4
6

53
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...
Using Labels to Control the Flow
Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more
precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a
block of code. We will see two different examples to understand how to use labels with break and
continue.
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name.
Also, there should not be any other statement in between a label name and associated loop.
Try the following two examples for a better understanding of Labels.
Example 1
The following example shows how to implement Label with a break statement.
.
<html>
<body>
<script type = "text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; // Quit the
innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer
loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Output
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0

54
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!
Example 2
<html>
<body>

<script type = "text/javascript">


<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name

for (var i = 0; i < 3; i++) {


document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}

document.write("Exiting the loop!<br /> ");


//-->
</script>

</body>
</html>
Output
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!
Javascript Operators
JavaScript includes operators as in other languages. An operator performs some operation on single or
multiple operands (data value) and produces a result. For example 1 + 2, where + sign is an operator
and 1 is left operand and 2 is right operand. + operator adds two numeric values and produces a result
which is 3 in this case.

JavaScript includes following categories of operators.


1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators

55
4. Assignment Operators
5. Conditional Operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
+ Adds two numeric operands.
- Subtract right operand from left operand
* Multiply two numeric operands.
/ Divide left operand by right operand.
% Modulus operator. Returns remainder of two operands.
++ Increment operator. Increase operand value by one.
-- Decrement operator. Decrease value by one.
Comparison Operators
JavaScript language includes operators that compare two operands and return Boolean value true or
false.
Operators Description
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type.
!= Compares inequality of two operands.
Checks whether left side value is greater than right side value. If yes then returns true
>
otherwise false.
Checks whether left operand is less than right operand. If yes then returns true otherwise
<
false.
Checks whether left operand is greater than or equal to right operand. If yes then returns
>=
true otherwise false.
Checks whether left operand is less than or equal to right operand. If yes then returns true
<=
otherwise false.
Logical Operators
Logical operators are used to combine two or more conditions. JavaScript includes following logical
operators.
Operator Description
&& is known as AND operator. It checks whether two operands are non-zero (0, false,
&&
undefined, null or "" are considered as zero), if yes then returns 1 otherwise 0.
|| is known as OR operator. It checks whether any one of the two operands is non-zero (0,
||
false, undefined, null or "" is considered as zero).
! ! is known as NOT operator. It reverses the boolean result of the operand (or condition)
Assignment Operators
JavaScript includes assignment operators to assign values to variables with less key strokes.
Assignment
Description
operators
= Assigns right operand value to left operand.
+= Sums up left and right operand values and assign the result to the left operand.
Subtract right operand value from left operand value and assign the result to the
-=
left operand.
*= Multiply left and right operand values and assign the result to the left operand.
/= Divide left operand value by right operand value and assign the result to the left

56
Assignment
Description
operators
operand.
Get the modulus of left operand divide by right operand and assign resulted
%=
modulus to the left operand.

Ternary Operator

JavaScript includes special operator called ternary operator :? that assigns a value to a variable based
on some condition. This is like short form of if-else condition.

Syntax:
<condition> ? <value1> : <value2>;

Ternary operator starts with conditional expression followed by ? operator. Second part ( after ? and
before : operator) will be executed if condition turns out to be true. If condition becomes false then
third part (after :) will be executed.

Example: Ternary operator


var a = 10, b = 5;

var c = a > b? a : b; // value of c would be 10


var d = a > b? b : a; // value of d would be 5

JavaScript Array
An array is a special type of variable, which can store multiple values using special syntax. Every
value is associated with numeric index starting with 0. The following figure illustrates how an array
stores values.

JavaScript Array
Array Initialization

An array in JavaScript can be defined and initialized in two ways, array literal and Array constructor
syntax.

Array Literal

Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in square
brackets.

Syntax:
var <array-name> = [element0, element1, element2,... elementN];
The following example shows how to define and initialize an array using array literal syntax.

Example: Declare and Initialize JS Array


var stringArray = ["one", "two", "three"];

var numericArray = [1, 2, 3, 4];

57
var decimalArray = [1.1, 1.2, 1.3];

var booleanArray = [true, false, false, true];

var mixedArray = [1, "two", "three", 4];


JavaScript array can store multiple element of different data types. It is not required to store value of
same data type in an array.

Accessing Array Elements

An array elements (values) can be accessed using index (key). Specify an index in square bracket with
array name to access the element at particular index. Please note that index of an array starts from
zero in JavaScript.

Example: Access Array Elements


var stringArray = new Array("one", "two", "three", "four");

stringArray[0]; // returns "one"


stringArray[1]; // returns "two"
stringArray[2]; // returns "three"
stringArray[3]; // returns "four"

var numericArray = [1, 2, 3, 4];


numericArray[0]; // returns 1
numericArray[1]; // returns 2
numericArray[2]; // returns 3
numericArray[3]; // returns 4

JavaScript - Functions
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions.
A JavaScript function can be defined using function keyword.
Syntax:
//defining a function
function <function-name>()
{
// code to be executed
};

//calling a function
<function-name>();
The following example shows how to define and call a function in JavaScript.
Example: Define and Call a Function
function ShowMessage() {
alert("Hello World!");
}

ShowMessage();
In the above example, we have defined a function named ShowMessage that displays a popup
message "Hello World!". This function can be execute using () operator e.g. ShowMessage().

58
Function Parameters
A function can have one or more parameters, which will be supplied by the calling code and can be
used inside a function. JavaScript is a dynamic type scripting language, so a function parameter can
have value of any data type.
Example: Function Parameters
function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
You can pass less or more arguments while calling a function. If you pass less arguments then rest of
the parameters will be undefined. If you pass more arguments then additional arguments will be
ignored.
Example: Function Parameters
function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs", "Mr."); // display Hello Steve Jobs


ShowMessage("Bill"); // display Hello Bill undefined
ShowMessage(); // display Hello undefined undefined
The Arguments Object
All the functions in JavaScript can use arguments object by default. An arguments object includes
value of each parameter.
The arguments object is an array like object. You can access its values using index similar to array.
However, it does not support array methods.
Example: Arguments Object
function ShowMessage(firstName, lastName) {
alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs");

ShowMessage("Bill", "Gates");

ShowMessage(100, 200);
An arguments object is still valid even if function does not include any parameters.
Example: Arguments Object
function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Steve", "Jobs"); // display Hello Steve Jobs


An arguments object can be iterated using for loop.
Example: Iterate all Arguments
function ShowMessage() {

for(var i = 0; i < arguments.length; i++){


alert(arguments[i]);
}
}

ShowMessage("Steve", "Jobs");

59
Return Value
A function can return zero or one value using return keyword.
Example: Return value From a Function
function Sum(val1, val2) {
return val1 + val2;
};

var result = Sum(10,20); // returns 30

function Multiply(val1, val2) {


console.log( val1 * val2);
};

result = Multiply(10,20); // undefined


In the above example, a function named Sum adds val1 & val2 and return it. So the calling code can
get the return value and assign it to a variable. The second function Multiply does not return any
value, so result variable will be undefined.
A function can return another function in JavaScript.
Example: Function Returning a Function
function multiple(x) {

function fn(y)
{
return x * y;
}

return fn;
}

var triple = multiple(3);


triple(2); // returns 6
triple(3); // returns 9
Function Expression
JavaScript allows us to assign a function to a variable and then use that variable as a function. It is
called function expression.
Example: Function Expression
var add = function sum(val1, val2) {
return val1 + val2;
};

var result1 = add(10,20);


var result2 = sum(10,20); // not valid

Anonymous Function

Anonymous function is useful in passing callback function, creating closure or Immediately


invoked function expression.
JavaScript allows us to define a function without any name. This unnamed function is called
anonymous function. Anonymous function must be assigned to a variable.
Example: Anonymous Function
var showMessage = function (){
alert("Hello World!");
};

60
showMessage();

var sayHello = function (firstName) {


alert("Hello " + firstName);
};

showMessage();

sayHello("Bill");
Nested Functions
In JavaScript, a function can have one or more inner functions. These nested functions are in the
scope of outer function. Inner function can access variables and parameters of outer function.
However, outer function cannot access variables defined inside inner functions.
Example: Nested Functions
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}

return SayHello();
}

ShowMessage("Steve");

Points to Remember :
1. JavaScript a function allows you to define a block of code, give it a name and then execute it
as many times as you want.
2. A function can be defined using function keyword and can be executed using () operator.
3. A function can include one or more parameters. It is optional to specify function parameter
values while executing it.
4. JavaScript is a loosely-typed language. A function parameter can hold value of any data type.
5. You can specify less or more arguments while calling function.
6. All the functions can access arguments object by default instead of parameter names.
7. A function can return a literal value or another function.
8. A function can be assigned to a variable with different name.
9. JavaScript allows you to create anonymous functions that must be assigned to a variable.

61
Unit-4
Objects in javascript

Introduction to Object Oriented Programming in JavaScript


As JavaScript is widely used in Web Development, in this article we would explore some of the
Object Oriented mechanism supported by JavaScript to get most out of it. Some of the common
interview question in JavaScript on OOPS includes,- “How Object Oriented Programming is
implemented in JavaScript? How they differ from other languages? Can you implement Inheritance in
JavaScript and so on…”
There are certain features or mechanisms which makes a Language Object Oriented like:
• Object
• Classes
• Encapsulation
• Inheritance
Let’s dive into the details of each one of them and see how they are implemented in JavaScript.
Object – An Object is a unique entity which contains property and methods. For example “car” is a
real life Object, which have some characteristics like color, type, model, horsepower and performs
certain action like drive. The characteristics of an Object are called as Property, in Object Oriented
Programming and the actions are called methods. An Object is an instance of a class. Objects are
everywhere in JavaScript almost every element is an Object whether it is a function,arrays and string.
Object can be created in two ways in JavaScript:
Using an Object Literal
// Defining Object
var person = {
// Propertise
first_name: "Sumit",
last_name: "Ghosh",

// Methods
getName: function ()
{
return "Person name is " + this.first_name +
" " + this.last_name;
},
// Object within Object
phone_number:
{
Mobile: "12345",
LandLine: " 678910"
}
}
console.log(person.getName());
console.log("Persons First Name " + person.first_name
+ " Landline number " + person.phone_number.LandLine);

Using an Object Constructor


// construtor to initialize variables

62
function person(first, last) {
this.firstName = first;
this.lastName = last;
}

// using prototype to define methods


person.prototype.getDetails = function () {
return "Person name is " + this.firstName +
" " + this.lastName;
}

var P1 = new person("Sumit", "Ghosh");


console.log(P1.firstName);
console.log(P1.getDetails());

There is another way of creating a JavaScript Object i.e. by using new Keyword but it is similar to
creating Object with Object Literal.
Classes – Classes are blueprint of an Object.A class can have many Object, because class is a
template while Object are instances of the class or the concrete implementation.
Before we move further into implementation, we should know unlike other Object Oriented Language
their is no classes in JavaScript we have only Object. To be more precise, JavaScript is a prototype
based object oriented language, which means it doesn’t have classes rather it define behaviors using
constructor function and then reuse it using prototype.

Regular expression:
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-replace
functions on text.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Here is the description of the parameters −
• pattern − A string that specifies the pattern of the regular expression or another regular
expression.
• attributes − An optional string containing any of the "g", "i", and "m" attributes that specify
global, case-insensitive, and multi-line matches, respectively.

Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used
to find a range of characters.
Sr.No. Expression & Description
[...]
1
Any one character between the brackets.
2 [^...]

63
Any one character not between the brackets.
[0-9]
3
It matches any decimal digit from 0 through 9.
[a-z]
4
It matches any character from lowercase a through lowercase z.
[A-Z]
5
It matches any character from uppercase A through uppercase Z.
[a-Z]
6
It matches any character from lowercase a through uppercase Z.

function upper_case(str)
{
regexp = /^[A-Z]/;
if (regexp.test(str))
{
console.log("String's first character is uppercase");
}
else
{
console.log("String's first character is not uppercase");
}
}
upper_case('Abcd');
upper_case('abcd');

sample program2:
function checkPhoneNumber(phoneNo) {
var phoneRE = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
if (phoneNo.match(phoneRE)) {
return true;
} else {
alert( "The phone number entered is invalid!" );
return false;
}
}

Exceptional Handling:
An error is an action which is inaccurate or incorrect. There are three types of error in programming
which are discusses below :
• Syntax error
• Logical error
• Runtime error
Syntax error: According to computer science, a syntax error is an error in the syntax of a sequence of
characters or tokens that is intended to be written in a particular programming language or it is also
the compile-time error if the syntax is not correct then it will give an error message.

64
Example:
<script type="text/javascript">

// Here the semicolon after the printing statement


// is missing and it is a syntax error
window.print()

</script>
As the syntax is not correct of the JavaScript it will affect only the thread that is under this JavaScript
and the rest of the code in other threads gets executed as nothing in them depends on the code
containing the error.
Logical error: It is the most difficult error to be traced as it is the error on the logical part of the
coding or logical error is a bug in a program that causes it to operate incorrectly and terminate
abnormally (or crash).

Runtime Error: A runtime error is an error that occurs during the running of the program, also
known as the exceptions. In the example that is given below the syntax is correct, but at runtime, it is
trying to call a method that does not exist.
Example:
<script type="text/javascript">

// An runtime error here


window.printme();

</script>
As in runtime error, there are exceptions and this exception is correct by the help of the try and catch
method
try ___ catch method: JavaScript uses the try catch and finally to handle the exception and it also
used the throw operator to handle the exception. try have the main code to run and in the catch, give
the exception statement all the things that are related to the exception.
Syntax:
<script type="text/javascript">
<!--
try
{
// Here the main Code run
[break;]
}

catch ( exception e )
{
// The code will run when there is an exception
[break;]
}
//-->
</script>

Example 1:

65
<html>
<head>
<title>Error and Exception handling</title>
<script type="text/javascript">
function First() {
var a = 123;
var b = 145;
var c = a + b;
alert("Value of a: " + a );
alert("Value of b: " + b );
alert("Sum of a and b: " + c);
}
</script>
</head>

<body>
<p>Click the GfG button to see the result:</p>

<form>
<input type="button" value="Click GfG" onclick="First();" />
</form>

</body>
</html>

built in objects in javascript:


JavaScript has several built-in or core language objects. These built-in objects are available regardless
of window content and operate independently of whatever page your browser has loaded.

Array Object
• Multiple values are stored in a single variable using the Array object.
• In JavaScript, an array can hold different types of data types in a single slot, which implies
that an array can have a string, a number or an object in a single slot.
• An Array object can be created by using following ways:
Using the Array Constructor:
To create empty array when don’t know the exact number of elements to be inserted in an array
var arrayname = new Array();
To create an array of given size
var arrayname = new Array(size);

66
To create an array with given elements
var arrayname = new Array(“element 1”,”element 2”,……..,”element n”);
Using the Array Literal Notation:
To create empty array
var arrayname =[ ];
To create an array when elements are given
var arrayname =[“element 1”,”element 2”,……..,”element n”];
• Properties of the Array object
o Length - Returns the number of elements in the array.
o Constructor - Returns the function that created the Array object.
o Prototype - Add properties and methods to an object.
• Methods of the Array object
o reverse() - Reverses the array elements
o concat() - Joins two or more arrays
o sort() - Sort the elements of an array
o push() - Appends one or more elements at the end of an array
o pop() - Removes and returns the last element
o shift() - Removes and returns the first element
• unshift(), join(), indexOf(), lastIndexOf(), slice(startindex, endindex) are some of the methods
used in Array object.
Boolean Object
• The Boolean object is wrapper class and member of global objects.
• It is used to convert a non-Boolean value to a Boolean value (true or false).
• If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the
object is set to false. Otherwise it is true (even with the string "false")!
• Boolean object can be created by using following ways:
Using Boolean Literal Notation: var bool = true;
Using Boolean Object as Function: var bool = Boolean(true);
Using Testable Expressions: if(true) {………….}
• Properties of the Boolean object
o Constructor - Returns the function that created the Boolean object.
o Prototype - Add properties and methods to an object.
• Methods of the Boolean object
o toSource() - Returns a string containing the source of the Boolean object; you can
use this string to create an equivalent object.
o toString() - Returns a string of either "true" or "false" depending upon the value of
the object.
o valueOf() - Returns the primitive value of the Boolean object
Date Object
• At times when user need to access the current date and time and also past and future date and
times. JavaScript provides support for working with dates and time through the Date object.
• The Date object provides a system-independent abstraction of dates and times.
• Date object can be created as : var today = new Date( );
• Dates may be constructed from a year, month, day of the month, hour, minute, and second,
and those six components, as well as the day of the week, may be extracted from a date.
• Dates may also be compared and converted to a readable string form. A Date is represented to
a precision of one millisecond.

67
• Properties of Date object
o Constructor - Returns the function that created the Date object.
o Prototype - Add properties and methods to an object.
• Methods of Date object
o Date() - Returns today's date and time
o getDate() - Returns the day of the month for the specified date
o getDay() - Returns the day of the week for the specified date
o getFullYear() - Returns the year of the specified date
o getHours() - Returns the hour in the specified date according to local time.
o getMilliseconds() - Returns the milliseconds in the specified date according to local
time.
• getMinute(), getMonth(), getTime(), getTimezoneOffset(), setDate(), setFullYear(),
setHours(), setMilliseconds(), setMinutes(), setMonth(), setSeconds(), setTime() are some of
the methods used in Date object.
Math Object
• The Math object is used to perform simple and complex arithmetic operations.
• The Math object provides a number of properties and methods to work with Number values
• The Math object does not have any constructors. All of its methods and properties are static;
that is, they are member functions of the Math object itself. There is no way to create an
instance of the Math object.
• Properties of Math object
o PI - The value of Pi
o E - The base of natural logarithm e
o LN2 - Natural logarithm of 2
o LN10 - Natural logarithm of 10
o LOG2E - Base 2 logarithm of e
o LOG10E - Base 10 logarithm of e
o SQRT2 - Square root of 2
o SQRT1_2 - Square root of ½
• Methods of Math object
o max(a,b) - Returns largest of a and b
o min(a,b) - Returns least of a and b
o round(a) - Returns nearest integer
o ceil(a) - Rounds up. Returns the smallest integer greater than or equal to a
o floor(a) - Rounds down. Returns the largest integer smaller than or equal to a
o exp(a) - Returns ea
o pow(a,b) - Returns ab
o abs(a) - Returns absolute value of a
o random() - Returns a pseudo random number between 0 and 1
o sqrt(a) - Returns square root of a
o sin(a) - Returns sin of a (a is in radians)
o cos(a) - Returns cos of a (a is in radians)
Number Object
• The Number objects represents numerical date, either integers or floating-point numbers.
• A Number objects are created using the Number() constructor var num = new
number(value);
• Properties of Number object
o Constructor - Returns the function that created the Number object.

68
o MAX VALUE - Returns maximum numerical value possible in JavaScript.
o MIN VALUE - Returns minimum numerical value possible in JavaScript.
o NEGATIVE INFINITY - Represent the value of negative infinity.
o POSITIVE INFINITY - Represent the value of infinity.
o Prototype - Add properties and methods to an object.
• Methods of Number object
o toExponential() - Converts a number into exponential notation.
o toFixed() - Formats a number with a specific number of digits to the right of the
decimal.
o toLocaleString() - Returns a string value version of the current number in a format
that may vary according to a browser's locale settings.
o toPrecision() - Defines how many total digits to display of a number.
o toString() - Returns the string representation of the number's value.
o valueOf() - Returns the number's value.
String Object
• in JavaScript, all strings are represented as instances of the String object.
• The String object is wrapper class and member of global objects.
• String object used to perform operations on the stored text, such as finding the length of the
string, searching for occurrence of certain characters within string, extracting a substring etc.
• A String is created by using literals. A string literal is either enclosed within single quotes(‘ ‘)
or double quotes(“ “) var string1= “ Ques10“ ;
• Properties of String object
o Length - Returns the length of string.
o Constructor - Returns the function that created the String object
o Prototype - Add properties and methods to an object
• Methods of String object
o charAt() - Returns the character at a specified position.
o concat() - Combines two or more strings.
o toLowerString() - Converts a string to lowercase.
o toUpperString() - Converts a string to uppercase.
o indexOf(searchtext, index) - Searches for the specified string from the beginning of
the string.
o lastIndexof(searchtext, index) - Searches for the specified string from the end of the
string
RegExp Object
• RegExp object used to validate the pattern of characters.
• RegExp define methods that use regular expressions to perform powerful pattern-matching
and search and replace functions on text.
• Regular expressions can be defined by using following ways
Using RegExp() Constructor: var RegularExpression = new
RegExp(“pattern”,”flag”);
Using Literal: var RegularExpression = /pattern/flag;
• Pattern – A String that specifies the pattern of the regular expression or another regular
expression.
• Flag – An optional string containing any of the “g”, “I” and “m” attributes that specify
global, case-insensitive and multiple matches respectively.
• Properties of RegExp object

69
o Constructor - Returns the function that created the RegExp object
o Global - Checks whether the "g" modifier is set
o ignoreCase - Checks whether the "i" modifier is set
o lastIndex - Specifies the index at which to start the next match
o multiline - Checks whether the "m" modifier is set
o source - Returns the text of the RegExp pattern
• Methods of RegExp object
o exec() - Tests for a match in a string. Returns the first match.
o test() - Tests for a match in a string. Returns true or false.
o toString() - Returns the string value of the regular expression.
o toSource() - Returns an object literal representing the specified object.

Javascript events:

What is an Event ?

JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of
response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a
set of events which can trigger JavaScript Code.

onclick Event Type

70
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.

Example
Try the following example.

<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

onsubmit Event Type

onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function before
submitting a form data to the webserver. If validate() function returns true, the form will be
submitted, otherwise it will not submit the data.

Try the following example.

<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>

71
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

onmouseover and onmouseout

These two event types will help you create nice effects with images or even with text as well. The
onmouseover event triggers when you bring your mouse over any element and the onmouseout
triggers when you move your mouse out from that element. Try the following example.

<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

Unit-5
DHTML WITH JAVASCRIPT

72
Data validation in javascript:
Form validation normally used to occur at the server, after the client had entered all the necessary data
and then pressed the Submit button. If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the client and request that the form be
resubmitted with correct information. This was really a lengthy process which used to put a lot of
burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web
server. Form validation generally performs two functions.

• Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check for
data.
• Data Format Validation − Secondly, the data that is entered must be checked for correct
form and value. Your code must include appropriate logic to test correctness of data.

Example

We will take an example to understand the process of validation. Here is a simple form in html
format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>

<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>

<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>

73
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

</table>
</form>
</body>
</html>
Basic Form Validation
First let us see how to do a basic form validation. In the above form, we are calling validate() to
validate data when onsubmit event is occurring. The following code shows the implementation of this
validate() function.
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
</script>
Data Format Validation
Now we will see how we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address. An email address must
contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email
address, and the last dot must at least be one character after the ‘@’ sign.
Example

74
Try the following code for email validation.

<script type = "text/javascript">


<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>

Opening and closing windows


A window is created automatically when a user launches Navigator, and a user can open a window by
choosing New Web Browser from the Navigator's File menu. A user can close a window by choosing
either Close or Exit from the Navigator's File menu. You can also open and close windows
programmatically.
Opening a window
You can create a window with the open method. The following statement creates a window called
msgWindow that displays the contents of the file sesame.html:

msgWindow=window.open("sesame.html")

The following statement creates a window called homeWindow that displays the Netscape home page:

homeWindow=window.open("http://www.netscape.com")

Windows can have two names. The following statement creates a window with two names. The first
name, "msgWindow", is used when referring to the window's properties, methods, and containership;
the second name, "displayWindow", is used when referring to the window as the target of a form
submit or hypertext link.

msgWindow=window.open("sesame.html","displayWindow")

When you create a window, a window name is not required. But if you want to refer to a window
from another window, the window must have a name.
When you open a window, you can specify attributes such as the window's height and width and
whether the window contains a toolbar, location field, or scrollbars. The following statement creates a
window without a toolbar but with scrollbars:

msgWindow=window.open
("sesame.html","displayWindow","toolbar=no,scrollbars=yes")

Closing a window

75
You can close a window programmatically with the close method. You cannot close a frame without
closing the entire parent window.
All of the following statements close the current window:

window.close()
self.close()
// Do not use the following statement in an event handler
close()
The following statement closes a window called msgWindow:
msgWindow.close()

messages and confirmations in javascript:


JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and
alert, or to get confirmation on any input or to have a kind of input from the users. Here we will
discuss each dialog box one by one.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one input
field requires to enter some text but the user does not provide any input, then as a part of validation,
you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button
"OK" to select and proceed.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
Confirmation Dialog Box
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box
with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks
on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;

76
} else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
Prompt Dialog Box
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it
enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label
which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel button,
the window method prompt() returns null.
Example
The following example shows how to use a prompt dialog box −
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

JavaScript Status Bar Messages


JavaScript can be used to display messages in the status bar using window.status. For example,
you can display a javascript status bar message whenever your users hover over your hyperlinks.
Status Bar Example
You can create a status bar message using the following code:
<script>
function writetostatus(input){
window.status=input

77
return true
}
</script>
For example, I create a link below that uses this function to a description of the link onmouse over:
Hide Copy Code
<a href="http://www.google.com" onMouseover="writetostatus('Search the web!')"
onMouseout="writetostatus('')">Google</a>
Conclusion
The key to writing to the status is using the property window.status, and remembering to return
true if you're adding it to a function.
Working with Frames
Some browsers (including the latest Netscape and Microsoft browsers) support frames, which enable
you to divide the browser window into multiple panes. Each frame can contain a separate URL or the
output of a script.
Using JavaScript Objects for Frames
When a window contains multiple frames, each frame is represented in JavaScript by a frame object.
This object is equivalent to a window object, but it is used for dealing with that frame. The frame
object's name is the same as the NAME attribute you give it in the <frame> tag.
Remember the window and self keywords, which refer to the current window? When you are
using frames, these keywords refer to the current frame instead. Another keyword, parent, enables
you to refer to the main window.
Each frame object in a window is a child of the parent window object. Suppose you define a set of
frames using the HTML below:
<frameset ROWS="*,*" COLS="*,*">
<frame NAME="topleft" SRC="topleft.htm">
<frame NAME="topright" SRC="topright.htm">
<frame NAME="bottomleft" SRC="botleft.htm">
<frame NAME="bottomright" SRC="botright.htm">
</frameset>
This simply divides the window into quarters. If you have a JavaScript program in the
topleft.htm file, it would refer to the other windows as parent.topright,
parent.bottomleft, and so on. The keywords window and self would refer to the topleft
frame.
<html>
<head>
<script language="JavaScript">
<!--
function myFunc() {
parent.frames[1].document.open();
parent.frames[1].document.write("frame-text.");
parent.frames[1].document.close();
}
var topFrame = "<a href='http://www.java2s.com' " +"onClick='parent.myFunc()'>Click me</a>";
var botFrame = "";
//-->
</script>
</head>
<frameset rows="50%,*">
<frame src="javascript:parent.topFrame">
<frame src="javascript:parent.botFrame">
</frameset>
</html>

Rollover Buttons

78
What Is a Rollover Button?
A rollover button is a dynamic Web button that changes appearance depending on the location of the
user's mouse pointer. It contains three states: normal, over and down. The normal state appears when
your mouse is off the button, the over state applies when your mouse rolls over the button, and the
down state applies to when you click on the button.

Types and Uses


Rollover buttons come in different shapes, sizes, colors and styles. Since images can be converted to
rollover buttons, a rollover button can also contain images. A rollover button can be raised, sunken,
flat or animated when a user clicks on it.

A rollover button is a dynamic Web button that changes appearance depending on the location of the
user's mouse pointer. It contains three states: normal, over and down. The normal state appears when
your mouse is off the button, the over state applies when your mouse rolls over the button, and the
down state applies to when you click on the button.
Types and Uses
Rollover buttons come in different shapes, sizes, colors and styles. Since images can be converted to
rollover buttons, a rollover button can also contain images. A rollover button can be raised, sunken,
flat or animated when a user clicks on it.
Uses
Rollover buttons are used primarily as navigational buttons on a Web page to direct people to other
locations. They are also used in drop-down and pop-up menus. Other rollover buttons are used for
animated effects and sounds, so an image, color, shape, text or sound can change as the user rolls over
the button on the Web.
Benefits
Rollover buttons extend the normal functionality of a button. Not only are they visually attractive, but
rollover buttons are also dynamic, altering the user to the fact that they're active elements on the page.
Web designers can add sound effects that will play if a user moves his mouse over these buttons.
When used in drop-down or pop-up menus, rollover buttons help save navigational space.
Suggested Size
The file size of a rollover button should be small. Since rollover buttons are images, they can quickly
take up extra space on the Web server and increase loading time.

<<html ">>
<<head>>
<<title>>Quick and Dirty Rollovers<</title>>
<<script type="text/javascript">>
function mouseOn()
{
document.image1.src = "imageon.gif";
}
function mouseOff()
{
document.image1.src = "imageoff.gif";
}
<</script>>
<</head>>
<<body>>
<<a href="#" onmouseover="mouseOn()" onmouseout="mouseOff()">><<img
name="image1" id="image1" src="imageoff.gif" border="0"
width="90" height="90" alt="rollover" />><</a>>
<</body>>
<</html>>
Moving images in javascript:

79
You can use JavaScript to create a complex animation having, but not limited to, the following
elements −

• Fireworks
• Fade Effect
• Roll-in or Roll-out
• Page-in or Page-out
• Object movements

JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML
element) around the page according to some sort of pattern determined by a logical equation or
function.

JavaScript provides the following two functions to be frequently used in animation programs.

• setTimeout( function, duration) − This function calls function after duration milliseconds
from now.
• setInterval(function, duration) − This function calls function after every duration
milliseconds.
• clearTimeout(setTimeout_variable) − This function calls clears any timer set by the
setTimeout() functions.

<script language="Javascript">

function timeout_trigger() {
window.alert('Hello!');
}

function timeout_init() {
setTimeout('timeout_trigger()', 2000);
}

</script>
<input type="button" value="click me" onclick="timeout_init()" />

80

S-ar putea să vă placă și