0% found this document useful (0 votes)
10 views245 pages

HTML Basics: Structure and Tags

HTML, or HyperText Markup Language, is a markup language used for designing web pages by structuring content with predefined tags. It consists of two main parts: the head, which contains metadata, and the body, which displays the content. While HTML is easy to learn and widely supported, it has limitations such as only creating static web pages and requiring extensive code for simple designs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views245 pages

HTML Basics: Structure and Tags

HTML, or HyperText Markup Language, is a markup language used for designing web pages by structuring content with predefined tags. It consists of two main parts: the head, which contains metadata, and the body, which displays the content. While HTML is easy to learn and widely supported, it has limitations such as only creating static web pages and requiring extensive code for simple designs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WEB DESIGN AND DEVELOPMENT

UNIT 1
HTML Introduction
HTML stands for HyperText Markup Language. It is used to design web
pages using a markup language. HTML is the combination of Hypertext and
Markup language. Hypertext defines the link between web pages. A markup
language is used to define the text document within the tag which defines the
structure of web pages. This language is used to annotate (make notes for the
computer) text so that a machine can understand it and manipulate text
accordingly. Most markup languages (e.g. HTML) are human-readable. The
language uses tags to define what manipulation has to be done on the text.

HTML is a markup language used by the browser to manipulate text, images, and
other content, in order to display it in the required format. HTML was created by Tim
Berners-Lee in 1991. The first-ever version of HTML was HTML 1.0, but the first
standard version was HTML 2.0, published in 1995.

Tag Basics
HTML uses predefined tags and elements which tell the browser how to
properly display the content. Remember to include closing tags. If omitted, the
browser applies the effect of the opening tag until the end of the page.

Page 1 of 49
Features of HTML:
• It is easy to learn and easy to use.
• It is platform-independent.
• Images, videos, and audio can be added to a web page.
• Hypertext can be added to the text.
• It is a markup language.
Advantages:
• HTML is used to build websites.
• It is supported by all browsers.
• It can be integrated with other languages like CSS, JavaScript, etc.
Disadvantages:
• HTML can only create static web pages. For dynamic web pages, other
languages have to be used.
• A large amount of code has to be written to create a simple web page.
• The security feature is not good.
STRUCTURE OF HTML

Every Html program contain two parts they are;.

• Head part
• Body part

<HTML> tag: The html tag acts as a container for the whole document. Every character
in the document should be in between the html start and end tags. The html tag can
also be used to define the language of the contained document through the "lang"
attribute. The content of the html tag is divided in two parts using the head (HTML
head tag) and the body (HTML body tag).

Page 2 of 49
<HEAD> tag: This section is the document's head. All the information contained in the
document's head is loaded first, before any other thing in the document, as it's defined
before the body segment. It includes tags like title, script, style, meta and so on.

<BODY> tag: This is the document's body: The body is the container for the visual part
of a document. All the things written here will be shown when the document is
rendered. Most of the tags in HTML can be inserted in the body section (inside the
HTML body tag) and will take care of the visual aspects of the document.

HTML Comments
The comment tag ( <! - - Comment - - > ) is used to insert comments in the
HTML code. It is a good practice of coding, so that coder and the reader can get
help to understand the code. It is useful to understand steps of the complex code.
The comment tag is helpful while the debugging of codes.
• It is a simple piece of code that is wiped off (ignore) by web browsers i.e. ,
not displayed by the browser.
• It helps the coder and reader to understand the piece of code used for
especially in complex source code.
Syntax:
<!-- Comments here -->
Types of HTML Comments:
There are two types of comments in HTML which are:
• Single-line comment
• Multi-lines comment

Single-line comment:
Single line comment is given inside the ( <!– comment –> ) tag.
Example
<!DOCTYPE html>
<html>

<body>
<!--This is heading Tag, It wont be displayed by the browser -->

<h1>GeeksforGeeks</h1>

<!--This is single line comment,It wont be displayed by the browser -->


<h2>This is single line comment</h2>
</body>
</html>

Page 3 of 49
Multi-line comment:

Multiple lines can be given by the syntax (<!– –>), Basically it’s the same as
we used in single line comment, difference is half part of the comment (” –> “), is
appended where the intended comment line ends.

Example

<!DOCTYPE html>
<html>
<body>

<!-- This is
heading tag -->

<h1>GeeksforGeeks</h1>

<!-- This is
multi-line
comment -->

<h2>This is multi-line comment</h2>

</body>
</html>

Output

Page 4 of 49
WORKING WITH TEXT
If you use a word processor, you must be familiar with the ability to make text bold,
italicized, or underlined; these are just three of the ten options available to indicate
how text can appear in HTML and XHTML.
Bold Text
Anything that appears within <b>...</b> element, is displayed in bold as
shown below:
Example
<!DOCTYPE html>
<html>
<head>
<title>Bold Text Example</title>
</head>
<body>
<p>The following word uses a <b>bold</b> typeface.</p>
</body>
</html>
This will produce the following result:
The following word uses a bold typeface.

Italic Text
Anything that appears within <i>...</i> element is displayed in italicized as
shown below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Italic Text Example</title>
</head>
<body>
<p>The following word uses a <i>italicized</i> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses an italicized typeface.

Underlined Text
Anything that appears within <u>...</u> element, is displayed with underline as
shown below:
Example
<!DOCTYPE html>
Page 5 of 49
<html>
<head>
<title>Underlined Text Example</title>
</head>
<body>
<p>The following word uses a <u>underlined</u> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses an underlined typeface.

Strike Text
Anything that appears within <strike>...</strike> element is displayed with
strikethrough, which is a thin line through the text as shown below:
Example
<!DOCTYPE html>
<html>
<head>
<title>Strike Text Example</title>
</head>
<body>
<p>The following word uses a <strike>strikethrough</strike> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses a strikethrough typeface.
Monospaced Font
The content of a <tt>...</tt> element is written in monospaced font. Most of the
fonts are known as variable-width fonts because different letters are of different
widths (for example, the letter 'm' is wider than the letter 'i'). In a monospaced font,
however, each letter has the same width.

Example
<!DOCTYPE html>
<html>
<head>
<title>Monospaced Font Example</title>
</head>
<body>
<p>The following word uses a <tt>monospaced</tt> typeface.</p>
</body>
</html>
Page 6 of 49
This will produce the following result:
The following word uses a monospaced typeface.

Superscript Text
The content of a <sup>...</sup> element is written in superscript; the font size
used is the same size as the characters surrounding it but is displayed half a
character's height above the other characters.
Example
<!DOCTYPE html>
<html>
<head>
<title>Superscript Text Example</title>
</head>
<body>
<p>The following word uses a <sup>superscript</sup> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses a superscript typeface.

Subscript Text
The content of a <sub>...</sub> element is written in subscript; the font size
used is the same as the characters surrounding it, but is displayed half a character's
height beneath the other characters.

Example
<!DOCTYPE html>
<html>
<head>
<title>Subscript Text Example</title>
</head>
<body>
<p>The following word uses a <sub>subscript</sub> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses a subscript typeface.

Inserted Text
Anything that appears within <ins>...</ins> element is displayed as inserted
text.
Page 7 of 49
Example
<!DOCTYPE html>
<html>
<head>
<title>Inserted Text Example</title>
</head>
<body>
<p>I want to drink <del>cola</del> <ins>wine</ins></p>
</body>
</html>

Deleted Text
Anything that appears within <del>...</del> element, is displayed as deleted
text.
Example
<!DOCTYPE html>
<html>
<head>
<title>Deleted Text Example</title>
</head>
<body>
<p>I want to drink <del>cola</del> <ins>wine</ins></p>
</body>
</html>

Larger Text
The content of the <big>...</big> element is displayed one font size larger
than the rest of the text surrounding it as shown below:
Example
<!DOCTYPE html>
<html>
<head>
<title>Larger Text Example</title>
</head>
<body>
<p>The following word uses a <big>big</big> typeface.</p>
</body>
</html>

Smaller Text
The content of the <small>...</small> element is displayed one font size
smaller than the rest of the text surrounding it as shown below:
Example
<!DOCTYPE html>
Page 8 of 49
<html>
<head>
<title>Smaller Text Example</title>
</head>
<body>
<p>The following word uses a <small>small</small> typeface.</p>
</body>
</html>

Grouping Content
The <div> and <span> elements allow you to group together several elements
to create sections or subsections of a page.
For example, you might want to put all of the footnotes on a page within a <div>
element to indicate that all of the elements within that <div> element relate to the
footnotes. You might then attach a style to this <div> element so that they appear
using a special set of style rules.
Example
<!DOCTYPE html>
<html>
<head>
<title>Div Tag Example</title>
</head>
<body>
<div id="menu" align="middle" >
<a href="/[Link]">HOME</a> |
<a href="/about/contact_us.htm">CONTACT</a> |
<a href="/about/[Link]">ABOUT</a>
</div>
<div id="content" align="left" bgcolor="white">
<h5>Content Articles</h5>
<p>Actual content goes here.....</p>
</div>
</body>
</html>
This will produce the following result:

HOME | CONTACT | ABOUT


CONTENT ARTICLES

Actual content goes here.....

The <span> element, on the other hand, can be used to group inline elements only.
So, if you have a part of a sentence or paragraph which you want to group together,
you could use the <span> element as follows
Page 9 of 49
Example
<!DOCTYPE html>
<html>
<head>
<title>Span Tag Example</title>
</head>
<body>
<p>This is the example of <span style="color:green">span tag</span> and the
<span style="color:red">div tag</span> alongwith CSS</p>
</body>
</html>
This will produce the following result:

This is the example of span tag and the div tag along with CSS
These tags are commonly used with CSS to allow you to attach a style to a section
of a page

Emphasized Text
Anything that appears within <em>...</em> element is displayed as
emphasized text.
Example
<!DOCTYPE html>
<html>
<head>
<title>Emphasized Text Example</title>
</head>
<body>
<p>The following word uses a <em>emphasized</em> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses an emphasized typeface.

Marked Text
Anything that appears with-in <mark>...</mark> element, is displayed as
marked with yellow ink.
Example
<!DOCTYPE html>
<html>
<head>
<title>Marked Text Example</title>
</head>
Page 10 of 49
<body>
<p>The following word has been <mark>marked</mark> with yellow</p>
</body>
</html>

This will produce the following result:


The following word has been marked with yellow.

Strong Text
Anything that appears within <strong>...</strong> element is displayed as
important text.
Example
<!DOCTYPE html>
<html>
<head>
<title>Strong Text Example</title>
</head>
<body>
<p>The following word uses a <strong>strong</strong> typeface.</p>
</body>
</html>

This will produce the following result:


The following word uses a strong typeface.

Text Abbreviation
You can abbreviate a text by putting it inside opening <abbr> and closing
</abbr> tags. If present, the title attribute must contain this full description and
nothing else.
Example
<!DOCTYPE html>
<html>
<head>
<title>Text Abbreviation</title>
</head>
<body>
<p>My best friend's name is <abbr title="Abhishek">Abhy</abbr>.</p>
</body>
</html>

This will produce the following result:


My best friend's name is Abhy.

Acronym Element
Page 11 of 49
The <acronym> element allows you to indicate that the text between <acronym>
and </acronym> tags is an acronym.
At present, the major browsers do not change the appearance of the content of the
<acronym> element.
Example
<!DOCTYPE html>
<html>
<head>
<title>Acronym Example</title>
</head>
<body>
<p>This chapter covers marking up text in <acronym>XHTML</acronym>.</p>
</body>
</html>

This will produce the following result:


This chapter covers marking up text in XHTML.

Address Text
The <address>...</address> element is used to contain any address.
Example
<!DOCTYPE html>
<html>
<head>
<title>Address Example</title>
</head>
<body>
<address>388A, Road No 22, Jubilee Hills - Hyderabad</address>
</body>
</html>

This will produce the following result:


388A, Road No 22, Jubilee Hills – Hyderabad

Paragraphs
The <p> tag offers a way to structure your text into different paragraphs. Each
paragraph of text should go in between an opening <p> and a closing </p> tag as
shown below in the example:

Example
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
Page 12 of 49
</head>
<body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
</body>
</html>

This will produce the following result:


Here is a first paragraph of text.
Here is a second paragraph of text.
Here is a third paragraph of text

Align attribute: The <p> tag specifically supports the alignment attribute and allows
us to align our paragraphs in left, right, or center alignment.
Syntax:
<p align="value">
Example: This example explains the align attribute to align the content in the <p>
tag.
<!DOCTYPE html>
<html>

<body>
<p align="center">Welcome Geeks</p>
<p align="left">A Computer Science portal for geeks.</p>
<p align="right">It contains well written, well thought articles.</p>
</body>
</html>

<pre> tag:
We have seen how the paragraph tag ignores all the changes of lines and extra
spaces within a paragraph, but there is a way to preserve this by the use of
the <pre> tag. It also contains an opening and a closing tag. It displays a text within
a fixed height and width and preserves the extra lines and spaces we use.
Syntax:
<pre> Content </pre>
Example: This example explains the use of the <pre> tag in the <p> tag.
<!DOCTYPE html>
<html>
Page 13 of 49
<body>
<pre>
This paragraph has multiple
lines. But it is displayed
as it is unlike the paragraph
tag.
</pre>
<pre>
This paragraph has multiple
spaces. But it is displayed
as it is unlike the paragraph
tag.
</pre>
</body>
</html>
OUTPUT

Line Break Tag


Whenever you use the <br /> element, anything following it starts from the next line.
This tag is an example of an empty element, where you do not need opening and
closing tags, as there is nothing to go in between them.
The <br /> tag has a space between the characters br and the forward slash. If you
omit this space, older browsers will have trouble rendering the line break, while if
you miss the forward slash character and just use <br> it is not valid in XHTML.

Example
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
Page 14 of 49
<p>Hello<br />
You delivered your assignment on time.<br />
Thanks<br />
Mahnaz</p>
</body>
</html>

This will produce the following result:


Hello You delivered your assignment on time. Thanks Mahnaz

Heading
Any document starts with a heading. You can use different sizes for your headings.
HTML also has six levels of headings, which use the elements <h1>, <h2>, <h3>,
<h4>, <h5>, and <h6>. While displaying any heading, browser adds one line before
and one line after that heading.

Example
<!DOCTYPE html>
<html>
<head>
<title>Heading Example</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
OUTPUT
This is heading 1
This is heading 2
This is heading 3
This is heading 4
This is heading 5
This is heading 6
HORIZONTAL RULE
The <hr> tag in HTML stands for horizontal rule and is used to insert a horizontal
rule or a thematic break in an HTML page to divide or separate document sections.
The <hr> tag is an empty tag, and it does not require an end tag.

Page 15 of 49
Tag Attributes: The table given below describe the <hr> tag attributes. These
attributes are not supported in HTML5:

Attribute Value Description

Used to specify the alignment of the horizontal


align left center right rule.

noshadenoshade Used to specify the bar without shading effect.

size pixels Used to specify the height of the horizontal rule.

width pixels Used to specify the width of the horizontal rule.

Syntax :

<hr> ...
Below programs illustrate the <hr> tag in HTML:
Example
<!DOCTYPE html>
<html>
<body>
<p>There is a horizontal rule below this paragraph.</p>
<!--HTML hr tag is used here-->
<hr>
<p>This is a horizontal rule above this paragraph.</p>
</body>
</html>
MARQUEE Tag
The HTML <marquee> tag is used for scrolling piece of text or image displayed either
horizontally across or vertically down your web site page depending on the settings.
Example
<!DOCTYPE html>
<html>

<head>
<title>HTML marquee Tag</title>
</head>

<body>
<marquee>This is basic example of marquee</marquee>
<marquee direction = "up">The direction of text will be from bottom to
top.</marquee>
Page 16 of 49
</body>

</html>

LIST
Tag Description

<ul> Defines an unordered list

<ol> Defines an ordered list

<li> Defines a list item

<dl> Defines a description list

<dt> Defines a term in a description list

<dd> Describes the term in a description list


HTML offers web authors three ways for specifying lists of information. All lists must
contain one or more list elements. Lists may contain −
• <ul> − An unordered list. This will list items using plain bullets.
• <ol> − An ordered list. This will use different schemes of numbers to list your
items.
• <dl> − A definition list. This arranges your items in the same way as they are
arranged in a dictionary.
HTML Unordered Lists
An unordered list is a collection of related items that have no special order or
sequence. This list is created by using HTML <ul> tag. Each item in the list is marked
with a bullet.
Example
<!DOCTYPE html>
<html>

<head>
<title>HTML Unordered List</title>
</head>
Page 17 of 49
<body>
<ul>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>

</html>

This will produce the following result −


The type Attribute
You can use type attribute for <ul> tag to specify the type of bullet you like. By
default, it is a disc. Following are the possible options −
<ul type = "square">
<ul type = "disc">
<ul type = "circle">
Example
Following is an example where we used <ul type = "square">
<!DOCTYPE html>
<html>

<head>
<title>HTML Unordered List</title>
</head>

<body>
<ul type = "square">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
Page 18 of 49
</ul>
</body>

</html>

This will produce the following result −


Example
Following is an example where we used <ul type = "disc"> −

<!DOCTYPE html>
<html>

<head>
<title>HTML Unordered List</title>
</head>

<body>
<ul type = "disc">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>

</html>
This will produce the following result −
Example
Following is an example where we used <ul type = "circle"> −

<!DOCTYPE html>
<html>

<head>
<title>HTML Unordered List</title>
</head>

<body>
<ul type = "circle">
<li>Beetroot</li>
Page 19 of 49
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>

</html>
This will produce the following result −
HTML Ordered Lists
If you are required to put your items in a numbered list instead of bulleted, then HTML
ordered list will be used. This list is created by using <ol> tag. The numbering starts
at one and is incremented by one for each successive ordered list element tagged
with <li>.
Example
<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>
This will produce the following result −
The type Attribute
You can use type attribute for <ol> tag to specify the type of numbering you like. By
default, it is a number. Following are the possible options −
<ol type = "1"> - Default-Case Numerals.
<ol type = "I"> - Upper-Case Numerals.
<ol type = "i"> - Lower-Case Numerals.
Page 20 of 49
<ol type = "A"> - Upper-Case Letters.
<ol type = "a"> - Lower-Case Letters.
Example
Following is an example where we used <ol type = "1">
<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol type = "1">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>
Example
Following is an example where we used <ol type = "I">

<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol type = "I">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
Page 21 of 49
<li>Radish</li>
</ol>
</body>

</html>

This will produce the following result −


Example
Following is an example where we used <ol type = "i">
<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol type = "i">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>
This will produce the following result −
Example
Following is an example where we used <ol type = "A" >
<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol type = "A">
Page 22 of 49
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>
Example
Following is an example where we used <ol type = "a">
<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol type = "a">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>
The start Attribute
You can use start attribute for <ol> tag to specify the starting point of numbering you
need. Following are the possible options −
<ol type = "1" start = "4"> - Numerals starts with 4.
<ol type = "I" start = "4"> - Numerals starts with IV.
<ol type = "i" start = "4"> - Numerals starts with iv.
<ol type = "a" start = "4"> - Letters starts with d.
<ol type = "A" start = "4"> - Letters starts with D.

Page 23 of 49
Example
Following is an example where we used <ol type = "i" start = "4" >
<!DOCTYPE html>
<html>

<head>
<title>HTML Ordered List</title>
</head>

