HTML Basics: Structure and Tags
HTML Basics: Structure and Tags
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
• 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>
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 -->
</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>
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>
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>
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>
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>
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:
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>
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>
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>
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>
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>
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>
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>
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
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>
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:
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
<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>
<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>
<!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>
<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.
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>
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>
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>
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
//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>
<!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>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>
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>
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>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>
<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
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
<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
<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>
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>
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
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.
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).
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;">
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.
Example
<img src="[Link] alt="
[Link]">
Animated Images
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>
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):
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.
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:
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.
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 Areas
Shape
Page 5 of 28
You must define the shape of the clickable area, and you can choose one
of these values:
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>
<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
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>
<map name="workmap">
<area shape="circle" coords="337,300,44" alt="Cup of coffee"
href="[Link]">
</map>
</body>
</html>
Shape="poly"
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>
<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>
Following is the list of important attributes which can be used with <embed>
tag.
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).
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.
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 −
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
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
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.
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.
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.
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.
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.
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
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
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 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
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.
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
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 −
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
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
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 −
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 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 saves a lot of work. It can control the layout of multiple web pages all at once.
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>
</body>
</html>
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>
<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.
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.
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>
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>
[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><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
Text 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.
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 carries the data, does not present it: XML allows you to store the
datairrespective of how it will be presented.
• 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 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.
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>
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.
XMLDeclaration
The XML document can optionally have an XML declaration. It is written as follows:
Where version is the XML version and encoding specifies the character encoding
used inthe 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.
<element>
<element/>
<?xml version="1.0"?>
<contact-info>
<company>TutorialsPoint
<contact-info>
</company>
<?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>
<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]
• Same attribute cannot have two values in a syntax. The following example
showsincorrect syntax because the attribute b is specified twice:
• Attribute names are defined without quotation marks, whereas attribute values
must always appear in quotation marks. Following example demonstrates
incorrectxml syntax:
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, & where amp is name. The name refers
to a predefined string of text and/or markup.
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:
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>
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 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:
<?xml >
<?xml version="1.0">
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
<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>
<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:
• 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.
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.
Properties of DOM: Let’s see the properties of the document object that can be accessed and modified
by the document object.
• 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.
<!DOCTYPE html>
<html>
<body>
<h2>GeeksforGeeks</h2>
Output:
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>
<!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:
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.
<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:
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.
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.
To make our life simpler, various vendors have come up with very nice JavaScript
editing tools. Some of them are listed here:
The specification for JavaScript 2.0 can be found on the following site:
[Link]
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>
• 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.
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>
Hello World!
But when formatted in a single line as follows, you must 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.
Example
The following example shows how to use comments in JavaScript.
/*
* 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.
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.
• There you will find the option to enable or disable javascript by right-clicking
on the value of that option -> select toggle.
• Click the Chrome menu at the top right hand corner of your browser.
• Select Settings.
• 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:
To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.
You can add a noscript block immediately after the script block as follows:
<html>
<body>
<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
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.
<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>
Say Hello
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
[Link]("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
Hello World
This is web page body
<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>
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 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>
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>
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.
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
• Assignment Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators:
+ (Addition)
- (Subtraction)
/ (Division)
% (Modulus)
++ (Increment)
-- (Decrement)
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>
Output
a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
a++ = 33
b-- = 10
== (Equal)
Checks if the value of two operands are equal or not, if yes, then
1
the condition becomes 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.
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.
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.
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.
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 />";
//-->
</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:
1 If both the operands are non-zero, then the condition becomes 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.
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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:
Ex: (A & B) is 2.
| (BitWise OR)
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.
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.
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.
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 />";
//-->
</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:
= (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
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
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
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
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
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 />";
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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.
? : (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 />";
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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.
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 />";
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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.
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 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
Window Object
The Window object is the top level object in the JavaScript hierarchy.
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.
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.
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.
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.
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
<html>
<body>
<script type=”text/javascript”>
[Link] (“Hello World!”);
</script>
</body>
</html>
<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
<html>
<head>
</head>
<body>
<script src=”[Link]”></script>
</body>
</html>
Operators
JavaScript supports a variety of operators. Table 7.1 summarizes them.
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.
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>
The resulting output is shown in Fig. 7.9, assuming that currently it is the
afternoon.
<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...
<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>
<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>
<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>
<html>
<body>
<script type=”text/javascript”>
var d = new Date ();
[Link] ([Link] ());
[Link] (“.”);
[Link] ([Link] () + 1);
[Link] (“.”);
[Link] ([Link] ());
</script>
</body>
</html>
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>
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>
<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>
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)
<html>
<body>
</body>
</html>
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>
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>
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>
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>
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
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>
<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>
(Contd)
Fig. 7.40 contd...
<tr>
<td><input type = “submit” value = “Submit Form”></td>
</tr>
<tr /> <tr />
</table>
</form>
</body>
</html>
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)
<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>
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
/////////////////////////////////////////////////////
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
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.
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).
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.
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.
<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>
Here, we are saying that we want to send a GET request to fetch a file named
[Link].
(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.
<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>
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)