<body>
<ol type = "i" start = "4">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>
This will produce the following result −
HTML Definition Lists
HTML and XHTML supports a list style which is called definition lists where entries
are listed like in a dictionary or encyclopedia. The definition list is the ideal way to
present a glossary, list of terms, or other name/value list.
Definition List makes use of following three tags.

• <dl> − Defines the start of the list


• <dt> − A term
• <dd> − Term definition
• </dl> − Defines the end of the list
Example
<!DOCTYPE html>
<html>

Page 24 of 49
<head>
<title>HTML Definition List</title>
</head>

<body>
<dl>
<dt><b>HTML</b></dt>
<dd>This stands for Hyper Text Markup Language</dd>
<dt><b>HTTP</b></dt>
<dd>This stands for Hyper Text Transfer Protocol</dd>
</dl>
</body>

</html>

This will produce the following result –


HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol

FONT TAG
The <font> tag in HTML plays an important role in the web page to create an
attractive and readable web page. The font tag is used to change the color, size, and
style of a text. The base font tag is used to set all the text to the same size, color
and face.
Syntax:
<font attribute = "value"> Content </font>
Example: In this example, we have used the <font> tag with a font size as 5.

<!DOCTYPE html>
<html>
<body>
<h2>GeeksforGeeks</h2>

<!--Normal paragraph tag-->


<p>Hello Geeks!.</p>
<!--font tag-->
<font size="5"> Welcome to GeeksforGeeks </font>
</body>
</html>
Page 25 of 49
OUTPUT

The font tag has basically three attributes which are given below:
• Font Size attribute
• Face/Type attribute
• Color attribute
Note: Font tag is not supported in HTML5.
We will discuss all these attributes & understand them through the examples.
font Size: This attribute is used to adjust the size of the text in the HTML document
using a font tag with the size attribute. The range of size of the font in HTML is from
1 to 7 and the default size is 3.

Syntax:
<font size="number">
Example: This example uses the <font> tag where different font sizes are specified.
<!DOCTYPE html>
<html>

<body>
<!--HTML font size tag starts here-->
<font size="1">GeeksforGeeks!</font><br />
<font size="2">GeeksforGeeks!</font><br />
<font size="3">GeeksforGeeks!</font><br />
<font size="4">GeeksforGeeks!</font><br />
<font size="5">GeeksforGeeks!</font><br />
<font size="6">GeeksforGeeks!</font><br />
<font size="7">GeeksforGeeks!</font>
<!--HTML font size tag ends here-->
</body>

</html>

Page 26 of 49
OUTPUT

Font Type: Font type can be set by using face attribute with font tag in HTML
document. But the fonts used by the user need to be installed in the system first.
Syntax:
<font face="font_family">
Example: This example describes the <font> tag with different font type & font size.
<!DOCTYPE html>
<html>

<body>
<!--HTML font face tag starts here-->
<font face="Times New Roman" size="6">
GeeksforGeeks!!
</font> <br />
<font face="Verdana" size="6">
GeeksforGeeks!!
</font><br />
<font face="Comic sans MS" size=" 6">
GeeksforGeeks!!
</font><br />
<font face="WildWest" size="6">
GeeksforGeeks!!
</font><br />
<font face="Bedrock" size="6">
GeeksforGeeks!!
</font><br />
<!--HTML font face tag ends here-->
</body>

</html>

Page 27 of 49
Font Color: Font color is used to set the text color using a font tag with the color
attribute in an HTML document. Color can be specified either with its name or with
its hex code.
Syntax:
<font color="color_name|hex_number|rgb_number">

Example: This example describes the <font> tag with different font colors.
<!DOCTYPE html>
<html>

<body>

<!--HTML font color tag starts here-->


<font color="#009900">GeeksforGeeks</font><br />
<font color="green">GeeksforGeeks</font>
<!--HTML font color tag ends here-->
</body>

</html>

OUTPUT

LINK
It is a connection from one web resource to another. A link has two ends, An
anchor and direction. The link starts at the “source” anchor and points to the
“destination” anchor, which may be any Web resource such as an image, a video
clip, a sound bite, a program, an HTML document or an element within an HTML
document. You will find many websites or social media platforms ( Like YouTube,
Instagram ) which link an image to a URL or a text to a URL etc.

Page 28 of 49
This basically means that by using the ‘a’ tag, you can link 1 element of the code to
another element that may/may not be in your code.
HTML Link Syntax
Links are specified in HTML using the “a” tag.

href : The href attribute is used to specify the destination address of the link used.
"href" stands for Hypertext reference.
Text link : The text link is the visible part of the link. It is what the viewer clicks on.

EXAMPLE
<!DOCTYPE html>
<html>
<h3>Example Of Adding a link</h3>
<body>
<p>Click on the following link</p>
<a href = "[Link]
</body>
</html>

OUTPUT

Internal Links
An internal link is a type of hyperlink whose target or destination is a resource,
such as an image or document, on the same website or domain.
EXAMPLE
<!DOCTYPE html>
<html>
<h3>Internal Link And External Link Example</h3>
<body>

//internal link

<p><a href="html_contribute.asp/">GeeksforGeeks Contribute


</a> It is a link to the contribute page on GeeksforGeeks' website.</p>

//external link
Page 29 of 49
<p><a href="[Link]
</a> It is a link to the GeeksforGeeks website on the World Wide Web.</p>
</body>
</html>

Changing Link Colours in HTML


Different types of links appear in different formats such as:

1. An unvisited link appears underlined and blue in colour by default.


2. A visited link appears underlined and purple in colour by default.
3. An active link appears underlined and red in colour by default.
The appearances of links can be changed by using CSS.

<!DOCTYPE html>
<html>
<head>
<style>
a:link {
color: red;
background-color: transparent;
}
a:visited {
color: green;
background-color: transparent;
}
a:hover {
color: blue;
background-color: transparent;
}
a:active {
color: yellow;
background-color: transparent;
}
Page 30 of 49
</style>
</head>
<body>

<p>Changing the default colors of links</p>

<p>Visited Link</p>

<a href="[Link]

<p>Link</p>

<a href="[Link]

<p>hovering effect</p>

<a href="[Link]

</body>
</html>
The Target Attribute in Links
The target attribute is used to specify the location where the linked document is
opened. The various options that can be used in the target attribute are listed
below in the table:

<!DOCTYPE html>
<html>
<body>
<h3>Various options available in the Target Attribute</h3>
<p>If you set the target attribute to "_blank",
the link will open in a new browser window or tab.</p>
<a href="[Link] target="_blank">GeeksforGeeks</a>
<p>If you set the target attribute to "_self",
the link will open in the same window or tab.</p>
<a href="[Link] target="_self">GeeksforGeeks</a>
<p>If you set the target attribute to "_top",
Page 31 of 49
the link will open in the full body of the window.</p>
<a href="[Link] target="_top">GeeksforGeeks</a>
<p>If you set the target attribute to "_parent",
the link will open in the parent frame.</p>
<a href="[Link] target="_parent">GeeksforGeeks</a>
</body>
</html>

Using Image as a Link in HTML

An image can be used to create a link to a specified URL. When the viewer clicks
on the link, it redirects them to another page.
The code is <a href=”url”>
<img src=”file address (on device or on web)” alt=”_”
style=”width:__ ; height:__ ; border:__”>
</a>
Note: img src stands for image source ( i.e URL or file address )

EXAMPLE

<!DOCTYPE html>
<html>
Page 32 of 49
<body>
<h3>Using Image as a link</h3>
<p>Click on the image to visit GeeksforGeeks homepage.</p>
<a href="[Link]
<img src="gfg_200X200.jpeg" alt="GeeksforGeeks"
style="width:80px;height:80px;border:0">
</a>
</body>
</html>

Creating a Bookmark Link for a Webpage


A bookmark is a link that can be used to jump to specified portion of a
[Link] are very useful if a webpage is quite long.
Steps to create a bookmark are:
1. Using the id attribute,create a bookmark.

2. Add the specified portion of the webpage to the bookmark.

EXAMPLE

<!DOCTYPE html>
<html>
<body>
<p><a href="#T11">Jump to Topic 11</a></p>
<p><a href="#T17">Jump to Topic 17</a></p>
<p><a href="#T20">Jump to Topic 20</a></p>
<h2>Topic 1</h2>
<p>paragraph 1
Page 33 of 49
.....</p>
<h2>Topic 2</h2>
<p>paragraph 1
.....</p>
<h2>Topic 3</h2>
<p>paragraph 1
.....</p>
<h2>Topic 4</h2>
<p>paragraph 1
.....</p>
<h2>Topic 5</h2>
<p>paragraph 1
.....</p>

<h2>Topic 6</h2>
<p>paragraph 1
.....</p>
<h2>Topic 7</h2>
<p>paragraph 1
.....</p>
<h2>Topic 8</h2>
<p>paragraph 1
.....</p>
<h2>Topic 9</h2>
<p>paragraph 1
.....</p>
<h2>Topic 10</h2>
<p>paragraph 1
.....</p>
<h2 id="T11">Topic 11</h2>
<p>paragraph 1
.....</p>
<h2>Topic 12</h2>
<p>paragraph 1
.....</p>
<h2>Topic 13</h2>
<p>paragraph 1
Page 34 of 49
.....</p>

<h2>Topic 14</h2>

<p>paragraph 1
.....</p>
<h2>Topic 15</h2>

<p>paragraph 1
.....</p>

<h2>Topic 16</h2>

<p>paragraph 1
.....</p>

<h2 id="T17">Topic 17</h2>


<p>paragraph 1
.....</p>

<h2>Topic 18</h2>
<p>paragraph 1
.....</p>
<h2>Topic 19</h2>
<p>paragraph 1
.....</p>
<h2 id="T20">Topic 20</h2>
<p>paragraph 1
.....</p>
</body>
</html>
Creating a download link in HTML
A text link of a pdf, doc or zip file can be created to make it downloadable.

<!DOCTYPE html>
<html>

Page 35 of 49
<h3>Creating a download link</h3>

<body>
<a href = "GeeksforGeeks | A computer science portal for [Link]">Download
PDF File</a>
</body>
</html>
TABLE
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
<!DOCTYPE html>
<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>

Row 1, Column 1 Row 1, Column 2


Row 2, Column 1 Row 2, Column 2
Page 36 of 49
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.
Example
<!DOCTYPE html>
<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>

Name Salary
Ramesh Raman 5000
Shabbir Hussein 7000

Page 37 of 49
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
<!DOCTYPE html>
<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>
AD

Name Salary

Ramesh Raman 5000

Shabbir Hussein 7000

Page 38 of 49
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
<!DOCTYPE html>
<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>
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

Page 39 of 49
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.
Example
<!DOCTYPE html>
<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>

Page 40 of 49
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

Here is an example of using background attribute. Here we will use an image


available in /images directory.
<!DOCTYPE html>
<html>

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

<body>
<table border = "1" bordercolor = "green" background = "/images/[Link]">
<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>
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
Page 41 of 49
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
<!DOCTYPE html>
<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>
Row 1, Column 1 Row 1, Column 2
Row 2, Column 1 Row 2, Column 2

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
<!DOCTYPE html>
<html>

<head>
<title>HTML Table Caption</title>
Page 42 of 49
</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>
This is the caption
row 1, column 1 row 1, column 2
row 2, column 1 row 2, column 2

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
<!DOCTYPE html>
<html>

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

<body>
Page 43 of 49
<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>

This is the head of the table


This is the foot of the table
Cell 1 Cell 2 Cell 3 Cell 4

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>.

Page 44 of 49
Example
Following is the example of using another table and other tags inside a table cell.
<!DOCTYPE html>
<html>

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

<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>

Page 45 of 49
Name Salary
Ramesh Raman 5000
Shabbir Hussein 7000

FRAMES
HTML Frames are used to divide the web browser window into multiple sections
where each section can be loaded separately. A frameset tag is the collection of
frames in the browser window.
Creating Frames: Instead of using body tag, use frameset tag in HTML to use
frames in web browser. But this Tag is deprecated in HTML 5. The frameset tag is
used to define how to divide the browser. Each frame is indicated by frame tag and
it basically defines which HTML document shall open into the frame. To define the
horizontal frames use row attribute of frame tag in HTML document and to define
the vertical frames use col attribute of frame tag in HTML document.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML Frames using row attribute</title>
</head>

<frameset rows = "20%, 60%, 20%">


<frame name = "top" src ="C:/Users/dharam/Desktop/[Link]" />
<frame name = "main" src ="C:/Users/dharam/Desktop/[Link]" /> <frame
name = "bottom" src ="C:/Users/dharam/Desktop/col_last.png" />
<noframes>
<body>The browser you are working doesnot support frames.</body>
</noframes>
</frameset>
</html>
Example: This example illustrates the col attribute of frameset tag.
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML Frames Using col Attribute</title>
</head>

Page 46 of 49
<frameset cols = "30%, 40%, 30%">
<frame name = "top" src ="C:/Users/dharam/Desktop/[Link]" />
<frame name = "main" src ="C:/Users/dharam/Desktop/[Link]" />
<frame name = "bottom" src ="C:/Users/dharam/Desktop/col_last.png" />
<noframes>
<body>The browser you are working does not support frames.</body>
</noframes>
</frameset>
</html>
Attributes of Frameset tag:
• cols: The cols attribute is used to create vertical frames in web browser.
This attribute is basically used to define the no of columns and its size
inside the frameset tag.
The size or width of the column is set in the frameset in the following
ways:
• Use absolute value in pixel
Example:
<frameset cols = "300, 400, 300">
• Use percentage value
Example:
<frameset cols = "30%, 40%, 30%">
• Use wild card values:
Example:
<frameset cols = "30%, *, 30%">
In the above example * will take the remaining percentage for
creating vertical frame.
• rows: The rows attribute is used to create horizontal frames in web
browser. This attribute is used to define no of rows and its size inside the
frameset tag.
The size of rows or height of each row use the following ways:
• Use absolute value in pixel
Example:
<frameset rows = "300, 400, 300">
• Use percentage value
Example:
<frameset rows = "30%, 40%, 30%">
• Use wild card values
Example:
<frameset rows = "30%, *, 30%">
Page 47 of 49
In the above example * will take the remaining percentage for
creating horizontal frame.
• border: This attribute of frameset tag defines the width of border of each
frames in pixels. Zero value is used for no border.
Example:
<frameset border="4" frameset>
• frameborder: This attribute of frameset tag is used to specify whether the
three-dimensional border should be displayed between the frames or not
for this use two values 0 and 1, where 0 defines for no border and value 1
signifies for yes there will be border.
• framespacing: This attribute of frameset tag is used to specify the
amount of spacing between the frames in a frameset. This can take any
integer value as an parameter which basically denotes the value in pixel.
Example:
• <framespacing="20">
• It means there will be 20 pixel spacing between the frames
Attributes of Frame Tag:
• name: This attribute is used to give names to the frame. It
differentiate one frame from another. It is also used to indicate
which frame a document should loaded into.
Example:
• <frame name = "top" src =
"C:/Users/dharam/Desktop/[Link]" />
• <frame name = "main" src =
"C:/Users/dharam/Desktop/[Link]" />
• <frame name = "bottom" src =
"C:/Users/dharam/Desktop/col_last.png" />
Here we use three frames with names as left center and right.
• src: This attribute in frame tag is basically used to define the
source file that should be loaded into the [Link] value of
src can be any url.
Example:
<frame name = "left" src = "/html/[Link]" />
In the above example name of frame is left and source file will
be loaded from “/html/[Link]” in frame.
• marginwidth: This attribute in frame tag is used to specify
width of the spaces in pixels between the border and contents
of left and right frame.
Example:
Page 48 of 49
• <frame marginwidth="20">
• marginheight: This attribute in frame tag is used to specify
height of the spaces in pixels between the border and contents
of top and bottom frame.
Example:
• <frame marginheight="20">
• scrollbar: To control the appearance of scroll bar in frame use
scrollbar attribute in frame tag. This is basically used to control
the appearance of scrollbar. The value of this attribute can be
yes, no, auto. Where the value no denotes there will be no
appearance of scroll bar.
Example:
• <frame scrollbar="no">
Advantages:
• It allows the user to view multiple documents within a single
Web page.
• It load pages from different servers in a single frameset.
• The older browsers that do not support frames can be
addressed using the tag.
Disadvantages: Due to some of its disadvantage it is rarely used in
web browser.
• Frames can make the production of website complicated.
• A user is unable to bookmark any of the Web pages viewed
within a frame.
• The browser’s back button might not work as the user hopes.
• The use of too many frames can put a high workload on the
server.
• Many old web browser doesn’t support frames.

Page 49 of 49
WEB DESIGN AND DEVELOPMENT
UNIT 2
IMAGES
Images can improve the design and the appearance of a web page.
HTML Images Syntax

The HTML <img> tag is used to embed an image in a web page.

Images are not technically inserted into a web page; images are linked to
web pages. The <img> tag creates a holding space for the referenced
image.

The <img> tag is empty, it contains attributes only, and does not have a
closing tag.

The <img> tag has two required attributes:

• src - Specifies the path to the image


• alt - Specifies an alternate text for the image

Syntax
<img src="url" alt="alternatetext">
The src Attribute

The required src attribute specifies the path (URL) to the image.

Note: When a web page loads, it is the browser, at that moment, that gets
the image from a web server and inserts it into the page. Therefore, make
sure that the image actually stays in the same spot in relation to the web
page, otherwise your visitors will get a broken link icon. The broken link
icon and the alt text are shown if the browser cannot find the image.

Example
<img src="img_chania.jpg" alt="Flowers in Chania">

Page 1 of 28
The alt Attribute

The required alt attribute provides an alternate text for an image, if the user
for some reason cannot view it (because of slow connection, an error in the
src attribute, or if the user uses a screen reader).

The value of the alt attribute should describe the image:

Example
<img src="img_chania.jpg" alt="Flowers in Chania">
If a browser cannot find an image, it will display the value of the alt attribute
Image Size - Width and Height

You can use the style attribute to specify the width and height of an image.

Example
<img src="img_girl.jpg" alt="Girl in a
jacket" style="width:500px;height:600px;">

Alternatively, you can use the width and height attributes:

Example
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">
The width and height attributes always define the width and height of the
image in pixels.
Images in Another Folder

If you have your images in a sub-folder, you must include the folder name
in the src attribute:

Example
<img src="/images/[Link]" alt="HTML5
Icon" style="width:128px;height:128px;">
Images on Another Server/Website

Page 2 of 28
Some web sites point to an image on another server.

To point to an image on another server, you must specify an absolute (full)


URL in the src attribute:

Example
<img src="[Link] alt="
[Link]">
Animated Images

HTML allows animated GIFs:

Example
<img src="[Link]" alt="Computer
Man" style="width:48px;height:48px;">
Image as a Link

To use an image as a link, put the <img> tag inside the <a> tag:

Example
<a href="[Link]">
<img src="[Link]" alt="HTML tutorial" style="width:42px;height:42px;">
</a>
Image Floating

Use the CSS float property to let the image float to the right or to the left of
a text:

Example
<p><img src="[Link]" alt="Smiley
face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>

<p><img src="[Link]" alt="Smiley


face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.</p>

Page 3 of 28
Common Image Formats

Here are the most common image file types, which are supported in all
browsers (Chrome, Edge, Firefox, Safari, Opera):

Abbreviation File Format File Extension

APNG Animated Portable Network .apng


Graphics

GIF Graphics Interchange Format .gif

ICO Microsoft Icon .ico, .cur

JPEG Joint Photographic Expert Group .jpg, .jpeg, .jfif, .pjpeg,


image .pjp

PNG Portable Network Graphics .png

SVG Scalable Vector Graphics .svg

IMAGE MAP

With HTML image maps, you can create clickable areas on an image.

Page 4 of 28
The HTML <map> tag defines an image map. An image map is an image
with clickable areas. The areas are defined with one or more <area> tags.

How Does it Work?

The idea behind an image map is that you should be able to perform
different actions depending on where in the image you click.

To create an image map you need an image, and some HTML code that
describes the clickable areas.

The Image

The image is inserted using the <img> tag. The only difference from other
images is that you must add a usemap attribute:

<img src="[Link]" alt="Workplace" usemap="#workmap">

The usemap value starts with a hash tag # followed by the name of the
image map, and is used to create a relationship between the image and the
image map.

Create Image Map

Then, add a <map> element.

The <map> element is used to create an image map, and is linked to the
image by using the required name attribute:

<map name="workmap">

The name attribute must have the same value as


the <img>'s usemap attribute .

The Areas

Then, add the clickable areas.

A clickable area is defined using an <area> element.

Shape

Page 5 of 28
You must define the shape of the clickable area, and you can choose one
of these values:

• rect - defines a rectangular region


• circle - defines a circular region
• poly - defines a polygonal region
• default - defines the entire region

You must also define some coordinates to be able to place the clickable
area onto the image.

Shape="rect"

The coordinates for shape="rect" come in pairs, one for the x-axis and one
for the y-axis.

EXAMPLE

<!DOCTYPE html>
<html>
<body>

<h2>Image Maps</h2>
<p>Click on the computer to go to a new page and read more about the
topic:</p>

<img src="[Link]" alt="Workplace" usemap="#workmap"


width="400" height="379">

<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer"
href="[Link]">
</map>

</body>
</html>

Page 6 of 28
Shape="circle"

To add a circle area, first locate the coordinates of the center of the circle:

337,300

Then specify the radius of the circle:

44 pixels

EXAMPLE

<!DOCTYPE html>
<html>
<body>

<h2>Image Maps</h2>
<p>Click on the cup of coffee to go to a new page and read more about the
topic:</p>

<img src="[Link]" alt="Workplace" usemap="#workmap"


width="400" height="379">

<map name="workmap">
<area shape="circle" coords="337,300,44" alt="Cup of coffee"
href="[Link]">
</map>

</body>
</html>
Shape="poly"

The shape="poly" contains several coordinate points, which creates a


shape formed with straight lines (a polygon).

This can be used to create any shape.

Page 7 of 28
EXAMPLE

<!DOCTYPE html>
<html>
<body>

<h2>Image Maps</h2>
<p>Click on the croissant to go to a new page and read more about the
topic:</p>

<img src="[Link]" alt="French Food" usemap="#foodmap"


width="450" height="675">

<map name="foodmap">
<area shape="poly"
coords="140,121,181,116,204,160,204,222,191,270,140,329,85,355,58,35
2,37,322,40,259,103,161,128,147" alt="Croissant" href="[Link]">
</map>

ADDING MULTIMEDIA

Sometimes you need to add music or video into your web page. The easiest
way to add video or sound to your web site is to include the special HTML
tag called <embed>. This tag causes the browser itself to include controls
for the multimedia automatically provided browser supports <embed> tag
and given media type.
You can also include a <noembed> tag for the browsers which don't
recognize the <embed> tag. You could, for example, use <embed> to display
a movie of your choice, and <noembed> to display a single JPG image if
browser does not support <embed> tag.
Example
Here is a simple example to play an embedded midi file

Page 8 of 28
<!DOCTYPE html>
<html>

<head>
<title>HTML embed Tag</title>
</head>

<body>
<embed src = "/html/[Link]" width = "100%" height = "60" >
<noembed><img src = "[Link]" alt = "Alternative Media"
></noembed>
</embed>
</body>

</html>

The <embed> Tag Attributes

Following is the list of important attributes which can be used with <embed>
tag.

[Link] Attribute & Description

1 align
Determines how to align the object. It can be set to either center, left
or right.

2 autostart
This boolean attribute indicates if the media should start
automatically. You can set it either true or false.

Page 9 of 28
3 loop
Specifies if the sound should be played continuously (set loop to
true), a certain number of times (a positive value) or not at all (false)

4 playcount
Specifies the number of times to play the sound. This is alternate
option for loop if you are usiong IE.

5 hidden
Specifies if the multimedia object should be shown on the page. A
false value means no and true values means yes.

6 width
Width of the object in pixels

7 height
Height of the object in pixels

8 name
A name used to reference the object.

9 src
URL of the object to be embedded.

10 volume
Controls volume of the sound. Can be from 0 (off) to 100 (full
volume).

Supported Video Types

Page 10 of 28
You can use various media types like Flash movies (.swf), AVI's (.avi), and
MOV's (.mov) file types inside embed tag.
• .swf files − are the file types created by Macromedia's Flash
program.
• .wmv files − are Microsoft's Window's Media Video file types.
• .mov files − are Apple's Quick Time Movie format.
• .mpeg files − are movie files created by the Moving Pictures
Expert Group.

<!DOCTYPE html>
<html>

<head>
<title>HTML embed Tag</title>
</head>

<body>
<embed src = "/html/[Link]" width = "200" height = "200" >
<noembed><img src = "[Link]" alt = "Alternative Media"
></noembed>
</embed>
</body>

</html>

Background Audio

You can use HTML <bgsound> tag to play a soundtrack in the background
of your webpage. This tag is supported by Internet Explorer only and most
of the other browsers ignore this tag. It downloads and plays an audio file
when the host document is first downloaded by the user and displayed. The
background sound file also will replay whenever the user refreshes the
browser.
Note − The bgsound tag is deprecated and it is supposed to be removed in
a future version of HTML. So they should not be used rather, it's suggested

Page 11 of 28
to use HTML5 tag audio for adding sound. But still for learning purpose, this
chapter will explain bgsound tag in detail.
This tag is having only two attributes loop and src. Both these attributes have
same meaning as explained above.
Here is a simple example to play a small midi file −
<!DOCTYPE html>
<html>

<head>
<title>HTML embed Tag</title>
</head>

<body>
<bgsound src = "/html/[Link]">
<noembed><img src = "[Link]" ></noembed>
</bgsound>
</body>

</html>
This will produce the blank screen. This tag does not display any component
and remains hidden.
Internet Explorer can also handle only three different sound format files −
wav, the native format for PCs; au, the native format for most Unix
workstations; and MIDI, a universal music-encoding scheme.

HTML Object tag

HTML 4 introduces the <object> element, which offers an all-purpose


solution to generic object inclusion. The <object> element allows HTML
authors to specify everything required by an object for its presentation by a
user agent.
Here are a few examples −
Example - 1
Page 12 of 28
You can embed an HTML document in an HTML document itself as follows

<object data = "data/[Link]" type = "text/html" width = "300" height =
"200">
alt : <a href = "data/[Link]">[Link]</a>
</object>
Here alt attribute will come into picture if browser does not
support object tag.
Example - 2
You can embed a PDF document in an HTML document as follows −
<object data = "data/[Link]" type = "application/pdf" width = "300" height =
"200">
alt : <a href = "data/[Link]">[Link]</a>
</object>
Example - 3
You can specify some parameters related to the document with
the <param> tag. Here is an example to embed a wav file −
<object data = "data/[Link]" type = "audio/x-wav" width = "200" height =
"20">
<param name = "src" value = "data/[Link]">
<param name = "autoplay" value = "false">
<param name = "autoStart" value = "0">
alt : <a href = "data/[Link]">[Link]</a>
</object>
Example - 4
You can add a flash document as follows −
<object classid = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id =
"penguin"
codebase = "someplace/[Link]" width = "200" height = "300">

<param name = "movie" value = "flash/[Link]" />


<param name = "quality" value = "high" />
<img src = "[Link]" width = "200" height = "300" alt = "Penguin" />
</object>
Example - 5
You can add a java applet into HTML document as follows −
Page 13 of 28
<object classid = "clsid:8ad9c840-044e-11d1-b3e9-00805f499d93"
width = "200" height = "200">
<param name = "code" value = "[Link]">
</object>
The classid attribute identifies which version of Java Plug-in to use. You can
use the optional codebase attribute to specify if and how to download the
JRE.

FORMS

HTML Forms are required, when you want to collect some data from the site
visitor. For example, during user registration you would like to collect
information such as name, email address, credit card, etc.
A form will take input from the site visitor and then will post it to a back-end
application such as CGI, ASP Script or PHP script etc. The back-end
application will perform required processing on the passed data based on
defined business logic inside the application.
There are various form elements available like text fields, textarea fields,
drop-down menus, radio buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following
syntax −
<form action = "Script URL" method = "GET|POST">
form elements like input, textarea etc.
</form>

Form Attributes

Apart from common attributes, following is a list of the most frequently used
form attributes −

[Link] Attribute & Description

1 action
Backend script ready to process your passed data.

2 method

Page 14 of 28
Method to be used to upload data. The most frequently used are
GET and POST methods.

3 target
Specify the target window or frame where the result of the script will
be displayed. It takes values like _blank, _self, _parent etc.

4 enctype
You can use the enctype attribute to specify how the browser
encodes the data before it sends it to the server. Possible values are

application/x-www-form-urlencoded − This is the standard
method most forms use in simple scenarios.
mutlipart/form-data − This is used when you want to upload binary
data in the form of files like image, word file etc.

AD

HTML Form Controls

There are different types of form controls that you can use to collect data
using HTML form −
• Text Input Controls
• Checkboxes Controls
• Radio Box Controls
• Select Box Controls
• File Select boxes
• Hidden Controls
• Clickable Buttons
• Submit and Reset Button

Text Input Controls

There are three types of text input used on forms −

Page 15 of 28
• Single-line text input controls − This control is used for items
that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.
• Password input controls − This is also a single-line text input
but it masks the character as soon as a user enters it. They are
also created using HTMl <input> tag.
• Multi-line text input controls − This is used when the user is
required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.

Single-line text input controls

This control is used for items that require only one line of user input, such as
search boxes or names. They are created using HTML <input> tag.
Example
Here is a basic example of a single-line text input used to take first name and
last name −
<!DOCTYPE html>
<html>

<head>
<title>Text Input Control</title>
</head>

<body>
<form >
First name: <input type = "text" name = "first_name" />
<br>
Last name: <input type = "text" name = "last_name" />
</form>
</body>

</html>
This will produce the following result –

Firstname:
Last name:

Page 16 of 28
Attributes

Following is the list of attributes for <input> tag for creating text field.

[Link] Attribute & Description

1 type
Indicates the type of input control and for text input control it will be
set to text.

2 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

3 value
This can be used to provide an initial value inside the control.

4 size
Allows to specify the width of the text-input control in terms of
characters.

5 maxlength
Allows to specify the maximum number of characters a user can
enter into the text box.

Password input controls

This is also a single-line text input but it masks the character as soon as a
user enters it. They are also created using HTML <input>tag but type
attribute is set to password.
Example
Here is a basic example of a single-line password input used to take user
password −

Page 17 of 28
<!DOCTYPE html>
<html>

<head>
<title>Password Input Control</title>
</head>

<body>
<form >
User ID : <input type = "text" name = "user_id" />
<br>
Password: <input type = "password" name = "password" />
</form>
</body>

</html>
This will produce the following result –

User ID :
Password:

Attributes

Following is the list of attributes for <input> tag for creating password field.

[Link] Attribute & Description

1 type
Indicates the type of input control and for password input control it
will be set to password.

2 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

Page 18 of 28
3 value
This can be used to provide an initial value inside the control.

4 size
Allows to specify the width of the text-input control in terms of
characters.

5 maxlength
Allows to specify the maximum number of characters a user can
enter into the text box.

Multiple-Line Text Input Controls

This is used when the user is required to give details that may be longer than
a single sentence. Multi-line input controls are created using HTML
<textarea> tag.
Example
Here is a basic example of a multi-line text input used to take item description
<!DOCTYPE html>
<html>

<head>
<title>Multiple-Line Input Control</title>
</head>

<body>
<form>
Description : <br />
<textarea rows = "5" cols = "50" name = "description">
Enter description here...
</textarea>
</form>
</body>

Page 19 of 28
</html>
This will produce the following result –
Description:

Attributes

Following is the list of attributes for <textarea> tag.

[Link] Attribute & Description

1 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

2 rows
Indicates the number of rows of text area box.

3 cols
Indicates the number of columns of text area box

Checkbox Control

Checkboxes are used when more than one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set
to checkbox..
Example
Here is an example HTML code for a form with two checkboxes –

Page 20 of 28
<!DOCTYPE html>
<html>

<head>
<title>Checkbox Control</title>
</head>

<body>
<form>
<input type = "checkbox" name = "maths" value = "on"> Maths
<input type = "checkbox" name = "physics" value = "on"> Physics
</form>
</body>

</html>
This will produce the following result –

Maths Physics

Attributes

Following is the list of attributes for <checkbox> tag.

[Link] Attribute & Description

1 type
Indicates the type of input control and for checkbox input control it
will be set to checkbox.

2 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

3 value
The value that will be used if the checkbox is selected.

Page 21 of 28
4 checked
Set to checked if you want to select it by default.

Radio Button Control

Radio buttons are used when out of many options, just one option is required
to be selected. They are also created using HTML <input> tag but type
attribute is set to radio.
Example
Here is example HTML code for a form with two radio buttons −
<!DOCTYPE html>
<html>

<head>
<title>Radio Box Control</title>
</head>

<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body>

</html>
This will produce the following result –

Maths Physics

Page 22 of 28
Attributes

Following is the list of attributes for radio button.

[Link] Attribute & Description

1 type
Indicates the type of input control and for checkbox input control it
will be set to radio.

2 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

3 value
The value that will be used if the radio box is selected.

4 checked
Set to checked if you want to select it by default.

Select Box Control

A select box, also called drop down box which provides option to list down
various options in the form of drop down list, from where a user can select
one or more options.
Example
Here is example HTML code for a form with one drop down box
<!DOCTYPE html>
<html>

<head>
<title>Select Box Control</title>
</head>

Page 23 of 28
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>

</html>
This will produce the following result –
Maths

Attributes

Following is the list of important attributes of <select> tag −

[Link] Attribute & Description

1 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

2 size
This can be used to present a scrolling list box.

3 multiple
If set to "multiple" then allows a user to select multiple items from the
menu.

Page 24 of 28
Following is the list of important attributes of <option> tag −

[Link] Attribute & Description

1 value
The value that will be used if an option in the select box box is
selected.

2 selected
Specifies that this option should be the initially selected value when
the page loads.

3 label
An alternative way of labeling options

File Upload Box

If you want to allow a user to upload a file to your web site, you will need to
use a file upload box, also known as a file select box. This is also created
using the <input> element but type attribute is set to file.
Example
Here is example HTML code for a form with one file upload box −
<html>

<head>
<title>File Upload Box</title>
</head>

<body>
<form>
<input type = "file" name = "fileupload" accept = "image/*" />
</form>
</body>

</html>

Page 25 of 28
Attributes

Following is the list of important attributes of file upload box −

[Link] Attribute & Description

1 name
Used to give a name to the control which is sent to the server to be
recognized and get the value.

2 accept
Specifies the types of files that the server accepts.

Button Controls

There are various ways in HTML to create clickable buttons. You can also
create a clickable button using <input>tag by setting its type attribute
to button. The type attribute can take the following values −

[Link] Type & Description

1 submit
This creates a button that automatically submits a form.

2 reset
This creates a button that automatically resets form controls to their
initial values.

3 button
This creates a button that is used to trigger a client-side script when
the user clicks that button.

4 image

Page 26 of 28
This creates a clickable button but we can use an image as
background of the button.

Example
Here is example HTML code for a form with three types of buttons −
<!DOCTYPE html>
<html>

<head>
<title>File Upload Box</title>
</head>

<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src =
"/html/images/[Link]" />
</form>
</body>

</html>

Hidden Form Controls

Hidden form controls are used to hide data inside the page which later on
can be pushed to the server. This control hides inside the code and does not
appear on the actual page. For example, following hidden form is being used
to keep current page number. When a user will click next page then the value
of hidden control will be sent to the web server and there it will decide which
page will be displayed next based on the passed current page.

Page 27 of 28
Example
Here is example HTML code to show the usage of hidden control −
<!DOCTYPE html>
<html>

<head>
<title>File Upload Box</title>
</head>

<body>
<form>
<p>This is page 10</p>
<input type = "hidden" name = "pagename" value = "10" />
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
</form>
</body>

</html>

Page 28 of 28
UNIT 3

STYLE SHEET

CSS stands for Cascading Style Sheets.

CSS saves a lot of work. It can control the layout of multiple web pages all at once.

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

Style sheet is a collection of formatting styles, which can be applied to a web page. The style sheet consists
of the following components:
• Style Rule
• Inline Styles
• Embedding style sheet
• Grouping style rules
• Selectors
• Cascading Style sheet
Style Rule
A style rule is a set of HTML tags specifying the formatting elements. Style rules can be applied to the
selected contents of a web page.
A style rule is made of three parts −

•Selector - A selector is an HTML tag at which a style will be applied. This could be any tag like
<h1> or <table> etc.
• Property - A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are
converted into CSS properties. They could be color, border etc.
• Value - Values assigned to properties. For example, the color property can have value either red or
#F1F1F1 etc
Syntax of a style rule
Selector {property : value}
Example
H1{color : blue}
Ways of incorporating style sheets in HTML document
➢ Including style information within HTML
➢ Embedding a style sheet
➢ Linking to an external style sheet
➢ Importing a style sheet
Including style information within HTML – Inline styles
Inline style sheet is the most basic style rule, which can be applied to individual elements in the web
page. Inline styles are implemented by using style attribute with the HTML tags.
Syntax
<HTML TAG STYLE = “PROPERTY: VALUE”>
Example
<html>
<body>

<h1 style="color:blue;">A Blue Heading</h1>

<h1 style="color:red;">A red Heading.</h1>

</body>
</html>

Embedding Style Sheet


Embedded style sheets refer to when you embed style sheet information into an HTML document using
the <style> element. We can do this by embedding the style sheet information within <style></style> tags
in the head of your document.

The CSS syntax for embedded style sheets is exactly the same as other CSS code.
For example, to use the following code, simply place it between the <head></head> tags of your HTML
document:

Syntax
<HTML>
<HEAD>
<STYLE>
Style rules
</STYLE>
<BODY>
………
………
</BODY>
</HTML>

Example
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Grouping Style Rules


The CSS grouping selector is used to select multiple elements and style them together. This reduces the
code and extra effort to declare common styles for each element. To group selectors, each selector is
separated by a space.
Syntax
The syntax for CSS grouping selector is as follows −
element, element {
/*declarations*/
}
Example
<html>
<head>
<style>
h1 ,h2 {color: blue;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<h2>This is a paragraph.</h2>

</body>
</html>
Linking to an external style sheet

An external style sheet is a separate file where you can declare all the styles that you want to use on
your website. You then link to the external style sheet from all your HTML pages.

This means you only need to set the styles for each element once. If you want to update the style of your
website, you only need to do it in one place.
1. Create the Style Sheet

Type CSS code into a plain text file, and save with a .css extension (for example, [Link]).

body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

Add the following code between the <head></head> tags of all HTML documents that you want to
reference the external style sheet. This code uses the HTML <link> element to link to the external style
sheet.

<link rel="stylesheet" href="[Link]">

So, by linking to it from all web pages, all of your HTML documents will use the styles from your external
style sheet resulting in a consistent look and feel.

<html>
<head>
<link rel="stylesheet" href="[Link]">

</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

So, by linking to it from all web pages, all of your HTML documents will use the styles from your external
style sheet resulting in a consistent look and feel.

If you want to change anything, you only need to update the external style sheet.

Importing a Style sheet


Importing the style sheet, automatically pulls the style sheet rules into the document for use. Once
imported , changes made to the style sheet will not be reflected in the web page into which it has been
imported.
Syntax
<HTML>
<HEAD>
<STYLE TYPE =”TEXT/CSS”>
</STLYE>
</HEAD>
<BODY>
……..
……..
</BODY>

Example
<html>
<head>
<style type="text/css">
@import url([Link]);
body {
background-color: honeydew;
}
</style>
</head>
<body>
<p>This is demo paragraph one. </p>
<p class="two">This is demo paragraph two.</p>
<p>This is demo paragraph three</p>
</body>
</html>

CSS document: [Link]


p { color: navy; font-style: italic; }
.two { color: darkgreen; font-size: 24px; }
Output

Selectors
Selectors define the elements to which a set of rules apply.
➢ Simple selector
➢ HTML selector
➢ Class selector
➢ ID selector
➢ Contextual selector
Simple selector
A simple selector describes an element irrespective of its position in the document structure.
Example
H1{color: blue}
HTML selector
These selectors use the names of the HTML elements without [Link] the HTML <P> tag becomes P.
Example
<html>
<head>
<style>
p{
border: 5px solid red;
}
</style>
</head>
<body>

<h2>The border Property</h2>

<p>This property is a shorthand property for border-width, border-style, and border-color.</p>


</body>
</html>
Class selector
The class selector gives authors the ability to apply styles to specific parts of a document and do not
necessarily to the whole document.
Syntax
<STYLE>
Class selector
.Class Name Class selector { Property : Value}
</STYLE>
<BODY>
<P Class = “Class Name”>
Class attribute
</BODY>
➢ Class name can be any valid string of character
➢ The class selector is preceded with a dot(.) called the flag character
➢ Class selector can be applied to any of the HTML elements by using the class attribute.
Example
<html>
<head>
<style>
[Link] {
border-style: solid;
border-color: red;
}

[Link] {
border-style: solid;
border-color: green;
}

[Link] {
border-style: dotted;
border-color: blue;
}
</style>
</head>
<body>
<h2>The border-color Property</h2>
<p>This property specifies the color of the four borders:</p>

<p class="one">A solid red border</p>


<p class="two">A solid green border</p>
<p class="three">A dotted blue border</p>

<p><b>Note:</b> The "border-color" property does not work if it is used alone. Use the "border-style"
property to set the borders first.</p>

</body>
</html>

ID selector

The id selector selects the id attribute of an HTML element to select a specific element.

An id is always unique within the page so it is chosen to select a single, unique element.

It is written with the hash character (#), followed by the id of the element.

Syntax

<STYLE>
ID selector name
#ID Selector name { Property : Value}
</STYLE>
<BODY>
<P ID = “IDSelectorName”>
ID attribute
</BODY>
➢ ID selector can be any valid string of character
➢ ID selector is preceded with a hash(#)
➢ ID selector can be applied to any of the HTML elements by using the ID attribute.
Example

<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello [Link]</p>
<p>This paragraph will not be affected.</p>
</body>
</html>
Contextual Selectors
Contextual selectors can be used to combine number of simple selectors separated by a space.
H1 I {Color : Red}
The conceptual selectors support inheritance as shown in the code below:
<HTML>
<BODY>
<P>…….
<B>…….</B>
</BODY>
</HTML>
In an HTML block,the outer tags are known as parent tags and the nested tags are known as child
tags. For example in the above code <P> is the parent and <B> is the child element,but whereas <BODY>
is parent element of the <P>tag.
Example
<HTML>
<HEAD>
<TITLE>contextual selectors</TITLE>
<STYLE>
Body {
Color : Magenta;
Background : white;
Font-family : Arial;
}
Ul {
Color : aqua
}
</STYLE>
</HEAD>
</HTML>
In the above example since the unordered list elements appear within the BODY selector then by
default inherit the style specified for the BODY [Link] since we wish to have different settings for the
list we override by setting the style for the UL tag also.
The BODY section of the HTML code is shown below
<BODY>
<UL>
<LI>Mangoes
<LI>Oranges
<LI>Apples
</UL>
<OL>
<LI>Mangoes
<LI>Oranges
<LI>Apples
</OL>
</BODY>
</HTML>
Elements that are not included within the style tags will have the same settings as that of the BODY tag.
Style Sheet Properties
✓ Font properties
✓ Text properties
✓ Color and Background properties
✓ Box properties
✓ Padding properties
Font properties

Property Description Values


font-style, font-variant, font-weight, font-
Sets all the font properties size/line-height, font-family, caption, icon,
Font
in one declaration menu, message-box, small-caption, status-
bar, inherit
font- Specifies the font family
family-name, generic-family, inherit
family for text
xx-small, x-small, small, medium, large, x-
Specifies the font size of
font-size large, xx-large, smaller, larger, length,
text
%, inherit
Specifies the font style for
font-style normal, italic, oblique, inherit
text
Specifies whether or not a
font-
text should be displayed normal, small-caps, inherit
variant
in a small-caps font
normal, bold, bolder, lighter,
font- Specifies the weight of a
100, 200, 300, 400, 500, 600, 700, 800,
weight font
900, inherit

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, %
letter- Increase or decrease the space
normal, length
spacing between characters
text-align Aligns the text in an element left, right, center, justify
text-
Adds decoration to text none, underline, overline, line-through
decoration
Indents the first line of text in an
text-indent length, %
element
text-
Controls the letters in an element none, capitalize, uppercase, lowercase
transform
Color and Background properties

1. background-color
2. background-image
3. background-repeat
4. background-attachment
5. background-position

1) CSS background-color

The background-color property is used to specify the background color of the element.

2) CSS background-image

The background-image property is used to set an image as a background of an element. By default the
image covers the entire element.

3) CSS background-repeat

By default, the background-image property repeats the background image horizontally and vertically.
Some images are repeated only horizontally or vertically.
The background looks better if the image repeated horizontally only.

background-repeat: repeat-x;

4) CSS background-attachment

The background-attachment property is used to specify if the background image is fixed or scroll with the
rest of the page in browser window. If you set fixed the background image then the image will not move
during scrolling in the browser.

5) CSS background-position

The background-position property is used to define the initial position of the background image. By default,
the background image is placed on the top-left of the webpage.

You can set the following positions:

1. center
2. top
3. bottom
4. left
5. right
6. background: white url('[Link]');
7. background-repeat: no-repeat;
8. background-attachment: fixed;
9. background-position: center;

Box properties
Block style elements such as the <P> element can be considered as rectangular boxes on the screen.
Box properties include : Margin properties and Border properties
Margin properties
The margin value should be in length like 15pt etc. The individual margins for a block element can be
set using margin-top,margin-rigid,margin-bottom or margin-left.
Border properties
Border-style : Used to set the appearance of the borders. The values can
include solid,double,groove,ridge etc.
Border-width : Used to mention the width of the border.
Border – color : Border may be assigned a color.
Padding properties
The space between an element’s border and its content can be specified in four padding regions can
be set using the padding-top,padding-right,padding-bottom and padding-left properties.

1. XML – Overview

XML stands for Extensible Markup Language. It is a text-based markup language


derivedfrom Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data. XML is
notgoing to replace HTML in the near future, but it introduces new possibilities by
adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of
systemsand solutions:
• XML is extensible: XML allows you to create your own self-descriptive tags
orlanguage, that suits your application.

• XML carries the data, does not present it: XML allows you to store the
datairrespective of how it will be presented.

• XML is a public standard: XML was developed by an organization called the


WorldWide Web Consortium (W3C) and is available as an open standard.
XML Usage

• XML can work behind the scene to simplify the creation of HTML
documents forlarge web sites.

• XML can be used to exchange the information between organizations and systems.

• XML can be used for offloading and reloading of databases.

• XML can be used to store and arrange the data, which can customize your
datahandling needs.

• XML can easily be merged with style sheets to create almost any desired output.

• Virtually, any type of data can be expressed as an XML document.

What is Markup?

XML is a markup language that defines set of rules for encoding documents in a format
that is both human-readable and machine-readable. So, what exactly is a markup
language? Markup is information added to a document that enhances its meaning in
certain ways, in that it identifies the parts and how they relate to each other. More
specifically, a markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text:

<message>
<text>Hello, world!</text>
</message>

This snippet includes the markup symbols, or the tags such as


<message>...</message>and <text>... </text>. The tags <message> and </message>
mark the start and the endof the XML code fragment. The tags <text> and </text>
surround the text Hello, world!.

Is XML a Programming Language?

A programming language consists of grammar rules and its own vocabulary which is
usedto create computer programs. These programs instruct the computer to perform
specific tasks. XML does not qualify to be a programming language as it does not
perform any computation or algorithms. It is usually stored in a simple text file and is
processed by special software that is capable of interpreting XML

2. XML – Syntax

In this chapter, we will discuss the simple syntax rules to write an XML
[Link] is a complete XML document:

<?xml version="1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

You can notice, there are two kinds of information in the above example:
• Markup, like <contact-info>
• The text, or the character data, Tutorials Point and (040) 123-4567

The following diagram depicts the syntax rules to write different types of markup and
textin an XML document.

Let us see each component of the above diagram in detail.

XMLDeclaration
The XML document can optionally have an XML declaration. It is written as follows:

<?xml version="1.0" encoding="UTF-8"?>

Where version is the XML version and encoding specifies the character encoding
used inthe document.

Syntax Rules for XML Declaration


• The XML declaration is case sensitive and must begin with "<?xml>" where
"xml"is written in lower-case.

• If the document contains XML declaration, then it strictly needs to be the


firststatement of the XML document.

• The XML declaration strictly needs be the first statement in the XML document.

• An HTTP protocol can override the value of encoding that you put in the
XMLdeclaration.

Tags and Elements

An XML file is structured by several XML-elements, also called XML-nodes or


[Link] names of XML-elements are enclosed in triangular brackets < > as
shown below:

<element>

Syntax Rules for Tags and Elements


Element Syntax: Each XML-element needs to be closed either with start or with
endelements as shown below:

<element> ... </element>

or in simple-cases, just this way:

<element/>

Nesting of Elements: An XML-element can contain multiple XML-elements as its


children,but the children elements must not overlap. i.e., an end tag of an element must
have thesame name as that of the most recent unmatched start tag.
The following example shows incorrect nested tags:

<?xml version="1.0"?>
<contact-info>
<company>TutorialsPoint
<contact-info>
</company>

The following example shows correct nested tags:

<?xml version="1.0"?>
<contact-info>
<company>TutorialsPoint</company>
<contact-info>

Root Element: An XML document can have only one root element. For example,
followingis not a correct XML document, because both the x and y elements occur at
the top levelwithout a root element:

<x>...</x>
<y>...</y>

The following example shows a correctly formed XML document:

<root>
<x>...</x>
<y>...</y>
</root>

Case Sensitivity: The names of XML-elements are case-sensitive. That means the
nameof the start and the end elements need to be exactly in the same case.
For example, <contact-info> is different from <Contact-Info>.

XML Attributes

An attribute specifies a single property for the element, using a name/value pair. An
XML-element can have one or more attributes. For example:
<a href="[Link]

Here href is the attribute name and [Link] is attribute


value.
Syntax Rules for XML Attributes
• Attribute names in XML (unlike HTML) are case sensitive.
Thatis, HREF and href are considered two different XML attributes.

• Same attribute cannot have two values in a syntax. The following example
showsincorrect syntax because the attribute b is specified twice:

<a b="x" c="y" b="z"> ... </a>

• Attribute names are defined without quotation marks, whereas attribute values
must always appear in quotation marks. Following example demonstrates
incorrectxml syntax:

<a b=x> ... </a>

In the above syntax, the attribute value is not defined in quotation marks.

XMLReferences

References usually allow you to add or include additional text or markup in an XML
document. References always begin with the symbol "&" which is a reserved
character and end with the symbol ";". XML has two types of references:
• Entity References: An entity reference contains a name between the start and
the end delimiters. For example, &amp; where amp is name. The name refers
to a predefined string of text and/or markup.

• Character References: These contain references, such as &#65;, contains a


hash mark (“#”) followed by a number. The number always refers to the Unicode
code of a character. In this case, 65 refers to alphabet "A".

XMLText

The names of XML-elements and XML-attributes are case-sensitive, which means the
nameof start and end elements need to be written in the same case. To avoid character
encodingproblems, all XML files should be saved as Unicode UTF-8 or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-elements and
between the XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be used
directly. To use them, some replacement-entities are used, which are listed below:

Not Allowed Character Replacement Entity Character


Description
< &lt; less than
> &gt; greater than
& &amp; ampersand
' &apos; apostrophe
" &quot; quotation mark
3. XML – Documents

An XML document is a basic unit of XML information composed of elements and other
markup in an orderly package. An XML document can contain a wide variety of data.
For example, database of numbers, numbers representing molecular structure or a
mathematical equation.
XML Document Example
A simple document is shown in the following example:

<?xml version="1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

The following image depicts the parts of XML document.

Document Prolog Section

Document Prolog comes at the top of the document, before the root element.
Thissection contains:
• XML declaration
• Document type declaration
You can learn more about XML declaration in this chapter : XML Declaration.

Document Elements Section

Document Elements are the building blocks of XML. These divide the document into
a hierarchy of sections, each serving a specific purpose. You can separate a document
into multiple sections so that they can be rendered differently, or used by a search
engine. Theelements can b containers, with a combination of text and other elements.
4. XML – Declaration

This chapter covers XML declaration in detail. XML declaration contains details that
prepare an XML processor to parse the XML document. It is optional, but when used,
it must appear in the first line of the XML document.

Syntax
Following syntax shows XML declaration:

<?xml
version="version_number"
encoding="encoding_declaration"
standalone="standalone_status"
?>

Each parameter consists of a parameter name, an equals sign (=), and parameter
valueinside a quote. Following table shows the above syntax in detail:

Parameter Parameter_value Parameter_description


Specifies the version of the XML
Version 1.0 standardused.
UTF-8, UTF-16, ISO-
10646-UCS-2, ISO-
10646-UCS-4, ISO- It defines the character encoding used
in
Encoding 8859-1 to ISO-8859- the document. UTF-8 is the
defaultencoding used.
9,ISO-2022-JP,
Shift_JIS,
EUC-JP

It informs the parser whether the


document relies on the information from
an external source, such as external
yes or no.
Standalone document type definition (DTD), for its
content. The default value is set to no.
Setting it to yes tells the processor there
are no external declarations required for
parsing the document.
Rules
An XML declaration should abide with the following rules:
• If the XML declaration is present in the XML, it must be placed as
the first line inthe XML document.

• If the XML declaration is included, it must contain version number attribute.

• The parameter names and values are case-sensitive.

• The names are always in lower case.

• The order of placing the parameters is important. The correct


order is: version,encoding and standalone.

• Either single or double quotes may be used.

• The XML declaration has no closing tag, i.e. </?xml>

XML Declaration Examples


Following are few examples of XML declarations:
XML declaration with no parameters:

<?xml >

XML declaration with version definition:

<?xml version="1.0">

XML declaration with all parameters defined:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>

XML declaration with all parameters defined in single quotes:

<?xml version='1.0' encoding='iso-8859-1' standalone='no' ?>

5. XML – Tags

Let us learn about one of the most important part of XML, the XML tags. XML
tags form the foundation of XML. They define the scope of an element in
XML. They can also be usedto insert comments, declare settings required for
parsing the environment, and to insert special instructions.
We can broadly categorize XML tags as follows:

StartTag

The beginning of every non-empty XML element is marked by a start-tag.


Following is anexample of start-tag:

<address>

EndTag

Every element that has a start tag should end with an end-tag. Following is
an example ofend-tag:

</address>

Note, that the end tags include a solidus ("/") before the name of an element.

EmptyTag

The text that appears between start-tag and end-tag is called content. An
element whichhas no content is termed as empty. An empty element can be
represented in two ways asfollows:
A start-tag immediately followed by an end-tag as shown below:

<hr></hr>

A complete empty-element tag is as shown below:

<hr />

Empty-element tags may be used for any element which has no content.

DHTML

DHTML stands for Dynamic HTML, it is totally different from HTML. The browsers which
support the dynamic HTML are some of the versions of Netscape Navigator and Internet Explorer of
version higher than 4.0. The DHTML is based on the properties of the HTML, javascript, CSS, and
DOM (Document Object Model which is used to access individual elements of a document) which
helps in making dynamic content. It is the combination of HTML, CSS, JS, and DOM. The DHTML
make use of Dynamic object model to make changes in settings and also in properties and
methods. It also makes uses of Scripting and it is also part of earlier computing trends.
DHTML allows different scripting languages in a web page to change their variables, which
enhance the effects, looks and many others functions after the whole page have been fully loaded or
under a view process, or otherwise static HTML pages on the same. But in true ways, there is noting
that as dynamic in DHTML, there is only the enclosing of different technologies like CSS, HTML, JS,
DOM, and different sets of static languages which make it as dynamic.
DHTML is used to create interactive and animated web pages that are generated in real-time,
also known as dynamic web pages so that when such a page is accessed, the code within the page
is analyzed on the web server and the resulting HTML is sent to the client’s web browser.
HTML: HTML stands for Hypertext Markup Language and it is a client-side markup language. It is
used to build the block of web pages.
Javascript: It is a Client-side Scripting language. Javascript is supported by most of the browser,
also have cookies collection to determine the user needs.
CSS: The abbreviation of CSS is Cascading Style Sheet. It helps in the styling of the web pages and
helps in designing of the pages. The CSS rules for DHTML will be modified at different levels using
JS with event handlers which adds a significant amount of dynamism with very little code.
DOM: It is known as a Document Object Model which act as the weakest links in it. The only defect
in it is that most of the browser does not support DOM. It is a way to manipulate the static contents.
DHTML is not a technology; rather, it is the combination of three different technologies,
client-side scripting (JavaScript or VBScript), cascading style sheets and document object
model.

Key Features: Following are the some major key features of DHTML:

• Tags and their properties can be changed using DHTML.


• It is used for real-time positioning.
• Dynamic fonts can be generated using DHTML.
• It is also used for data binding.
• It makes a webpage dynamic and be used to create animations, games, applications along
with providing new ways of navigating through websites.
• The functionality of a webpage is enhanced due to the usage of low-bandwidth effect by
DHTML.
• DHTML also facilitates the use of methods, events, properties, and codes.
Why Use DHTML?
DHTML makes a webpage dynamic but Javascript also does, the question arises that what
different does DHTML do? So the answer is that DHTML has the ability to change a
webpages look, content and style once the document has loaded on our demand without
changing or deleting everything already existing on the browser’s webpage. DHTML can
change the content of a webpage on demand without the browser having to erase everything
else, i.e. being able to alter changes on a webpage even after the document has completely
loaded.
Advantages:

• Size of the files are compact in compared to other interactional media like Flash or
Shockwave, and it downloads faster.
• It is supported by big browser manufacturers like Microsoft and Netscape.
• Highly flexible and easy to make changes.
• Viewer requires no extra plug-ins for browsing through the webpage that uses DHTML,
they do not need any extra requirements or special software to view it.
• User time is saved by sending less number of requests to the server. As it is possible to
modify and replace elements even after a page is loaded, it is not required to create
separate pages for changing styles which in turn saves time in building pages and also
reduces the number of requests that are sent to the server.
• It has more advanced functionality than a static HTML. it is capable of holding more
content on the web page at the same time.
Disadvantages:

• It is not supported by all the browsers. It is supported only by recent browsers such as
Netscape 6, IE 5.5, and Opera 5 like browsers.
• Learning of DHTML requires a lot of pre-requisites languages such as HTML, CSS, JS, etc
should be known to the designer before starting with DHTML which is a long and time-
consuming in itself.
• Implementation of different browsers are different. So if it worked in one browser, it might
not necessarily work the same way in another browser.
• Even after being great with functionality, DHTML requires a few tools and utilities that are
some expensive. For example, the DHTML text editor, Dreamweaver. Along with it the
improvement cost of transferring from HTML to DHTML makes cost rise much higher.

DOM (Document Object Model)


The Document Object Model (DOM) is a programming interface for HTML(HyperText Markup
Language) and XML(Extensible markup language) documents. It defines the logical structure of
documents and the way a document is accessed and manipulated.
DOM is a way to represent the webpage in a structured hierarchical way so that it will become
easier for programmers and users to glide through the document. With DOM, we can easily access and
manipulate tags, IDs, classes, Attributes, or Elements of HTML using commands or methods provided
by the Document object. Using DOM, the JavaScript gets access to HTML as well as CSS of the web
page and can also add behavior to the HTML elements. so basically Document Object Model is an
API that represents and interacts with HTML or XML documents.

Why DOM is required?


HTML is used to structure the web pages and Javascript is used to add behavior to our web
pages. When an HTML file is loaded into the browser, the javascript can not understand the HTML
document directly. So, a corresponding document is created(DOM). DOM is basically the
representation of the same HTML document but in a different format with the use of objects.
Javascript interprets DOM easily i.e javascript can not understand the tags(<h1>H</h1>) in HTML
document but can understand object h1 in DOM. Now, Javascript can access each of the objects (h1,
p, etc) by using different functions.

Structure of DOM: DOM can be thought of as a Tree or Forest(more than one tree). The term structure
model is sometimes used to describe the tree-like representation of a document. Each branch of the
tree ends in a node, and each node contains objects Event listeners can be added to nodes and
triggered on an occurrence of a given event. One important property of DOM structure models
is structural isomorphism: if any two DOM implementations are used to create a representation of the
same document, they will create the same structure model, with precisely the same objects and
relationships.

Why called an Object Model?


Documents are modeled using objects, and the model includes not only the structure of a document but
also the behavior of a document and the objects of which it is composed like tag elements with attributes
in HTML.

Properties of DOM: Let’s see the properties of the document object that can be accessed and modified
by the document object.

Representation of the DOM

• Window Object: Window Object is object of the browser which is always at top of the
hierarchy. It is like an API that is used to set and access all the properties and methods of
the browser. It is automatically created by the browser.
• Document object: When an HTML document is loaded into a window, it becomes a
document object. The ‘document’ object has various properties that refer to other objects
which allow access to and modification of the content of the web page. If there is a need to
access any element in an HTML page, we always start with accessing the ‘document’ object.
Document object is property of window object.

• Form Object: It is represented by form tags.


• Link Object: It is represented by link tags.
• Anchor Object: It is represented by a href tags.
• Form Control Elements:: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
Methods of Document Object:
• write(“string”): Writes the given string on the document.
• getElementById(): returns the element having the given id value.
• getElementsByName(): returns all the elements having the given name value.
• getElementsByTagName(): returns all the elements having the given tag name.
• getElementsByClassName(): returns all the elements having the given class name.
Example: In this example, We use HTML element id to find the DOM HTML element.
HTML

<!DOCTYPE html>
<html>

<body>
<h2>GeeksforGeeks</h2>

<!-- Finding the HTML Elements by their Id in DOM -->


<p id="intro">A Computer Science portal for geeks.</p>
<p>This example illustrates the <b>getElementById</b> method.</p>
<p id="demo"></p>
<script>
const element = [Link]("intro");
[Link]("demo").innerHTML =
"GeeksforGeeks introduction is: " + [Link];
</script>
</body>
</html>

Output:

Getting the HTML element by getElementById() Method

Example: This example describes the representation of the HTML elements in the tree structure.
html
<table>
<ROWS>
<tr>
<td>Car</td>
<td>Scooter</td>
</tr>
<tr>
<td>MotorBike</td>
<td>Bus</td>
</tr>
</ROWS>
</table>

HTML elements in tree-like structure

What DOM is not?


• The Document Object Model is not a binary description where it does not define any binary
source code in its interfaces.
• The Document Object Model is not used to describe objects in XML or HTML whereas the
DOM describes XML and HTML documents as objects.
• The Document Object Model is not represented by a set of data structures; it is an interface
that specifies object representation.
• The Document Object Model does not show the criticality of objects in documents i.e it
doesn’t have information about which object in the document is appropriate to the context and
which is not.
Levels of DOM:
• Level 0: Provides a low-level set of interfaces.
• Level 1: DOM level 1 can be described in two parts: CORE and HTML.
• CORE provides low-level interfaces that can be used to represent any structured
document.
• HTML provides high-level interfaces that can be used to represent HTML
documents.
• Level 2: consists of six specifications: CORE2, VIEWS, EVENTS, STYLE,TRAVERSAL,
and RANGE.
• CORE2: extends the functionality of CORE specified by DOM level 1.
• VIEWS: views allows programs to dynamically access and manipulate the content
of the document.
• EVENTS: Events are scripts that are either executed by the browser when the
user reacts to the web page.
• STYLE: allows programs to dynamically access and manipulate the content of
style sheets.
• TRAVERSAL: This allows programs to dynamically traverse the document.
• RANGE: This allows programs to dynamically identify a range of content in the
document.
• Level 3: consists of five different specifications: CORE3, LOAD and
SAVE, VALIDATION, EVENTS, and XPATH.
• CORE3: extends the functionality of CORE specified by DOM level 2.
• LOAD and SAVE: This allows the program to dynamically load the content of the
XML document into the DOM document and save the DOM Document into an XML
document by serialization.
• VALIDATION: This allows the program to dynamically update the content and
structure of the document while ensuring the document remains valid.
• EVENTS: extends the functionality of Events specified by DOM Level 2.
• XPATH: XPATH is a path language that can be used to access the DOM tree.
Example: This example illustrates the dom-manipulation using getElementById() Method.
HTML

<!DOCTYPE html>
<html>
<head>
<title>DOM manipulation</title>
</head>
<body>
<label>Enter Value 1: </label>
<input type="text" id="val1" />
<br />
<br />
<label>Enter Value 2: </label>
<input type=".text" id="val2" />
<br />
<button onclick="getAdd()">Click To Add</button>
<p id="result"></p>
<script type="text/javascript">
function getAdd() {
// Fetch the value of input with id val1
const num1 = Number([Link]("val1").value);
// Fetch the value of input with id val2
const num2 = Number([Link]("val2").value);
const add = num1 + num2;
[Link](add);
// Displays the result in paragraph using dom
[Link]("result").innerHTML = "Addition : " + add;
// Changes the color of paragraph tag with red
[Link]("result").[Link] = "red";
}
</script>
</body>
</html>

Output:

Manipulating the Document objects using getElementById() Method

EVENT BUBBLING
Data Binding
The user interface or UI is the piece of our web applications that we present to
the end user. Sometimes we want to update the UI to reflect changes in input or vice
versa. For this task, we can use data binding. This means that we can connect
changes to an object to the UI.
For example, if you have an Employee Name input field, then you should be able to
have the underlying data change as well. Most data binding is done between an
external application and an underlying database system. However, we now have tools
that let us complete two-way binding right in the web browser. Two-way binding
means that updates to the UI and model are kept in sync.
The graphic below shows how one-way and two-way binding work.

The word model in the graphic simply means the data model. In our example, we will
be using an Employee Name and Rate as fields in our model. When they are updated in
the UI, they get updated in the model (and vice versa). There are tools out there such
as AngularJS, Knockout, Backbones, Derby, or Meteor. These tools provide built-in data
binding and their own syntax.

Data Binding in JavaScript


You can also accomplish binding in native JavaScript! First, let's build a simple HTML
page with some inputs. When the user enters data in the fields, we want to dynamically
update the UI. This is why you will see that each field is repeated. Don't worry, it will
make sense when we get to the actual JavaScript.

<html>
<head>
<title>Data Binding in JavaScript</title>
<head>
<body>
<p>Employee Name: <input class="emp" type="text"></p>
<p>Output: <input class="emp" type="text"></p>
<p>Rate: <input class="rate" type="text"></p>
<p>Output: <input class="rate" type="text"></p>
<script src="[Link]"></script>
</body>
</html>
When you open this page in a browser, it looks like this:

Data binding HTML output

Now for the fun part. The following JavaScript may look intimidating, but when
examined carefully, we can see how the data is kept in sync with the UI. Recall that we
have two fields, each of the same class and name for both Employee Name and Rate.
The JavaScript code looks at these and ensures that both are kept up to date.
var $scope = {};
function bindMe() {
var boundClasses = ["emp", "rate"];
var attachEvent = function (classes) {
[Link](function (thisClass) {
var elements = [Link](thisClass);
for (var i in elements) {
elements[i].onkeyup = function bindMe() {
for (var i in elements) {
elements[i].value = [Link];
}
}
}
[Link]($scope, className, {
set: function (newValue) {
for (var i in elements) {
elements[i].value = newValue;
}
}
});
});
};
attachEvent(boundClasses);
}();
[Link] – OVERVIEW

What is JavaScript?
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side
script to interact with the user and make dynamic pages. It is an interpreted
programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript
made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.

The ECMA-262 Specification defined a standard version of the core JavaScript


language.

• JavaScript is a lightweight, interpreted programming language.

• Designed for creating network-centric applications.

• Complementary to and integrated with Java.

• Complementary to and integrated with HTML.

• Open and cross-platform.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted by
the browser.

It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.

Advantages of JavaScript
The merits of using JavaScript are:

• Less server interaction: You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your
server.

• Immediate feedback to the visitors: They don't have to wait for a page
reload to see if they have forgotten to enter something.

• Increased interactivity: You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.

• Richer interfaces: You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:

• Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.

• JavaScript cannot be used for networking applications because there is no such


support available.

• JavaScript doesn't have any multithreading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that


allows you to build interactivity into otherwise static HTML pages.

JavaScript Development Tools


One of major strengths of JavaScript is that it does not require expensive
development tools. You can start with a simple text editor such as Notepad. Since it
is an interpreted language inside the context of a web browser, you don't even need
to buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript
editing tools. Some of them are listed here:

• Microsoft FrontPage: Microsoft has developed a popular HTML editor called


FrontPage. FrontPage also provides web developers with a number of
JavaScript tools to assist in the creation of interactive websites.

• Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very


popular HTML and JavaScript editor in the professional web development
crowd. It provides several handy prebuilt JavaScript components, integrates
well with databases, and conforms to new standards such as XHTML and XML.

• Macromedia HomeSite 5: HomeSite 5 is a well-liked HTML and JavaScript


editor from Macromedia that can be used to manage personal websites
effectively.

Where is JavaScript Today?


The ECMAScript Edition 5 standard will be the first update to be released in over four
years. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the
difference between the two is extremely minor.

The specification for JavaScript 2.0 can be found on the following site:
[Link]

Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript


standard, although both the languages still support the features that are not a part
of the standard.
[Link] – SYNTAX

JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within the <head>
tags.

The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes:

• Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.

• Type: This attribute is what is now recommended to indicate the scripting


language in use and its value should be set to "text/javascript".

So your JavaScript syntax will look as follows.

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Your First JavaScript Code


Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser
that does not support JavaScript. The comment ends with a "//-->". Here "//"
signifies a comment in JavaScript, so we add that to prevent a browser from reading
the end of the HTML comment as a piece of JavaScript code. Next, we call a
function [Link] which writes a string into our HTML document.

This function can be used to write text, HTML, or both. Take a look at the following
code.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
[Link] ("Hello World!")
//-->
</script>
</body>
</html>

This code will produce the following result:

Hello World!

Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.

Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line. For example, the
following code could be written without semicolons.

<script language="javascript" type="text/javascript">


<!--
var1 = 10
var2 = 20
//-->
</script>

But when formatted in a single line as follows, you must use semicolons:

<script language="javascript" type="text/javascript">


<!--
var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.

So the identifiers Time and TIME will convey different meanings in JavaScript.

NOTE: Care should be taken while writing variable and function names in JavaScript.

Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:

• Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.

• Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.

• The HTML comment closing sequence --> is not recognized by JavaScript so it


should be written as //-->.

Example
The following example shows how to use comments in JavaScript.

<script language="javascript" type="text/javascript">


<!--

// This is a comment. It is similar to comments in C++

/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
[Link] – ENABLING

All the modern browsers come with built-in support for JavaScript. Frequently, you
may need to enable or disable this support manually. This chapter explains the
procedure of enabling and disabling JavaScript support in your browsers: Internet
Explorer, Firefox, chrome, and Opera.

JavaScript in Internet Explorer


Here are the steps to turn on or turn off JavaScript in Internet Explorer:

• Follow Tools -> Internet Options from the menu.

• Select Security tab from the dialog box.

• Click the Custom Level button.

• Scroll down till you find the Scripting option.

• Select Enable radio button under Active scripting.

• Finally click OK and come out.

To disable JavaScript support in your Internet Explorer, you need to select Disable
radio button under Active scripting.

JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox:

• Open a new tab -> type about: config in the address bar.

• Then you will find the warning dialog. Select I’ll be careful, I promise!

• Then you will find the list of configure options in the browser.

• In the search bar, type [Link].

• There you will find the option to enable or disable javascript by right-clicking
on the value of that option -> select toggle.

If [Link] is true; it converts to false upon clicking toogle. If javascript is


disabled; it gets enabled upon clicking toggle.
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome:

• Click the Chrome menu at the top right hand corner of your browser.

• Select Settings.

• Click Show advanced settings at the end of the page.

• Under the Privacy section, click the Content settings button.

• In the "Javascript" section, select "Do not allow any site to run JavaScript"
or "Allow all sites to run JavaScript (recommended)".

JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera:

• Follow Tools-> Preferences from the menu.

• Select Advanced option from the dialog box.

• Select Content from the listed items.

• Select Enable JavaScript checkbox.

• Finally click OK and come out.

To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.

Warning for Non-JavaScript Browsers


If you have to do something important using JavaScript, then you can display a
warning message to the user using <noscript> tags.

You can add a noscript block immediately after the script block as follows:

<html>
<body>

<script language="javascript" type="text/javascript">


<!--
[Link] ("Hello World!")
//-->
</script>

<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>

Now, if the user's browser does not support JavaScript or JavaScript is not enabled,
then the message from </noscript> will be displayed on the screen.
[Link] – PLACEMENT

There is a flexibility given to include JavaScript code anywhere in an HTML document.


However the most preferred ways to include JavaScript in an HTML file are as follows:

• Script in <head>...</head> section.

• Script in <body>...</body> section.

• Script in <body>...</body> and <head>...</head> sections.

• Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can place JavaScript in an HTML file in
different ways.

JavaScript in <head>...</head> Section


If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows.

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

This code will produce the following results:

Click here for the result

Say Hello

JavaScript in <body>...</body> Section


If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document. In this case,
you would not have any function defined using JavaScript. Take a look at the following
code.

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
[Link]("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

This code will produce the following results:

Hello World
This is web page body

JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as
follows.

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
[Link]("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

This code will produce the following result.

HelloWorld
Say Hello
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages of
a site.

You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.

<html>
<head>
<script type="text/javascript" src="[Link]" ></script>
</head>
<body>
.......
</body>
</html>

To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.

For example, you can keep the following content in [Link] file and then you
can use sayHello function in your HTML file after including the [Link] file.

function sayHello() {
alert("Hello World")
}
[Link] – VARIABLES

JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set
of data types it supports. These are the type of values that can be represented and
manipulated in a programming language.

JavaScript allows you to work with three primitive data types:

• Numbers, e.g., 123, 120.50 etc.

• Strings of text, e.g. "This text string" etc.

• Boolean, e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript
supports a composite data type known as object. We will cover objects in detail in a
separate chapter.

Note: Java does not make a distinction between integer values and floating-point
values. All numbers in JavaScript are represented as floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 754
standard.

JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.

<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

You can also declare multiple variables with the same var keyword as follows:

<script type="text/javascript">
<!--
var money, name;
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable


initialization at the time of variable creation or at a later point in time when you need
that variable.

For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable, you can assign a value at the time of
initialization as follows.

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

Note: Use the var keyword only for declaration or initialization, once for the life of
any variable name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable will hold. The value type
of a variable can change during the execution of a program and JavaScript takes care
of it automatically.
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.

• Global Variables: A global variable has global scope which means it can be
defined anywhere in your JavaScript code.

• Local Variables: A local variable will be visible only within a function where it
is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the
same name as a global variable, you effectively hide the global variable. Take a look
into the following example.

<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
[Link](myVar);
}
//-->
</script>

It will produce the following result:

Local
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind.
• You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For example, break
or boolean variable names are not valid.

• JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.

• JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.
JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following table. They
cannot be used as JavaScript variables, functions, methods, loop labels, or any object
names.

abstract else Instanceof switch

boolean enum int interface synchronized

break byte export long native this

case catch extends new throw

char class false final null throws

const finally package transient

continue float for private true

debugger function protected try

default goto public typeof

delete if return var void

do implemenes short static volatile

double import super while

in with
[Link] – OPERATORS

What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator. JavaScript supports the following types of
operators.

• Arithmetic Operators

• Comparison Operators

• Logical (or Relational) Operators

• Assignment Operators

• Conditional (or ternary) Operators

Let’s have a look at all the operators one by one.

Arithmetic Operators
JavaScript supports the following arithmetic operators:

Assume variable A holds 10 and variable B holds 20, then:

S. No. Operator and Description

+ (Addition)

1 Adds two operands

Ex: A + B will give 30

- (Subtraction)

2 Subtracts the second operand from the first

Ex: A - B will give -10


* (Multiplication)

3 Multiply both operands

Ex: A * B will give 200

/ (Division)

4 Divide the numerator by the denominator

Ex: B / A will give 2

% (Modulus)

5 Outputs the remainder of an integer division

Ex: B % A will give 0

++ (Increment)

6 Increases an integer value by one

Ex: A++ will give 11

-- (Decrement)

7 Decreases an integer value by one

Ex: A-- will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

[Link]("a + b = ");
result = a + b;
[Link](result);
[Link](linebreak);

[Link]("a - b = ");
result = a - b;
[Link](result);
[Link](linebreak);

[Link]("a / b = ");
result = a / b;
[Link](result);
[Link](linebreak);

[Link]("a % b = ");
result = a % b;
[Link](result);
[Link](linebreak);

[Link]("a + b + c = ");
result = a + b + c;
[Link](result);
[Link](linebreak);
a = a++;
[Link]("a++ = ");
result = a++;
[Link](result);
[Link](linebreak);

b = b--;
[Link]("b-- = ");
result = b--;
[Link](result);
[Link](linebreak);

//-->
</script>

<p>Set the variables to different values and then try...</p>


</body>
</html>

Output

a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
a++ = 33
b-- = 10

Set the variables to different values and then try...


Comparison Operators
JavaScript supports the following comparison operators:

Assume variable A holds 10 and variable B holds 20, then:

[Link] Operator and Description

== (Equal)

Checks if the value of two operands are equal or not, if yes, then
1
the condition becomes true.

Ex: (A == B) is not true.

!= (Not Equal)

Checks if the value of two operands are equal or not, if the values
2
are not equal, then the condition becomes true.

Ex: (A != B) is true.

> (Greater than)

Checks if the value of the left operand is greater than the value of
3
the right operand, if yes, then the condition becomes true.

Ex: (A > B) is not true.

< (Less than)

Checks if the value of the left operand is less than the value of the
4
right operand, if yes, then the condition becomes true.

Ex: (A < B) is true.

>= (Greater than or Equal to)

Checks if the value of the left operand is greater than or equal to


5 the value of the right operand, if yes, then the condition becomes
true.

Ex: (A >= B) is not true.


<= (Less than or Equal to)

Checks if the value of the left operand is less than or equal to the
6
value of the right operand, if yes, then the condition becomes true.

Ex: (A <= B) is true.

Example
The following code shows how to use comparison operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

[Link]("(a == b) => ");


result = (a == b);
[Link](result);
[Link](linebreak);

[Link]("(a < b) => ");


result = (a < b);
[Link](result);
[Link](linebreak);

[Link]("(a > b) => ");


result = (a > b);
[Link](result);
[Link](linebreak);
[Link]("(a != b) => ");
result = (a != b);
[Link](result);
[Link](linebreak);

[Link]("(a >= b) => ");


result = (a >= b);
[Link](result);
[Link](linebreak);

[Link]("(a <= b) => ");


result = (a <= b);
[Link](result);
[Link](linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
(a <= b) => true

Set the variables to different values and different operators and then
try...

Logical Operators
JavaScript supports the following logical operators:

Assume variable A holds 10 and variable B holds 20, then:

[Link] Operator and Description

&& (Logical AND)

1 If both the operands are non-zero, then the condition becomes true.

Ex: (A && B) is true.

|| (Logical OR)

2 If any of the two operands are non-zero, then the condition becomes true.

Ex: (A || B) is true.

! (Logical NOT)

Reverses the logical state of its operand. If a condition is true, then the
3
Logical NOT operator will make it false.

Ex: ! (A && B) is false.


Example
Try the following code to learn how to implement Logical Operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

[Link]("(a && b) => ");


result = (a && b);
[Link](result);
[Link](linebreak);

[Link]("(a || b) => ");


result = (a || b);
[Link](result);
[Link](linebreak);

[Link]("!(a && b) => ");


result = (!(a && b));
[Link](result);
[Link](linebreak);

//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

(a && b) => false


(a || b) => true
!(a && b) => true

Set the variables to different values and different operators and then
try...

Bitwise Operators
JavaScript supports the following bitwise operators:
Assume variable A holds 2 and variable B holds 3, then:

[Link] Operator and Description

& (Bitwise AND)

1 It performs a Boolean AND operation on each bit of its integer arguments.

Ex: (A & B) is 2.

| (BitWise OR)

2 It performs a Boolean OR operation on each bit of its integer arguments.

Ex: (A | B) is 3.

3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand
two is true, but not both.

Ex: (A ^ B) is 1.

~ (Bitwise Not)

4 It is a unary operator and operates by reversing all the bits in the operand.

Ex: (~B) is -4.

<< (Left Shift)

It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a
5
value left by one position is equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and so on.

Ex: (A << 1) is 4.

>> (Right Shift)

Binary Right Shift Operator. The left operand’s value is moved right by the
6
number of bits specified by the right operand.

Ex: (A >> 1) is 1.

>>> (Right shift with Zero)

This operator is just like the >> operator, except that the bits shifted in
7
on the left are always zero.

Ex: (A >>> 1) is 1.

Example
Try the following code to implement Bitwise operator in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

[Link]("(a & b) => ");


result = (a & b);
[Link](result);
[Link](linebreak);

[Link]("(a | b) => ");


result = (a | b);
[Link](result);
[Link](linebreak);

[Link]("(a ^ b) => ");


result = (a ^ b);
[Link](result);
[Link](linebreak);

[Link]("(~b) => ");


result = (~b);
[Link](result);
[Link](linebreak);

[Link]("(a << b) => ");


result = (a << b);
[Link](result);
[Link](linebreak);
[Link]("(a >> b) => ");
result = (a >> b);
[Link](result);
[Link](linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0

Set the variables to different values and different operators and then
try...

Assignment Operators
JavaScript supports the following assignment operators:

[Link] Operator and Description

= (Simple Assignment )
1
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

+= (Add and Assignment)

It adds the right operand to the left operand and assigns the result to the
2
left operand.

Ex: C += A is equivalent to C = C + A

-= (Subtract and Assignment)

It subtracts the right operand from the left operand and assigns the result
3
to the left operand.

Ex: C -= A is equivalent to C = C - A

*= (Multiply and Assignment)

It multiplies the right operand with the left operand and assigns the result
4
to the left operand.

Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment)

It divides the left operand with the right operand and assigns the result to
5
the left operand.

Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment)

It takes modulus using two operands and assigns the result to the left
6
operand.

Ex: C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators, so they will become <<=, >>=, >>=,
&=, |= and ^=.

Example
Try the following code to implement assignment operator in JavaScript.
<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

[Link]("Value of a => (a = b) => ");


result = (a = b);
[Link](result);
[Link](linebreak);

[Link]("Value of a => (a += b) => ");


result = (a += b);
[Link](result);
[Link](linebreak);

[Link]("Value of a => (a -= b) => ");


result = (a -= b);
[Link](result);
[Link](linebreak);

[Link]("Value of a => (a *= b) => ");


result = (a *= b);
[Link](result);
[Link](linebreak);
[Link]("Value of a => (a /= b) => ");
result = (a /= b);
[Link](result);
[Link](linebreak);

[Link]("Value of a => (a %= b) => ");


result = (a %= b);
[Link](result);
[Link](linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

Value of a => (a = b) => 10


Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0

Set the variables to different values and different operators and then
try...
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the
conditional operator (? :) and the typeof operator.

Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.

[Link] Operator and Description

? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y

Example
Try the following code to understand how the Conditional Operator works in
JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

[Link] ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
[Link](result);
[Link](linebreak);

[Link] ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
[Link](result);
[Link](linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

((a > b) ? 100 : 200) => 200


((a < b) ? 100 : 200) => 100

Set the variables to different values and different operators and then
try...

typeof Operator
The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand is a


number, string, or boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.

Type String Returned by typeof

Number "number"

String "string"
Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

Example
The following code shows how to implement typeof operator.

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


[Link]("Result => ");
[Link](result);
[Link](linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


[Link]("Result => ");
[Link](result);
[Link](linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

Result => B is String


Result => A is Numeric

Set the variables to different values and different operators and then
try...
CONDITIONAL STATEMENT
LOOPING STATEMENT
JavaScript HTML DOM Objects

In addition to the built-in JavaScript objects, you can also access and
manipulate all of the HTML DOM objects with JavaScript.

More JavaScript Objects


Follow the links to learn more about the objects and their collections, properties,
methods and events.

Object Description
Window The top level object in the JavaScript hierarchy. The Window
object represents a browser window. A Window object is
created automatically with every instance of a <body> or
<frameset> tag
Navigator Contains information about the client's browser
Screen Contains information about the client's display screen
History Contains the visited URLs in the browser window
Location Contains information about the current URL

The HTML DOM

The HTML DOM is a W3C standard and it is an abbreviation for the Document Object
Model for HTML.

The HTML DOM defines a standard set of objects for HTML, and a standard way to
access and manipulate HTML documents.

All HTML elements, along with their containing text and attributes, can be accessed
through the DOM. The contents can be modified or deleted, and new elements can
be created.

The HTML DOM is platform and language independent. It can be used by any
programming language like Java, JavaScript, and VBScript.

Follow the links below to learn more about how to access and manipulate each DOM
object with JavaScript:

Object Description
Document Represents the entire HTML document and can be used to
access all elements in a page
Anchor Represents an <a> element
Area Represents an <area> element inside an image-map
Base Represents a <base> element
Body Represents the <body> element
Button Represents a <button> element
Event Represents the state of an event
Form Represents a <form> element
Frame Represents a <frame> element
Frameset Represents a <frameset> element
Iframe Represents an <iframe> element
Image Represents an <img> element
Input button Represents a button in an HTML form
Input checkbox Represents a checkbox in an HTML form
Input file Represents a fileupload in an HTML form
Input hidden Represents a hidden field in an HTML form
Input password Represents a password field in an HTML form
Input radio Represents a radio button in an HTML form
Input reset Represents a reset button in an HTML form
Input submit Represents a submit button in an HTML form
Input text Represents a text-input field in an HTML form
Link Represents a <link> element
Meta Represents a <meta> element
Option Represents an <option> element
Select Represents a selection list in an HTML form
Style Represents an individual style statement
Table Represents a <table> element
TableData Represents a <td> element
TableRow Represents a <tr> element
Textarea Represents a <textarea> element

HTML DOM Window Object

Window Object

The Window object is the top level object in the JavaScript hierarchy.

The Window object represents a browser window.

A Window object is created automatically with every instance of a <body> or


<frameset> tag.

Window Object Collections


Collection Description
frames[] Returns all named frames in the window
Window Object Properties
Property Description
closed Returns whether or not a window has been closed
defaultStatus Sets or returns the default text in the statusbar of the
window
document See Document object
history See History object
length Sets or returns the number of frames in the window
location See Location object
name Sets or returns the name of the window
opener Returns a reference to the window that created the
window
outerHeight Sets or returns the outer height of a window
outerWidth Sets or returns the outer width of a window
pageXOffset Sets or returns the X position of the current page in
relation to the upper left corner of a window's display
area
pageYOffset Sets or returns the Y position of the current page in
relation to the upper left corner of a window's display
area
parent Returns the parent window
personalbar Sets whether or not the browser's personal bar (or
directories bar) should be visible
scrollbars Sets whether or not the scrollbars should be visible
self Returns a reference to the current window
status Sets the text in the statusbar of a window
statusbar Sets whether or not the browser's statusbar should
be visible
toolbar Sets whether or not the browser's tool bar is visible
or not (can only be set before the window is opened
and you must have UniversalBrowserWrite privilege)
top Returns the topmost ancestor window
Window Object Methods
Method Description
alert() Displays an alert box with a message and an OK
button
blur() Removes focus from the current window
clearInterval() Cancels a timeout set with setInterval()
clearTimeout() Cancels a timeout set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and
a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the contents of the current window
prompt() Displays a dialog box that prompts the user for input
resizeBy() Resizes a window by the specified pixels
resizeTo() Resizes a window to the specified width and height
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
setInterval() Evaluates an expression at specified intervals
setTimeout() Evaluates an expression after a specified number of
milliseconds

HTML DOM Navigator Object

Navigator Object

The Navigator object is actually a JavaScript object, not an HTML DOM object.

The Navigator object is automatically created by the JavaScript runtime engine and
contains information about the client browser.

Navigator Object Collections


Collection Description
plugins[] Returns a reference to all embedded objects in the
document
Navigator Object Properties
Property Description
appCodeName Returns the code name of the browser
appMinorVersion Returns the minor version of the browser
appName Returns the name of the browser
appVersion Returns the platform and version of the browser
browserLanguage Returns the current browser language
cookieEnabled Returns a Boolean value that specifies whether
cookies are enabled in the browser
cpuClass Returns the CPU class of the browser's system
onLine Returns a Boolean value that specifies whether
the system is in offline mode
platform Returns the operating system platform
systemLanguage Returns the default language used by the OS
userAgent Returns the value of the user-agent header sent
by the client to the server
userLanguage Returns the OS' natural language setting
Navigator Object Methods
Method Description
javaEnabled() Specifies whether or not the browser has Java
enabled
taintEnabled() Specifies whether or not the browser has data
tainting enabled

HTML DOM Screen Object

Screen Object

The Screen object is actually a JavaScript object, not an HTML DOM object..

The Screen object is automatically created by the JavaScript runtime engine and
contains information about the client's display screen.

Screen Object Properties


Property Description
availHeight Returns the height of the display screen
(excluding the Windows Taskbar)
availWidth Returns the width of the display screen
(excluding the Windows Taskbar)
bufferDepth Sets or returns the bit depth of the color
palette in the off-screen bitmap buffer
colorDepth Returns the bit depth of the color palette
on the destination device or buffer
deviceXDPI Returns the number of horizontal dots per
inch of the display screen
deviceYDPI Returns the number of vertical dots per
inch of the display screen
fontSmoothingEnabled Returns whether the user has enabled
font smoothing in the display control
panel
height The height of the display screen
logicalXDPI Returns the normal number of horizontal
dots per inch of the display screen
logicalYDPI Returns the normal number of vertical
dots per inch of the display screen
pixelDepth Returns the color resolution (in bits per
pixel) of the display screen
updateInterval Sets or returns the update interval for the
screen
width Returns width of the display screen
HTML DOM History Object

History Object

The History object is actually a JavaScript object, not an HTML DOM object.

The History object is automatically created by the JavaScript runtime engine and
consists of an array of URLs. These URLs are the URLs the user has visited within a
browser window.

The History object is part of the Window object and is accessed through the
[Link] property.

IE: Internet Explorer, F: Firefox, O: Opera.

History Object Properties


Property Description
length Returns the number of elements in the history list
History Object Methods
Method Description
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific page in the history list

HTML DOM History Object

History Object

The History object is actually a JavaScript object, not an HTML DOM object.
The History object is automatically created by the JavaScript runtime engine and
consists of an array of URLs. These URLs are the URLs the user has visited within a
browser window.

The History object is part of the Window object and is accessed through the
[Link] property.

IE: Internet Explorer, F: Firefox, O: Opera.

History Object Properties


Property Description
length Returns the number of elements in the history list
History Object Methods
Method Description
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific page in the history list

Browser Object Model

1. Browser Object Model (BOM)

The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of window by
specifying window or directly. For example:

1. [Link]("hello javatpoint");

is same as:

1. alert("hello javatpoint");

You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,
PlVideo te: The

document object represents an html document. It forms DOM (Document Object Model).
JavaScript and AJAX
191

UNIT 5

INTRODUCTION

HTML Web pages are static. They do not react to events. Also, they do not
produce different outputs when different users ask for them, or even when the
same user asks for them, but under different conditions. Therefore, there is a lot of
predictability about HTML pages. Moreover, the output is always the same. This
means that there is no programming involved at all. Therefore, attempts were
made to add interactivity to HTML pages. This was done both at the client (Web
browser) side, as well as the server (Web server) side. Thus, we have both client-
side as well as server-side programming on the Internet. The server-side
programming techniques will be discussed at length later. This chapter looks at the
client-side programming techniques. Several techniques have come and gone, but
the one that has stayed on is the JavaScript language. JavaScript is a quick and
dirty programming language, which can be used on the client (Web browser) for
performing a number of tasks, such as validating input, doing local calculations,
etc.
In addition to JavaScript, the technology of AJAX has gained prominence in
the last few years. We shall also discuss AJAX in detail.

7.1 JAVASCRIPT

7.1.1 Basic Concepts


We know that HTML pages are static. In other words, there is no interactivity in the
case of plain HTML pages. To add interactivity to HTML inside the browser itself,
the technology of JavaScript was developed. JavaScript involves programming.
We can write small programs that execute inside the HTML page, based on
certain events or just like that. These programs are written in JavaScript. Earlier,
there were a few other scripting languages such as VBScript and Jscript.
However, these technologies are obsolete now, and JavaScript is the only one
that has survived.
JavaScript is an interpreted language. It can be directly embedded inside
HTML pages, or it can be kept in a separate file (with extension .js) and referred to
in the HTML page. It is supported by all the major browsers, such as Internet
Explorer, Firefox, and Netscape Navigator. We need to remember that Java and
JavaScript do not have anything in common, except for the naming. It was cool to
call everything Java something when these technologies were coming up for the
first time. Hence, we have the name JavaScript.
JavaScript has several features:
□ Programming tool—JavaScript is a scripting language with a very simple
syntax.
□ Can produce dynamic text into an HTML page—For example, the
JavaScript statement [Link] (“<h1>” + name + “</h1>”); results
into the HTML output <h1>Atul</h1>, if the variable name contains the text
Atul.
□ Reacting to events—JavaScript code executes when something happens,
like when a page has finished loading or when a user clicks on an HTML
element.
□ Read and write HTML elements—JavaScript can read and change the
content of an HTML element.
□ Validate data—JavaScript can be used to validate form data before it is
submitted to a server. This saves the server from extra processing.
The first JavaScript is shown in Fig. 7.1.

<html>
<body>
<script type=”text/javascript”>
[Link] (“Hello World!”);
</script>
</body>
</html>

Fig. 7.1 JavaScript example

7.1.2 Controlling JavaScript Execution


As we can see, JavaScript is a part of the basic HTML page. It is contained inside the
<script>…</script>
tags. Here, document is the name of an object, and write is a method of that object.
We can control when JavaScript should code execute. By default, scripts in a
page will be executed immediately while the page loads into the browser. This is
not always what we want. Sometimes we want to execute a script when a page
loads, and at other times when a user triggers an event.
Scripts that we want to execute only when they are called, or when an event
is triggered, go in the head section. When we place a script in the head section,
we ensure that the script is loaded before anyone uses it. That is, it does not
execute on its own. However, if we put scripts in the body section, then they
automatically get executed when the page loads in the browser.
This difference is shown in Fig. 7.2.
Fig. 7.2 Where to place JavaScript

Of course, we can put as many scripts as we like, in an HTML page. Also,


there is no limitation on how many of them should be in the <head> section, and
how many of them should be in the <body>section
example we had shown earlier, the script was written inside the <body> section,
and therefore, it executed without needing to make any explicit call. Instead, if we
had written it inside the <head> section, then we would have needed to call it
explicitly from some part of the <body>section.
Let us understand the differences between the two clearly. Figure 7.3 shows
the code for writing a script inside the <head> section, versus in the <body>
section.

<html> <html>
<head> <head>
<script </head>
<body>
type=”text/javascript”>
<script type=”text/javascript”>
function message () {
alert (“Called from the <body> [Link] (“Directly
section”) executed”)
} </script>
</script> </body>
</html>
</head>
<body onload = “message ()”>
</body>
</html>
(a) Script in the <head> section (b) Script in the <body> section

Fig. 7.3 Writing scripts in <head› and <body› sections

As we can see, the difference is where we have put the script.


In case (a), the script is inside the <head> section, and therefore, must explicitly
get called to get executed. We call the script from the onload event of the <body>
section.
In other words, we tell the browser that as soon as it starts loading the HTML
page (i.e., the contents of the <body>section), it should call the message ()function
written in the <head> section. In case (b), the script is a part of the <body> section
itself, and therefore, would get executed as soon as the HTML page gets loaded
in the browser. There is no need to call this script from anywhere.
Figure 7.4 shows how to put the JavaScript in an external file and include it in
our HTML page. We have not shown the script code itself, as the example is only
to illustrate the concept.

<html>
<head>
</head>
<body>
<script src=”[Link]”></script>
</body>
</html>

Fig. 7.4 How to declare external JavaScript?

As we can see, the JavaScript code is supposed to be contained in a separate file


called as [Link].

7.1.3 Miscellaneous Features


Variables JavaScript allows us to define and use variables just like other
programming languages. Variables are declared using the keyword var. However,
this keyword is optional. In other words, the following two declarations are
equivalent.
var name = “test”;
name = “test”;
Variables can be local or global.
□ Local variables When we declare a variable within a function, the variable
can only be accessed within that function. When we exit the function, the
variable is destroyed. This type of variable is a local variable.
□ Global variables If we declare a variable outside a function, all the functions
on our HTML page can access it. The lifetime of these variables starts when
they are declared, and ends when the page is closed.
Figure 7.5 shows an example of using variables.
<html>
<head>
<title>Seconds in a day</title>
<script type = “text/javascript”>
var seconds_per_minute = 60;
var minutes_per_hour = 60;
var hours_per_day = 60;
var seconds_per_day = seconds_per_minute * minutes_per_hour * hours_per_day;
</script>
</head>
<body>
<h1> We can see that ...</h1>
<script type=”text/javascript”>
[Link] (“there are “);
[Link] (seconds_per_day);
[Link] (“ seconds in a day.”);
</script>
</body>
</html>

Fig. 7.5 Variables example

The resulting output is shown in Fig. 7.6.


Fig. 7.6 Output of variables example

Operators
JavaScript supports a variety of operators. Table 7.1 summarizes them.

Table 7.1 JavaScript operators

Operator classification List of


operators
Arithmetic + - * / % ++ --
Assignment = += -= *= /= %=
Comparison = < > <= >= !=
Logical && || !

Functions
A function contains block of code that needs to be executed repeatedly, or
based on certain events. Another part of the HTML page calls a JavaScript
function on needs basis. Usually, all functions should be defined in the <head>
section, right at the beginning of the HTML page, and should be called as and when
necessary. A function can receive arguments, or it can also be a function that does
not expect any arguments. A function is declared by using the keyword function,
followed by the name of the function, followed by parentheses. If there are any
arguments that the function expects, they are listed inside the parentheses,
separated by commas. A function can return a single value by using the return
statement. However, unlike standard programming languages, a function does not
have to mention its return data typein the function declaration.
Enough of theory! Let us now look at a function example, as shown in Fig. 7.7.

function total (a, b) {


result = a+b;
return result;
}
Fig. 7.7 Function example

As we can see, the name of the function is total. It expects two arguments.
What should be their data types? This is not needed to be mentioned. The
function adds the values of these two arguments and stores the result into a third
variable called as result. It then returns this value back to the caller. How would
the caller call this function? It would say something like sum = total (5, 7).
Conditional statements
JavaScript supports three types of conditional statements, if, if-else, and
switch. They work in a manner that is quite similar to what happens in Java or C#.
Figure 7.8 shows an example of the if statement.

<html>
<body>
<script type=”text/javascript”>
var d = new Date ();
var time = [Link] ();
if (time > 12) {
[Link] (“<b>Good afternoon</b>”);
}
</script>
</body>
</html>

Fig. 7.8 Example of if statement

The resulting output is shown in Fig. 7.9, assuming that currently it is the
afternoon.

Fig. 7.9 Output of if example

On the other hand, an if-else statement allows us to write alternative code


whenever the ifstatement is not true. Figure 7.10 shows an example of the if-else
statement.
<html>
<body>
<script type=”text/javascript”>
var d = new Date ();
var time = [Link] ();

if (time < 12) {


[Link] (“Good morning!”);
}
else {
[Link] (“Good day!”);
}
</script>
</body>
</html>

Fig. 7.1o Example of if-else statement

The resulting output is shown in Fig. 7.11.

Fig. 7.11 Output of if-else example

Figure 7.12 shows an example of the switch statement.

<html>
<body>
<script type = “text/javascript”>
var d = new Date ();
theDay = [Link] ();
switch (theDay) {
case 5:
[Link] (“Finally Friday”);
break;
case 6:
case 0:

(Contd)
Fig. 7.12 contd...

[Link] (“Super Weekend”);


break;
default:
[Link] (“I’m looking forward to this weekend!”);
}
</script>
</body>
</html>

Fig. 7.12 Example of switch statement

Figure 7.13 shows the resulting output.

Fig. 7.13 Output of the switch example

We can also use the ?: conditional operator in JavaScript. For example, we


can have the following code block.
greeting = (visitor == “Senior”) ? “Dear sir “: “Dear “;
Loops JavaScript provides three kinds of loops, while, do-while, and for. The while
loop first checks for the condition being tested, and if it is satisfied, only then
executes the code. The do-while loop first executes the code and then checks for
the condition being tested. In other words, it executes at least once, regardless of
whether the condition being tested is successful or not. The for loop executes in
iteration, usually incrementing or decrementing the loop index.
Figure 7.14 shows the example of the while loop.

<html>
<body>
<script type = “text/javascript”>
var i = 0;

while (i <= 5) {
[Link] (“The number is “ + i);

(Contd)
Fig. 7.14 contd...
[Link] (“<br>”);
i++;
}
</script>

<p><p>
<b>We have seen an example of the <i>while</i> loop</b>

</body>
</html>

Fig. 7.14 Example of while loop

Figure 7.15 shows the output of the whileexample.

Fig. 7.15 Output of while example

Figure 7.16 shows the example of the do-whileloop.

<html>
<body>
<script type=”text/javascript”>
i = 0;
do {
[Link] (“The number is “ + i);
[Link] (“<br>”);
i++;
}
while (i <= 5);
</script>

(Contd)
Fig. 7.16 contd...

<p><p>
<b>We have seen an example of the <i>do-while</i> loop</b>

</body>
</html>

Fig. 7.16 Example of do-while loop

Figure 7.17 shows the output of the do-whileexample.

Fig. 7.17 Output of the do-while example

Figure 7.18 shows the example of the for loop.

<html>
<body>
<script type=”text/javascript”>
for (i = 0; i <= 5; i++) {
[Link] (“The number is “ + i);
[Link] (“<br>”);
}
</script>
<p><p>
<b>We have seen an example of the <i>for</i> loop</b>
</body>
</html>

Fig. 7.18 Example of the for loop


Figure 7.19 shows the output of the forexample

Fig. 7.19 Output of the for example

Standard objects JavaScript provides several standard objects, such as Array,


Boolean, Date, Math, String, etc. We shall quickly review some of them.
Figure 7.20 shows the example of the Dateobject.

<html>
<body>
<script type=”text/javascript”>
var d = new Date ();
[Link] ([Link] ());
[Link] (“.”);
[Link] ([Link] () + 1);
[Link] (“.”);
[Link] ([Link] ());
</script>
</body>
</html>

Fig. 7.20 Date object example

In the code, we create a new instance of the Date object. From this object, we
get the day number, the month number (and increment by one, since it starts with
0), and the four-digit year; all concatenated with each other by using a dot symbol.
The output is shown in Fig. 7.21.
We can manipulate values of the Date object as well. For example, we can
display the current date and time in the full form, change the year value to a
value of our choice, and then display the full date and time again. This is shown
in Fig. 7.22.
Fig. 7.21 Output of the Date object

<html>
<body>
<script type=”text/javascript”>
var d = new Date ();
[Link] (d);
[Link] (“<br />”);
[Link] (“2100”);
[Link] (d);
</script>
</body>
</html>

Fig. 7.22 Manipulating dates

The resulting output is shown in Fig. 7.23.

Fig. 7.23 Output of the date manipulation example

Here is another example related to dates, as shown in Fig. 7.24. Here, we use
the Array default object as well.
<html>
<body>
<script type = “text/javascript”>
var d = new Date ();
var weekday = new Array (“Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”);
[Link] (“Today is “ + weekday [[Link] ()]);
</script>
</body>
</html>

Fig. 7.24 Use of Dateand Array objects

The resulting output is shown in Fig. 7.25.

Fig. 7.25 Output of the Date and Array objects

The same example is modified further, as shown in Fig. 7.26.

<html>
<body>
<script type=”text/javascript”>
var d = new Date ();
var weekday = new Array (“Sunday”, “Monday”, “Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”);
var monthname = new Array (“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”,
“Aug”, “Sep”, “Oct”, “Nov”, “Dec”);
[Link] (weekday [[Link] ()] + “ “);
[Link] (monthname [[Link] ()] + “ “);
[Link] ([Link] ());
</script>
</body>
</html>

Fig. 7.26 Another date example

The resulting output is shown in Fig. 7.27.


Fig. 7.27 Output of the modified example

Table 7.2 shows the most useful date functions.

Table 7.2 Date functions

Method Description
Date() Returns a Date object
getDate() Returns the date of a Date object (from 1–31)
Returns the day of a Date object (from 0–6, where 0 =
getDay()
Sunday, 1 = Monday, etc.)
getMonth()
Returns the month of a Date object (from 0–11, where 0 =
getFullYear() January, 1 = February, etc.)
getYear() Returns the year of a Date object (four digits)
getHours() Returns the year of a Date object
getMinutes() (from 0–99). Returns the hour of a
getSeconds() Date object (from 0–23) Returns the
minute of a Date object (from 0–59)
Returns the second of a Date object
(from 0–59)

Figure 7.28 shows an example of using the Mathobject.

<html>
<body>

<script type = “text/javascript”>


[Link] ([Link] (7.80))
</script>

</body>
</html>

Fig. 7.28 Math object example


The resulting output is shown in Fig. 7.29.

Fig. 7.29 Output of using the Math object

Table 7.3 lists the important methods of the Mathobject.

Table 7.3 Math functions

Method Description
abs (x) Returns the absolute value of x
cos (x) Returns the cosine of x
exp (x) Returns the value of E raised to the power of x
log (x) Returns the natural log of x
max (x, y) Returns the number with the highest value of x and y
min (x, y) Returns the number with the lowest value of x and y
pow (x, y) Returns the value of the number x raised to the power of y
random () Returns a random number between 0 and 1
Rounds x to the nearest integer
round (x)
Returns the sine of x
sin (x)
Returns the square root of x
sqrt (x)
Returns the tangent of x
tan (x)

JavaScript provides a few functions for handling strings. These are summarized
below.
□ indexOf (): Finds location of a specified set of characters (i.e., of a sub-
string). Starts counting at 0, returns starting position if found, else returns -
1.
□ lastIndexOf (): Similar to the above, but looks for the last occurrence of the
sub string.
□ charAt (): Returns a single character inside a string at a specific position.
□ subString (): Returns a sub string inside a string at a specific position.
□ split (): Divides a string into sub strings, based on a delimiter.
We shall discuss a few string processing examples when we
study form validations. Figure 7.30 shows a sample of the
indexOf ()function.
<html>
<head>
<title>Validate Email Address</title>
<script type = “text/javascript”>
function validateEmailAddress
(the_email_address) { var the_at_symbol =
the_email_address.indexOf (“@”);
var the_dot_symbol =
the_email_address.lastIndexOf (“.”);var
the_space_symbol = the_email_address.indexOf (“
“);

/////////////////////////////////////////////////////
// Now see if the email address is valid
/////////////////////////////////////////////////////if (
(the_at_symbol != -1) && // There must be an @ symbol
(the_at_symbol != 0) && // The @ symbol must not be at the first
position(the_dot_symbol != -1) && // There must be a . symbol
(the_dot_symbol != 0) && // The . symbol must not be at the first position
(the_dot_symbol > the_at_symbol + 1) && // Must have something after @
and before.(the_email_address.length > the_dot_symbol + 1) && // Must
have something after. (the_space_symbol == -1) // Must not have a space
anywhere
){
alert (“Email address seems to be correct.”);
return true;
}
else {
alert (“Error!!! Email address seems to be
incorrect.”);return false;
}
}
</script>
<head>
<body>
<h1>Please enter your email address below</h1>
<form name = “the_form” action = “” method = “post”
onSubmit = “var the_result = validateEmailAddress
(this.email_address.value);return the_result;”>
Email address:<input type = “text” name = “email_address”>
<input type = “submit” value = “Submit Form”>
</form>
</body>
</html>

Fig. 7.30 Example of indexOf ()

7.1.4 JaVaScript and Form Processing


JavaScript has a big role to play in the area of form processing. We know that
HTML forms are used for accepting user inputs. JavaScript helps in validating
these inputs and also to perform some processing on the basis of certain events.

Figure 7.31 shows a simple example of capturing the event of a button getting
clicked.

<html>
<head>
<script type=”text/javascript”>
function show_alert() {
alert(“Hello World!”)
}
</script>
</head>
<body>
<form>
<input type = “button” value = “Click me!” name=”myButton”
onClick = “show_alert ()” />
</form>
</body>
</html>

Fig. 7.31 Button click example

As we can see, we have a simple button on the screen. On clicking of this button,
we are calling a JavaScript function to display an alert box. The resulting output is
shown in Fig. 7.32.

Fig. 7.32 (a) Original screen, (b) Result when the button is clicked
Now let us take a look at a more useful example. Here, we accept two
numbers from the user and display a hyper link where the user can click to
compute their multiplication. When the user does so, we display the resulting
multiplication value inside an alert box. The code for this functionality is shown in
Fig. 7.33.

<html>
<head>
<title>Simple Multiplication</title>
<script type=”text/javascript”>
function multiply () {
var number_one = document.the_form.field_one.value;
var number_two = document.the_form.field_two.value;
var result = number_one * number_two;
alert (number_one + “ times “ + number_two + “ is: “ + result);
}
</script>
</head>
<body>
<form name = “the_form”>
Number 1: <input type = “text” name = “field_one”> <br>
Number 2: <input type = “text” name = “field_two”> <br>
<a href = “#” onClick = “multiply (); return false;”>Multiply them! </a>
</form>
</body>
</html>

Fig. 7.33 Using JavaScript to multiply two numbers

The resulting output is shown in Fig. 7.34.

Fig. 7.34 Multiplying two numbers

We will now modify the same example to display the resulting multiplication value
inside a third text box, instead of displaying it inside an alert box. The code for this
purpose is shown in Fig. 7.35.
<html>
<head>
<title>A Simple Calculator</title>
<script type=”text/javascript”>
function multiply () {
var number_one = document.the_form.field_one.value;
var number_two = document.the_form.field_two.value;
var result = number_one * number_two;
document.the_form.the_answer.value = result;
}
</script>
</head>
<body>
<form name = “the_form”>
Number 1: <input type = “text” name = “field_one”> <br>
Number 2: <input type = “text” name = “field_two”> <br>
The Product: <input type = “text” name = “the_answer”> <br>
<a href = “#” onClick = “multiply (); return false;”>Multiply them! </a>
</form>
</body>
</html>

Fig. 7.35 Displaying result of multiplication in a separate text box

Fig. 7.36 Displaying result of multiplication in a separate text box

Let us now take an example of using checkboxes. Figure 7.37(a) shows the
code, where we display three checkboxes. Depending on the number of selections,
the JavaScript just displays the score, assigning one mark per selection. The result
is shown in Fig. 7.37(b).
Note that JavaScript offers short hands for certain syntaxes. For example, every
time writing the complete [Link].the_form syntax is quite tedious.
However, a solution is available whereby the following two syntaxes are equivalent.
Fig. 7.37 Checkbox example, (b) Output

<form name = “my_form”


onSubmit = “[Link] = [Link].my_form.the_url.value;
returnfalse;”>
<form name = “my_form”
onSubmit = “[Link] = this.the_url.value; return false;”>As
we can see, the second syntax is quite handy.
Here is another example.
<form name = “my_form”>
<input type = “text” name = “age” onChange = “checkAge
([Link].my_form.[Link]);” />
</form>
<form name = “my_form”>
<input type = “text” name = “age” onChange = “checkAge ([Link]);” />
</form>
Inside onChange event, implicitly it is the current element, and hence, we can
directly say [Link], even without saying age!
In the following example (Fig. 7.38), we illustrate the usage of arrays and loops.
The functionality achieved is actually the same as what we had achieved in the
checkbox example shown earlier. But the code is quite compact here, as we can
see.
<html>
<head>
<title>Using Arrays</title>
<script type = “text/javascript”>
function computeScore () {
var index = 0, correct_answers = 0;
while (index < 3) {
if ([Link].the_form.elements[index].checked == true) {
correct_answers++;
}
index++;
}
alert (“You have scored “ + correct_answers + “ mark(s)!”);
}
</script>
</head>
<body>
<h1>An Interesting Quiz</h1>
<br><br>
Select the statements that are true:
<form name = “the_form”>
<input type = “checkbox” name = “question1”>I stay in Pune<br>
<input type = “checkbox” name = “question2”>I am a Student<br>
<input type = “checkbox” name = “question3”>I enjoy Programming in JavaScript<br>
<br><br>
<input type = “button” value = “Compute Marks” onClick = “computeScore();”>
</form>
</body>
</html>

Fig. 7.38 Usage of arrays and loops

The resulting output is not shown, as we have already had one look at it earlier.
Of course, we can also use either the do-whileor the for loop, instead. Figure
7.39 shows an example of the for loop.
<html>
<head>
<title>Rainbow!</title>
<script = “text/javascript”>
function rainbow () {
var rainbow_colours = new Array (“red”, “orange”, “yellow”, “green”,
“blue”, “violet”);

(Contd)
Fig. 7.39 contd...

var index = 0;
for (index = 0; index < rainbow_colours.length; index++) {
[Link] = rainbow_colours [index];
//[Link] (index);
}
}
</script>
</head>
<body>
<form>
<input type = “button” value = “Rainbow” onClick = “rainbow();”>
</form>
</body>
</html>

Fig. 7.39 Example of the for loop

Figure 7.40 shows an example of where we want to validate the contents of an


HTML form.

<html>
<head>
<title>Form Validation</title>
<script type = “text/javascript”>
function checkMandatoryFields () {
var error_Message = “”;
// Check text box
if ([Link].the_form.the_text.value == “”) {
error_Message += “Please enter your name.\n”;
}
// Check scrolling list
if ([Link].the_form.[Link] < 0) {
error_Message += “Please select a state.\n”;
}
// Check radio buttons
var radio_Selected = “false”;
for (var index = 0; index < [Link].the_form.[Link]; index++) {
if ([Link].the_form.gender[index].checked == true) {
radio_Selected = “true”;
}
}
if (radio_Selected == “false”) {
error_Message += “Please select a gender.\n”;
}
if (error_Message == “”) {

(Contd)
Fig. 7.40 contd...

return true;
}
else {
error_Message = “Please correct the following errors:\n\n” + error_Message;
alert (error_Message);
return false;
}
}
</script>
<head>

Fig. 7.4o Form validations—Part 1[2

<body bgColor = “lightblue”>


<h1>Please provide your details below</h1>
<form name = “the_form” action = “” method = “post” onSubmit = “var the_result =
checkMandatoryFields (); return the_result;”>
<table border = “2” bgColor = “yellow”>
<tr>
<td><b>Name:</b></td>
<td><input type = “text” name = “the_text”></td>
</tr>
<tr /><tr />
<tr>
<td><b>State:</b></td>
<td>
<select name = “state” size = “5”>
<option value = “andhra”>Andhra Pradesh</option>
<option value = “bihar”>Bihar</option>
<option value = “Karnataka”>Karnataka</option>
<option value = „goa“>Goa</option>
<option value = “maharashtra”>Maharashtra</option>
<option value = “mp”>Madhya Pradesh</option>
<option value = “rajasthan”>Rajasthan</option>
<option value = “up”>Uttar Pradesh</option>
</select>
</td>
</tr>
<tr /><tr />
<tr>
<td><b>Gender:</b></td>
<td>
<input type = “radio” name = “gender”>Female
<input type = “radio” name = “gender”>Male
</td>
</tr>
<tr /> <tr />

(Contd)
Fig. 7.40 contd...

<tr>
<td><input type = “submit” value = “Submit Form”></td>
</tr>
<tr /> <tr />
</table>
</form>
</body>
</html>

Fig. 7.4o Form validations—Part 2[2

Figure 7.41 shows a sample of the indexOf () string function. This example
attempts to accept an email address from the user in an HTML form and then
validates it. The particulars of the validation logic are mentioned inside the code
comments. So, we will not repeat them here.

<html>
<head>
<title>Validate Email Address</title>
<script type = “text/javascript”>
function validateEmailAddress
(the_email_address) { var the_at_symbol =
the_email_address.indexOf (“@”);
var the_dot_symbol =
the_email_address.lastIndexOf (“.”);var
the_space_symbol = the_email_address.indexOf (“
“);

/////////////////////////////////////////////////////
// Now see if the email address is valid
/////////////////////////////////////////////////////if (
(the_at_symbol != -1) && // There must be an @ symbol
(the_at_symbol != 0) && // The @ symbol must not be at the first
position(the_dot_symbol != -1) && // There must be a . symbol
(the_dot_symbol != 0) && // The . symbol must not be at the first position
(the_dot_symbol > the_at_symbol + 1) && // Must have something after @
and before.(the_email_address.length > the_dot_symbol + 1) && // Must
have something after. (the_space_symbol == -1) // Must not have a space
anywhere
){
alert (“Email address seems to be correct.”);
return true;
}
else {
alert (“Error!!! Email address seems to be
incorrect.”);return false;
}
}
</script>
<head>
(Contd)

Fig. 7.41 contd...

<body>
<h1>Please enter your email address below</h1>
<form name = “the_form” action = “” method = “post”
onSubmit = “var the_result = validateEmailAddress (this.email_address.value);
return the_result;”>
Email address:<input type = “text” name = “email_address”>
<input type = “submit” value = “Submit Form”>
</form>
</body>
</html>

Fig. 7.41 Using the indexOf ()string function

We can write the same logic using another string function, namely charAt ().
The resulting code is shown in Fig. 7.42.

<html>
<head>
<title>Validate Email Address - charAt Version</title>
<script type = “text/javascript”>
function validateEmailAddress
(the_email_address) { var the_at_symbol =
the_email_address.indexOf (“@”);
var the_dot_symbol =
the_email_address.lastIndexOf (“.”);var
the_space_symbol = the_email_address.indexOf (“
“); var is_invalid = false;

/////////////////////////////////////////////////////
// Now see if the email address is valid
/////////////////////////////////////////////////////if (
(the_at_symbol != -1) && // There must be an @ symbol
(the_at_symbol != 0) && // The @ symbol must not be at the first
position(the_dot_symbol != -1) && // There must be a . symbol
(the_dot_symbol != 0) && // The . symbol must not be at the first position
(the_dot_symbol > the_at_symbol + 1) && // Must have something after @
and before.(the_email_address.length > the_dot_symbol + 1) && // Must
have something after. (the_space_symbol == -1) // Must not have a space
anywhere
){
is_invalid = false; // do nothing
}
else {
is_invalid = true;
}
if (is_invalid == true) {
alert (“Error!!! Email address is invalid.”);

(Contd)
Fig. 7.42 contd...

return false;
}

/////////////////////////////////////////////////////
// Now check for the presence of illegal characters
/////////////////////////////////////////////////////

var the_invalid_characters = “!#$%^&*()+=:;?/<>”;


var the_char = “”;

Fig. 7.42 Using the charAt () function—Part 1

for (var index = 0; index < the_invalid_characters.length; index++) {


the_char = the_invalid_characters.charAt (index);
if (the_email_address.indexOf (the_char) != -1) {
is_invalid = true;
}
}
if (is_invalid == true) {
alert (“Error!!! Email address is invalid.”);
return false;
}
else {
alert (“Email address seems to be valid.”);
return true;
}
}
</script>
<head>
<body>
<h1>Please enter your email address below</h1>
<form name = “the_form” action = “” method = “post”
onSubmit = “var the_result = validateEmailAddress (this.email_address.value);
return the_result;”>
Email address:<input type = “text” name = “email_address”>
<input type = “submit” value = “Submit Form”>
</form>
</body>
</html>

Fig. 7.42 Using the charAt ()function—Part 2

Another string function, substring () is a bit tricky. The general syntax for this
function is substring (from, until). This means return a string starting with from and
ending with one character less than until. That is, until is at a position that is
greater than the last position of the substring by one. As a result, some of the
tricky examples shown in Table 7.4 need to be observed carefully.
Table 7.4 Examples of the substring () function

Example Result Explanation


the_word.substring (0, 4) “Java” from = 0, until = 4–1 = 3. So, returns characters
at positions 0, 1, 2, and 3.
the_word.substring (1, 4) “ava” from = 1, until = 4–1 = 3. So, returns characters
at positions 1, 2, and 3.
the_word.substring (1, 2) “a”
from = 1, until = 2–1 = 1. So, returns character
“” at position 1 only.
the_word.substring (2, 2)
from = 2, until = 2–1 = 1. So, returns an empty
string.

7.2 AJAX

7.2.1 Introduction
The term AJAX is used quite extensively in Information Technology these days.
Everyone seems to want to make use of AJAX, but a few may not know where
exactly it fits in, and what it can do. In a nutshell:
AJAX can be used for making user experience better by using clever
techniques for communication between a Web browser (the client) and the Web
server.
How can AJAX do this? Let us understand this at a conceptual level.
In traditional Web programming, we have programs that execute either on the
client (e.g., written using JavaScript) or on the server (e.g., written using Java’s
Servlets/JSP, Microsoft’s [Link], or other technologies, such as PHP, Struts,
etc.). This is shown in Fig. 7.43.

Fig. 7.43 Technologies and their location

What do these programs do? They perform a variety of tasks. For example:
□ Validate that the amount that the user has entered on the screen is not over
10,000
□ Ensure that user’s age is numeric and is over 18
□ If city is entered as Pune, then country must be India
Mind you, these are simple examples of validating user inputs. They are best
done on the client-side itself, using JavaScript. However, all tasks are not
validations of these kinds alone. For example:

□ From the source account number specified by the user, transfer the amount
mentioned by the user into the target account number specified by the user
□ Produce a report of all transactions that have failed in the last four hours
with an appropriate reason code
□ Due to 1% increase in the interest rates, increase the EMI amount for all
the customers who have availed floating loans
These are examples of business processes. These are best run on the
server-side, using the technologies listed earlier.
We can summarize as follows.
Client-side technologies, such as JavaScript, are used for validating user
inputs. Server-side technologies, such as Java Servlets, JSP, [Link], PHP,
etc., are used for ensuring that business processes happen as expected.
Sometimes, we run into situations where we need a mixture of the two. For
instance, suppose that there is a text box on the screen, where the user needs to
type the city name. As the user starts typing the city name, we want to
automatically populate a list of all city names that match what the user has started
typing. (For example, when the user types M, then we want to show Madrid, Manila,
Mumbai, and so on). The user may select one of these, or may type the next
character, say a. If the user has typed the second character as a, the user’s input
would now have become Ma. Now, we want to show only Madrid and Manila, but
not Mumbai (which has the first two characters as Mu). We may perhaps even
show a warning to the user, in case the user is typing the name of a city, which
does not exist at all!
The best example of this is Google Suggest
([Link] You can visit this URL and
try what we have shown below. Suppose that we are trying to search for the word
i-flex.
In the search window, type i. We would get a list of all the matching entries,
starting with ifrom Google’s database, as shown in Fig. 7.44.
Now add a hyphen to get the following screen. As we can see, the list is now
filtered for entries starting with i-. The result is shown in Fig. 7.45.
Now add an f to make it i-f. This is shown
in Fig. 7.46. We get what we want!
This process has used AJAX.
We can use AJAX in similar situations, where we want to capture the matter the
user is typing or has typed, and process it while the user continues to do whatever
she is doing.
Of course, this is just one of the uses of AJAX. It can be used in any situation,
where we want the client to send a request to the server for taking some action,
without the user having to abandon her current task. Thus, AJAX helps us to do
something behind the scenes, without impacting the user’s work.
AJAX stand for Asynchronous JavaScript And XML, as explained below.
□ Asynchronous because it does not disturb the user’s work, and does not
refresh the full screen (unlike what happens when the user submits a form
to the server, for example).
□ SavaScript because it uses JavaScript for the actual work.
□ And XML because XML is supposed to be everywhere today (using AJAX,
the server can return XML to the browser).

Fig. 7.44 Google Suggest—1


Fig. 7.45 Google Suggest—2

Fig. 7.46 Google Suggest—3

7.2.2 How does AJAX Work?


AJAX uses the following techniques, described in a generic fashion.
Whenever AJAX needs to come into the picture, based on the user action (e.g.,
when something is typed), it sends a request from the Web browser to the Web
server.
On the Web server, a program written in a server-side technology (any one
from those listed earlier) receives this request from the Web browser, sent by
AJAX.
The program on the Web server processes this request, and sends a
response back to the Web browser. Note that while this happens, the user does
not have to wait—actually, the user does not even notice that the Web browser
has sent a request to the Web server!
The Web browser processes the response received from the Web server, and
takes an appropriate action (e.g., in Google Suggest, the browser would show us
a list of all the matching entries for the text typed so far, which was sent by the
Google server to the browser in step 3 above).
This concept is shown in
Fig. 7.47. Let us
understand how this
works.
1. While the user (client) is filling up an HTML form, based on a certain event,
JavaScript in the client’s browser prepares and sends an AJAX request
(usually called as an XMLHttpRequest) to the Web server.
2. While the user continues working as if nothing has happened (shown with
two processing arrows at the bottom part of the diagram), the Web server
invokes the appropriate server-side code (e.g., a JSP/Servlet, an [Link]
page, a PHP script, as we shall learn later).
Fig. 7.47 The AJAX process

3. The server-side code prepares an AJAX response and hands it over to the
Web server.
4. While the user continues working with the remainder of the HTML form, the
server sends the AJAX response back to the browser. The browser
automatically reflects the result of the AJAX response (e.g., populate a
field on the HTML form). Note that the user would not even notice that
steps 1 to 3 have happened behind the scene!
Therefore, we can differentiate between non-AJAX based processing and
AJAX based processing as shown in Fig. 7.48 and Fig. 7.49.

Fig. 7.48 Traditional HTTP processing (without AJAX)

Fig. 7.49 AJAX based processing


7.2.3 AJAX FAQ
In the beginning, people have a lot of questions regarding AJAX. We summarize them
along with their answers below.
1. Do we not use the request/response model in AJAX?
□ We do, but the approach is different now. We do not submit a form now, but
instead send requests using JavaScript.
2. Why not submit the form? Why do we prefer to use AJAX?
□ AJAX processing is asynchronous. Client does not wait for server to respond.
When server responds, JavaScript does not refresh the whole page.
3. How does a page get back a response, then?
□ When the server sends a response, JavaScript can update a page with new
values, change an image, or transfer control to a new page. The user does
not have to wait while this happens.
4. Should we use AJAX for all our requests?
□ No. Traditional form filling is still required in many situations. But for
immediate and intermediate responses/feedbacks, we should use AJAX.
5. Where is the XML in AJAX?
□ Sometimes the JavaScript can use XML to speak with the server back and
forth.

7.2.4 Life without AJAX


Suppose that we have a book shop, where we want to constantly view the amount
of profit we have made. For this purpose, an application sends us the latest number
of copies sold, as on that date. We multiply that with the profit per copy, and
compute the total profit made. We shall get into coding details subsequently.
The conceptual view of this is shown in Fig. 7.50.

Fig. 7.5o AJAX case study—1


The way this executes is shown step by step below.
Step f User clicks on the button shown in the HTML form. As a result, the
request would go to the Web server. This is shown in Fig. 7.51.

Fig. 7.51 AJAX case study—2

Step 2 The server-side program (may be a JSP) processes the user’s request,
and sends back an HTTP response to the user. This response refreshes or
reloads the screen completely. This is shown in Fig. 7.52.

Fig. 7.52 AJAX case study—3


At this stage, let us reinforce our AJAX ideas.
AJAX has Ability to fetch data from the server without having to refresh a page.
Applications without ASAX
□ Normal Web applications communicate with the server by referring to a new
URL
□ Example: When a form is submitted, it is processed by a server-side
program, which gets invoked
ASAX applications
□ Use an object called as XMLHttpRequest object built into the browser, using
JavaScript to communicate with the server
□ HTML form is not needed to communicate with the server
What is this XMLHttpRequest object all about? It is an alternative for HTML
forms. It is used to communicate with the server side code, from inside a browser.
The server side code now returns text or XML data, not the complete HTML Web
page. The programmer has to extract data received from the server via the
XMLHttpRequest object, according to the need.

7.2.5 AJAX Coding


Figure 7.53 outlines the way we can write code for AJAX-based applications.

Fig. 7.53 AJAX processing steps

Let us now discuss these steps in detail.


(f) Greate the XMLHttpRequest object
Two main browsers are required to be handled: Internet Explorer and Others.
Code for non Internet Explorer browsers
var XMLHttpRequestObject = false;
if ([Link]) { // Non-IE browser
XMLHttpRequestObject = new XMLHttpRequest ();
}
Code for Internet Explorer
else if ([Link]) { // IE browser
XMLHttpRequestObject = new ActiveXObject
(“[Link]”);
}
We can write a complete HTML page to ensure that our browser was able
to successfully create the XMLHttpRequest object, as shown in Fig. 7.54.

<html>
<head>
<title>AJAX Example</title>
<script language = “javascript”>
var XMLHttpRequestObject = false;
if ([Link]) {
XMLHttpRequestObject = new XMLHttpRequest ();
}
else if ([Link]) {
XMLHttpRequestObject = new ActiveXObject (“[Link]”);
}
if (XMLHttpRequestObject) {
[Link] (“<h1>Welcome to AJAX</h1>”);
}
</script>
</head>
<body>
</body>
</html>

Fig. 7.54 Checking for the presence of the XMLHttpRequest object


This code does not do anything meaningful, except for checking that the
browser is AJAX enabled. Of course, by this we simply mean that the browser is
able to create and deal with the XMLHttpRequest object, as needed by the AJAX
technology. If it is able to do so (which is what should happen for all modern
browsers), we will see the output as shown in Fig. 7.55.
(2) Tell the XMLHttpRequest object as to where to send the request
We need to open the XMLHttpRequest object now by calling its open method. It
expects two parameters, the type of the method (GET/POST), and the URL where
the asynchronous AJAX request is to be sent. An example is shown below.
[Link] (“GET”, “[Link]”);

Here, we are saying that we want to send a GET request to fetch a file named
[Link].

Fig. 7.55 Output of the earlier HTML page

(3) Tell the XMLHttpRequest object what to do when the request is answered
We can download data from the server using the XMLHttpRequest object. This
process happens behind the scenes, i.e., in an asynchronous manner. When data
comes from the server, the following two things happen.
(i) The readyState property of the HTTPRequestObject changes to one of the
following possible values: 0 – Uninitialized, 1 – Loading, 2 – Loaded, 3 –
Interactive, 4 – Complete
(ii) The status property holds the results of the
HTTP download 200 – OK, 404 – Not found,
etc
Thus, we can check this status as follows.
if (([Link] == 4) &&
([Link] == 200)) {

}
(4) Tell the XMLHttpRequest object make a request
In this step, we download the data received from the server and use it in our
application, as desired.

7.2.6 Life with AJAX


Let us now continue our earlier example to understand how AJAX enabling makes it
so much more effective.
Our code would have the following JavaScript functions:
□ getBooksSold ()—This function would create a new object to talk to the
server.
□ updatePage ()—This function would ask the server for the latest book sales
figures.
□ createRequest ()—This function would set the number of books sold
and profit made. Let us write the HTML part first. The code is shown in
Fig. 7.56.

<html>
<head>
<title>Sales Report</title>
<link rel=”stylesheet” type=”text/css” href=”[Link]” />
</head>
<body>
<h1>Sales Report for our Books</h1>
<div id=”Books”>
<table>
<tr><th>Books Sold</th>
<td><span id=”books-sold”>555</span></td></tr>
<tr><th>Sell Price</th>
<td>Rs. <span id=”price”>300</span></td></tr>
<tr><th>Buying Cost</th>
<td>Rs. <span id=”cost”>250</span></td></tr>
</table>
<h2>Profit Made: Rs. <span id=”cash”>27750</span></h2>
<form method=”GET” action=”[Link]”>
<input value=”Show me the latest profit” type=”button” />
</form>
</div>
</body>
</html>

Fig. 7.56 HTML code for AJAX-enabled page—Initial version

The resulting screen is shown in Fig. 7.57.

Fig. 7.57 Result of our HTML code


We now want to add JavaScript so that at the click of the button, the function
getBooksSold ()will get called. This is shown in Fig. 7.58.

Fig. 7.58 Adding JavaScript

The getBooksSold () function


What should the getBooksSold ()function do? We can summarize:
□ Create a new request by calling the createRequest () function

□ Specify the URL to receive the updates from

□ Set up the request object to make a connection

□ Request an updated number of

books sold Here is the outline of the


JavaScript code so far.
<script language=“javascript” type=“text/javascript”>
function createRequest ()
// JavaScript code
function getBooksSold () {
createRequest ();
}
</script>
Now, let us think about the contents of the createRequest
()function. The createRequest ()function
This function would simply create an instance of the XMLHttpRequest object, as
per the browser type:
function createRequest () {
if ([Link]) {
XMLHttpRequestObject = new
XMLHttpRequest ();
}
else
if ([Link]) {
XMLHttpRequestObject = new ActiveXObject (“[Link]”);
}
}
Now let us modify the getBooksSold ()function suitably, as follows:
function getBooksSold () {
createRequest ();
var url = “[Link]”;
[Link] (“GET”, url);
}

This would call [Link]. We want to process the response sent
by this JSP now.
function getBooksSold () {
createRequest ();
var url = “[Link]”;
[Link] (“GET”, url);
[Link] = updatePage;
[Link] (null);

}
Here, updatePage () is a function that will get called when the JSP on the
server side has responded to our XMLHttpRequest. What should this function
have? Let us see. First, it should receive the value sent by the JSP.
function updatePage () {
var newTotal = [Link];
Note that normally, the server-side JSP would have returned a full HTML page.
But now the JSP is dealing with an AJAX request (i.e., XMLHttpRequest object).
Hence, the JSP does not send a full HTML page. Instead, it simply returns a
number in which the updatePage () function is interested. This number is stored
inside a JavaScript variable called as newTotal.
Now, we want to also read the current values of the HTML form variables books-
soldand cash. Hence, we amend the above function further.
function updatePage () {
var newTotal = [Link];
var booksSoldElement = [Link] (“books-
sold”);var cashElement = [Link] (“cash”);
Now, we want to replace the current value of the books sold element with the
on received from the server now. Hence, we add one more line to the code.
function updatePage () {
var newTotal = [Link];

var booksSoldElement = [Link] (“books-sold”);


var cashElement = [Link] (“cash”);
replaceText (booksSoldElement, newTotal);
}

This would refreshonly the tag of interest, which is the booksSoldElement, which,
in turn, means the
books-soldHTML form variable.
What should the JSP do? It is expected to simply return the latest number of
books sold at this juncture.
Hence, it has a single line:
[Link] (300)

You might also like