0% found this document useful (0 votes)
3 views87 pages

Web&PHP_Module 1&2

Php

Uploaded by

mahisd8113
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views87 pages

Web&PHP_Module 1&2

Php

Uploaded by

mahisd8113
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Web UIT Thiruvananthapuram

Module I
HTML
Introduction to Internet
Computers and their structures are tough to approach, and it is made even extra tough while
you want to recognize phrases associated with the difficulty this is already utilized in regular
English, Network, and the net will appear to be absolutely wonderful from one some other,
however, they may seem like identical.
A network is a group of two or more computer systems (Multiple gadgets, additionally called
hosts), which are related through a couple of channels for the motive of sending and
receiving data (records/media) in a shared environment. The community also can consist of
serval gadgets/mediums that resource communique among or extra machines; those
gadgets are called Network devices and consist of routers, switches, hubs, and bridges,
amongst others.
Internet is a group of computer systems connected from all around the world. The Internet
protocol suite is a framework defined through the Internet standards. Methods are divided
right into a layered set of protocols on this architecture. The Internet gives a huge variety of
statistics and communique offerings, which includes forums, databases, email, and
hypertext. It is made of the neighborhood to global personal, public networks connected
through plenty of digital, wireless, and networking technologies.
The Internet is a worldwide interconnected network of hundreds of thousands of computers
of various types that belong to multiple networks.
Working of the internet: The internet is a global computer network that connects various
devices and sends a lot of information and media. It uses an Internet Protocol (IP) and
Transport Control Protocol (TCP)-based packet routing network. TCP and IP work together
to ensure that data transmission across the internet is consistent and reliable, regardless of
the device or location. Data is delivered across the internet in the form of messages and
packets. A message is a piece of data delivered over the internet, but before it is sent, it is
broken down into smaller pieces known as packets.
IP is a set of rules that control how data is transmitted from one computer to another via the
internet. The IP system receives further instructions on how the data should be transferred
using a numerical address (IP Address). The TCP is used with IP to ensure that data is
transferred in a secure and reliable manner. This ensures that no packets are lost, that
packets are reassembled in the correct order, and that there is no delay that degrades data
quality.
History of Internet
Talking about the history of internet, the ARPANET (Advanced Research Projects Agency
Network, later renamed the internet) established a successful link between the University of
California Los Angeles and the Stanford Research Institute on October 29, 1969. Libraries
automate and network catalogs outside of ARPANET in the late 1960s.
TCP/IP (Transmission Control Protocol and Internet Protocol) is established in the 1970s,
allowing internet technology to mature. The development of these protocols aided in the
standardization of how data was sent and received via the internet. NSFNET (National
Science Foundation Network), the 56 Kbps backbone of the internet, was financed by the
National Science Foundation in 1986. Because government monies were being used to
administer and maintain it, there were commercial restrictions in place at the time.
In the year 1991, a user-friendly internet interface was developed. Delphi was the first
national commercial online service to offer internet connectivity in July 1992. Later in May
1995, All restrictions on commercial usage of the internet are lifted. As a result, the internet
has been able to diversify and grow swiftly. Wi-Fi was first introduced in 1997. The year is
1998, and Windows 98 is released. Smartphone use is widespread in 2007. The 4G network
is launched in 2009. The internet is used by 3 billion people nowadays. By 2030, there are
expected to be 7.5 billion internet users and 500 billion devices linked to the internet.

1
Web UIT Thiruvananthapuram

Uses of the Internet:


 E-mail: E-mail is an electronic message sent across a network from one computer user
to one or more recipients. It refers to the internet services in which messages are sent
from and received by servers.
 Web Chat: Web chat is an application that allows you to send and receive messages in
real-time with others. By using Internet chat software, the user can log on to specific
websites and talk with a variety of other users online. Chat software is interactive
software that allows users to enter comments in one window and receive responses from
others who are using the same software in another window.
 World Wide Web: The World Wide Web is the Internet’s most popular information
exchange service. It provides users with access to a large number of documents that are
linked together using hypertext or hyperlinks.
 E-commerce: E-commerce refers to electronic business transactions made over the
Internet. It encompasses a wide range of product and service-related online business
activities.
 Internet telephony: The technique that converts analog speech impulses into digital
signals and routes them through packet-switched networks of the internet is known as
internet telephony.
 Video conferencing: The term “video conferencing” refers to the use of voice and
images to communicate amongst users.
Web Client
The client (or user) side of the Internet. The Web browser on the user’s computer or mobile
device is referred to as a Web client. It could also apply to browser extensions and helper
software that improve the browser’s ability to support specific site services.
Web browser
A web browser is a software program software that searches for, retrieves, and
presentations material which includes Web pages, photos, videos, and different files. The
browser sends a request to the Webserver, which then transmits the statistics returned to
the browser, which presentations the findings at the laptop. Example – Mozilla Firefox,
Microsoft Edge, Google Chrome, Safari etc.
Webpage
An internet web page (additionally called a web page) is a report that may be regarded in
an internet browser at the World Wide Web. HTML (HyperText Markup Language) and CSS
(Cascading Style Sheet) are used to generate the primary shape of an internet web page.
An internet web page is generally a segment of an internet site that carries statistics in plenty
of formats, which includes textual content inside the shape of paragraphs, lists, tables, and
so on.
The home web page is the beginning or first web page of an internet site. It gives trendy
statistics and connections to all the internet pages which are associated. Every internet web
page has its personal deal with. This may be visible withinside the deal with the bar. As a
result, if we need to get admission to a selected internet web page, the deal needs to be
placed inside the browser’s deal with bar.
Website
An internet site, in trendy, is a group of statistics approximately statistics prepared into many
internet pages. An internet site is probably made for a sure motive, subject matter, or to
provide a service. An internet site (abbreviated as “website” or “site”) is a group of online
pages connected collectively through links and saved on an internet server. By clicking on
links, a tourist can pass from one web page to the next. An internet site’s pages also are
connected below one area call and proportion a not unusual place subject matter and
template.
Search Engine

2
Web UIT Thiruvananthapuram

Search engines are websites that search on the internet on behalf of users and show a listing
of results. More than actually written may be discovered on seek engines. You can be
capable of looking for different online content material which includes photographs, video
content material, books, and news, in addition to gadgets and offerings, relying on the seek
engine you are the use of.
To make use of the Internet, you do not always want to recognize the deal with an internet
site. It is crucial to recognize the way to do a look for statistics. Using a seek engine is one
of the only methods to seek. A seek engine can help you in finding what you are looking for.
You also can appearance up net maps and instructions to help you to plot your adventure
from one factor to some other. Example: Google, Bing, DuckDuckGo, yahoo, etc.
Web 1.0: The Beginning of the Internet
Web 1.0, which emerged with the invention of the Internet, featured static web pages that
could only be viewed. These early websites were essentially digital brochures, with limited
interactivity and no ability for users to contribute content. This era saw the rise of early
browsers such as Mosaic and Netscape Navigator, which made it easier for users to access
the Web.
Web 2.0: The Era of Social Media and User-Generated Content
Web 2.0, which emerged during the “Internet Boom” era of the late 1990s and early 2000s,
introduced more dynamic web pages and websites, and allowed for user-generated content.
This era saw the rise of social media platforms such as Facebook, Twitter, and YouTube,
as well as the introduction of blogs, wikis, and other forms of user-generated content.
Web 3.0: The Future of the Internet
Web 3.0, which is still in development, promises to bring a more personalized and intuitive
experience for users. It is expected to be more intelligent and able to understand the context
and intent of the user’s actions. This will be achieved through the integration of Artificial
Intelligence (AI) and Machine Learning (ML) technologies.
Many experts in the tech industry claimed that Web 3.0 is the next evolution of the internet
that is focused on decentralization, intelligence, and security. It aims to create a more
personalized, intuitive, and inclusive experience for users by leveraging new technologies
such as blockchain and artificial intelligence. The goal of Web 3.0 is to make the internet
more democratic, open-source, and secure.
Differentiation between Network and Internet
The number one distinction between a network and the internet is that a network is made of
computer systems that are bodily related and may be used as a personal laptop at the same
time as additionally sharing records. The Internet, on the alternative hand, might be an era
that connects those small and massive networks and creates a brand new in -intensity
community.
Advantages of the Internet:
 It is the best source of a wide range of information. There is no better place to conduct
research than the internet.
 Online gaming, talking, browsing, music, movies, dramas, and TV series are quickly
becoming the most popular ways to pass the time.
 Because there are hundreds of thousands of newsgroups and services that keep you
updated with every tick of the clock, the Internet is a source of the most recent news.
 Because of virtual shops where you may buy anything you want and need without leaving
your house, internet shopping is becoming increasingly popular. Recently, virtual shops
have been making a lot of money.
 With the emergence of online businesses, virtual stores, and credit card usage,
purchasing goods without going to the store has never been easier.
Disadvantages of the Internet:

3
Web UIT Thiruvananthapuram

 Spending too much time on the internet is hazardous for the young generation’s physical
and mental health.
 Children who use the internet develop an addiction, which is quite dangerous.
 It is now quite easy to decipher someone’s chat or email messages thanks to the hacking
community.
 With the emergence of online stores, people prefer to order online rather than going to
local stores which results in less social interactions among people.

HTML
HTML stands for Hypertext Markup Language, and it is the most widely used language to
write Web Pages.
 Hypertext refers to the way in which Web pages (HTML documents) are linked
together. Thus, the link available on a webpage is called Hypertext.
 As its name suggests, HTML is a Markup Language which means you use HTML to
simply "mark-up" a text document with tags that tell a Web browser how to structure it
to display.
Originally, HTML was developed with the intent of defining the structure of documents like
headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information
between researchers.
Now, HTML is being widely used to format web pages with the help of different tags available
in HTML language.

Basic HTML Document

In its simplest form, following is an example of an HTML document −

<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document content goes here.....</p>
</body>
</html>

HTML Tags

HTML is a markup language and makes use of various tags to format the content. These tags
are enclosed within angle braces <Tag Name>. Except few tags, most of the tags have their
corresponding closing tags. For example, <html> has its closing tag </html> and <body> tag
has its closing tag </body> tag etc.
Above example of HTML document uses the following tags −

Sr.No Tag & Description

1 <!DOCTYPE...>
This tag defines the document type and HTML version.

4
Web UIT Thiruvananthapuram

2 <html>
This tag encloses the complete HTML document and mainly comprises of
document header which is represented by <head>...</head> and document body
which is represented by <body>...</body> tags.

3 <head>
This tag represents the document's header which can keep other HTML tags like
<title>, <link> etc.

4 <title>
The <title> tag is used inside the <head> tag to mention the document title.

5 <body>
This tag represents the document's body which keeps other HTML tags like <h1>,
<div>, <p> etc.

6 <h1>
This tag represents the heading.

7 <p>
This tag represents a paragraph.

To learn HTML, you will need to study various tags and understand how they behave, while
formatting a textual document. Learning HTML is simple as users have to learn the usage of
different tags in order to format the text or images to make a beautiful webpage.
World Wide Web Consortium (W3C) recommends to use lowercase tags starting from HTML
4.

HTML Document Structure

A typical HTML document will have the following structure −

<html>
<head>
Document header related tags
</head>
<body>
Document body related tags
</body>
</html>

The <!DOCTYPE> Declaration

The <!DOCTYPE> declaration tag is used by the web browser to understand the version of
the HTML used in the document. Current version of HTML is 5 and it makes use of the
following declaration −

5
Web UIT Thiruvananthapuram

<!DOCTYPE html>
There are many other declaration types which can be used in HTML document depending on
what version of HTML is being used. We will see more details on this while discussing
<!DOCTYPE...> tag along with other HTML tags.
HTML Tags

HTML tags are like keywords which defines that how web browser will format and display the
content. With the help of tags, a web browser can distinguish between an HTML content and
a simple content. HTML tags contain three main parts: opening tag, content and closing tag.
But some HTML tags are unclosed tags.

When a web browser reads an HTML document, browser reads it from top to bottom and left
to right. HTML tags are used to create HTML documents and render their properties. Each
HTML tags have different properties.

An HTML file must have some essential tags so that web browser can differentiate between a
simple text and HTML text. You can use as many tags you want as per your code requirement.

o All HTML tags must enclosed within <> these brackets.


o Every tag in HTML perform different tasks.
o If you have used an open tag <tag>, then you must use a close tag </tag> (except
some tags)

Syntax

<tag> content </tag>Unclosed HTML Tags

Some HTML tags are not closed, for example br and hr.

<br> Tag: br stands for break line, it breaks the line of the code.

<hr> Tag: hr stands for Horizontal Rule. This tag is used to put a line across the webpage.

HTML Meta Tags

DOCTYPE, title, link, meta and style

HTML Text Tags

<p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <strong>, <em>, <abbr>, <acronym>, <address>,
<bdo>, <blockquote>, <cite>, <q>, <code>, <ins>, <del>, <dfn>, <kbd>, <pre>, <samp>,
<var> and <br>

HTML Link Tags

<a> and <base>

HTML Image and Object Tags

<img>, <area>, <map>, <param> and <object>

6
Web UIT Thiruvananthapuram

HTML List Tags

<ul>, <ol>, <li>, <dl>, <dt> and <dd>

HTML Table Tags

table, tr, td, th, tbody, thead, tfoot, col, colgroup and caption

HTML Form Tags

form, input, textarea, select, option, optgroup, button, label, fieldset and legend

HTML - Basic Tags

Heading Tags

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>

Paragraph Tag

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>
</head>
<body>
<p>Here is a first paragraph of text.</p>
7
Web UIT Thiruvananthapuram

<p>Here is a second paragraph of text.</p>


<p>Here is a third paragraph of text.</p>
</body>
</html>
HTML <body> tag

HTML <body> tag defines the main content of an HTML document which displays on the
browser. It can contain text content, paragraphs, headings, images, tables, links, videos, etc.

The <body> must be the second element after the <head> tag or it should be placed between
</head> and </html> tags. This tag is required for every HTML document and should only use
once in the whole HTML document.

Syntax

<body> Place your Content here........</body>

Following are some specifications about the <body> tag

Display Inline

Start tag/End tag Both start and End tag

Usage Structural

Example

<!DOCTYPE html>
<html>
<head>
<title>Body Tag</title>
</head>
<body>
<h2>Example of body tag</h2>
<p>This paragraph is written between the body tag</p>
</body>
</html>
HTML | <div> align Attribute
The HTML div align Attribute is used to specify the alignment of the <div> element or the
content present inside the div Element.
Note : This attribute is not supported by HTML5.
Syntax:
<div align="left | right | center | justify";>
Attribute Values:
 left: It sets the content to the left-align.
 right: It sets the content to the right-align.
 center: I sets the div element to the center. By default, it is set to center.
 justify: It sets the content to the justify position.
Example:
Supported Browsers: The browsers supported by HTML div align Attribute are listed
below:
8
Web UIT Thiruvananthapuram

 Google Chrome
 Internet Explorer
 Firefox
 Apple Safari
 Opera

HTML | Quotations
The Quotation elements in HTML are used to insert quoted texts in a web page, that is
portion of texts different from the normal texts in the web page. Below are some of the
most used quotation elements of HTML:
1. <q> element: The <q> element is used to set a set of text inside the quotation marks.
It has both opening and closing tags.

HTML <pre> Tag


The <pre> tag in HTML is used to define the block of preformatted text which preserves
the text spaces, line breaks, tabs, and other formatting characters which are ignored by
web browsers. Text in the <pre> element is displayed in a fixed-width font, but it can be
changed using CSS. The <pre> tag requires a starting and end tag.
Syntax:

<pre> Contents... </pre>

HTML - Lists
HTML offers web authors three ways for specifying lists of information. All lists must contain
one or more list elements. Lists may contain −
 <ul> − An unordered list. This will list items using plain bullets.
 <ol> − An ordered list. This will use different schemes of numbers to list your items.
 <dl> − A definition list. This arranges your items in the same way as they are arranged
in a dictionary.

HTML Unordered Lists

An unordered list is a collection of related items that have no special order or sequence. This
list is created by using HTML <ul> tag. Each item in the list is marked with a bullet.
Example
<!DOCTYPE html>
<html>

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

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

9
Web UIT Thiruvananthapuram

</html>
This will produce the following result –

 Beetroot
 Ginger
 Potato
 Radish

The type Attribute

You can use type attribute for <ul> tag to specify the type of bullet you like. By default, it is a
disc. Following are the possible options −
<ul type = "square">
<ul type = "disc">
<ul type = "circle">

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 −

1. Beetroot
2. Ginger
3. Potato
4. Radish

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 −
10
Web UIT Thiruvananthapuram

<ol type = "1"> - Default-Case Numerals.


<ol type = "I"> - Upper-Case Numerals.
<ol type = "i"> - Lower-Case Numerals.
<ol type = "A"> - Upper-Case Letters.
<ol type = "a"> - Lower-Case Letters.

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.

HTML Definition Lists

HTML and XHTML supports a list style which is called definition lists where entries are listed
like in a dictionary or encyclopedia. The definition list is the ideal way to present a glossary,
list of terms, or other name/value list.
Definition List makes use of following three tags.
 <dl> − Defines the start of the list
 <dt> − A term
 <dd> − Term definition
 </dl> − Defines the end of the list
Example
Live Demo
<!DOCTYPE html>
<html>

<head>
<title>HTML Definition List</title>
</head>

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

</html>
This will produce the following result −
HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol
HTML <hr> Tag
11
Web UIT Thiruvananthapuram

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.
Tag Attributes: The table given below describe the <hr> tag attributes. These attributes
are not supported in HTML5:

Attribute Value Description


align left center right Used to specify the alignment of the horizontal rule.
noshade noshade Used to specify the bar without shading effect.
size pixels Used to specify the height of the horizontal rule.
width pixels Used to specify the width of the horizontal rule.
Syntax :

<hr> ...
HTML - Blocks
All the HTML elements can be categorized into two categories (a) Block Level
Elements (b)Inline Elements.

Block Elements

Block elements appear on the screen as if they have a line break before and after them. For
example, the <p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <ul>, <ol>, <dl>, <pre>, <hr />,
<blockquote>, and <address> elements are all block level elements. They all start on their
own new line, and anything that follows them appears on its own new line.

Inline Elements

Inline elements, on the other hand, can appear within sentences and do not have to appear
on a new line of their own. The <b>, <i>, <u>, <em>, <strong>, <sup>, <sub>, <big>, <small>,
<li>, <ins>, <del>, <code>, <cite>, <dfn>, <kbd>, and <var> elements are all inline elements.

Grouping HTML Elements

There are two important tags which we use very frequently to group various other HTML tags
(i) <div> tag and (ii) <span> tag

The <div> tag

This is the very important block level tag which plays a big role in grouping various other HTML
tags and applying CSS on group of elements. Even now <div> tag can be used to create
webpage layout where we define different parts (Left, Right, Top etc.) of the page using <div>
tag. This tag does not provide any visual change on the block but this has more meaning when
it is used with CSS.

The <span> tag

The HTML <span> is an inline element and it can be used to group inline-elements in an HTML
document. This tag also does not provide any visual change on the block but has more
meaning when it is used with CSS.
12
Web UIT Thiruvananthapuram

The difference between the <span> tag and the <div> tag is that the <span> tag is used with
inline elements whereas the <div> tag is used with block-level elements.
Example
Following is a simple example of <span> tag. We will learn Cascading Style Sheet (CSS) in a
separate chapter but we used it here to show the usage of <span> tag −

Live Demo
<!DOCTYPE html>
<html>

<head>
<title>HTML span Tag</title>
</head>

<body>
<p>This is <spanstyle="color:red">red</span> and this is
<spanstyle="color:green">green</span></p>
</body>

</html>
This will produce the following result −
This is red and this is green
HTML Text Formatting

HTML contains several elements for defining text with a special meaning.

HTML Formatting Elements

Formatting elements were designed to display special types of text:

 <b> - Bold text


 <strong> - Important text
 <i> - Italic text
 <em> - Emphasized text
 <mark> - Marked text
 <small> - Smaller text
 <del> - Deleted text
 <ins> - Inserted text
 <sub> - Subscript text
 <sup> - Superscript text

HTML <b> and <strong> Elements

The HTML <b> element defines bold text, without any extra importance.

The HTML <strong> element defines text with strong importance. The content inside is
typically displayed in bold.

HTML <i> and <em> Elements

13
Web UIT Thiruvananthapuram

The HTML <i> element defines a part of text in an alternate voice or mood. The content
inside is typically displayed in italic.

Tip: The <i> tag is often used to indicate a technical term, a phrase from another language,
a thought, a ship name, etc.

The HTML <em> element defines emphasized text. The content inside is typically displayed
in italic.

Tip: A screen reader will pronounce the words in <em> with an emphasis, using verbal
stress.

HTML <small> Element

The HTML <small> element defines smaller text:

HTML <mark> Element

The HTML <mark> element defines text that should be marked or highlighted:

HTML <del> Element

The HTML <del> element defines text that has been deleted from a document. Browsers will
usually strike a line through deleted text:

HTML <ins> Element

The HTML <ins> element defines a text that has been inserted into a document. Browsers
will usually

HTML <sub> Element

The HTML <sub> element defines subscript text. Subscript text appears half a character
below the normal line, and is sometimes rendered in a smaller font. Subscript text can be
used for chemical formulas, like H2O:

HTML <sup> Element

The HTML <sup> element defines superscript text. Superscript text appears half a character
above the normal line, and is sometimes rendered in a smaller font. Superscript text can be
used for footnotes, like WWW
HTML Entities

HTML character entities are used as a replacement of reserved characters in HTML. You can
also replace characters that are not present on your keyboard by entities.

These characters are replaced because some characters are reserved in HTML. HTML
entities provide a wide range of characters which can allow you to add icons, geometric
shapes, mathematical operators, etc.

14
Web UIT Thiruvananthapuram

For example: if you use less than (<) or greater than (>) symbols in your text, the browser
can mix them with tags that's why character entities are used in HTML to display reserved
characters.

How to use an entity:

You can use an entity in your HTML document by name or by a numerical character reference.
Each entity starts with symbol ampersand (&) and ends with a semicolon (;).

Syntax:

&entity_name;
OR
&#entity_number;

Most used HTML Character Entities

Result Description Entity Name Entity Number

non-breaking space &nbsp; 160

< less than &lt; 60

> greater than &gt; 62

& Ampersand &amp; 38

" double quotation mark &quot; 34

' single quotation mark (apostrophe) &apos; 39

¢ Cent &cent; 162

£ Pound &pound; 163

¥ Yen &yen; 165

€ Euro &euro; 8364

© Copyright &copy; 169

® registered trademark &reg; 174

Note:Entity names are case sensitive.

Advantage of entity name: An entity name is easy to remember.

Disadvantage of entity name: Browsers may not support all entity names, but the support
for numbers is good.

Example:

15
Web UIT Thiruvananthapuram

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3>HTML entity example</h3>
<p> "This is the content written within entity"</p>
<p> <p> Paragraph tag </p>
</body>
</html>
Diacritical Marks in HTML

There are some special types of letters used in HTML whichhave some glyph added to the
top or below the letters. These glyphs are called diacritical mark.

Some diacritical marks, like grave ( )̀ and acute ( )́ are called accents.Diacritical marks can
be used both above and below a letter, inside a letter, and between two letters.

Following is a list of some diacritical marks:

Mark Character Construct Result

̀ A a&#768; à

́ A a&#769; á

̂ A a&#770; â

̃ A a&#771; ã

̀ O O&#768; Ò

́ O O&#769; Ó

̂ O O&#770; Ô

̃ O O&#771; Õ

HTML Comments

Comments are some text or code written in your code to give an explanation about the code,
and not visible to the user. Comments which are used for HTML file are known as HTML
comments. Anything written between these tags will be ignored by the browser, so comments
will not be visible on the webpage.
16
Web UIT Thiruvananthapuram

Comments of any code make code easy to understand and increase readability of code.

Comments are also part of the code, which gives an explanation of the code.

How to add comment In HTML

You can add comments in your HTML file using <! -- ... --> tag. So if you will write anything
between theses comment tag that will be treated as comment and browser will not read it.

Syntax

<! -- Write commented text here -->

Note: The commented code will not be visible to a webpage, and hence you can use comment
tag for documentation purpose, and debugging purpose:

Such as:

<!-- <p>There is some text</p>


<p>There is second text</p> -->

Multiline Comment

In HTML code, we can also comments multiple lines at a time. In multiline comment we can
use any description about code or multiple line code to debug, etc.

Syntax

<!---
Your code is commented.
Write description of code.
It will not display at webpage.
-->
HTML - Fonts

Fonts play a very important role in making a website more user friendly and increasing content
readability. Font face and color depends entirely on the computer and browser that is being
used to view your page but you can use HTML <font> tag to add style, size, and color to the
text on your website. You can use a <basefont> tag to set all of your text to the same size,
face, and color.
The font tag is having three attributes called size, color, and face to customize your fonts. To
change any of the font attributes at any time within your webpage, simply use the <font> tag.
The text that follows will remain changed until you close with the </font> tag. You can change
one or all of the font attributes within one <font> tag.
Note −The font and basefont tags are deprecated and it is supposed to be removed in a future
version of HTML. So they should not be used rather, it's suggested to use CSS styles to
manipulate your fonts. But still for learning purpose, this chapter will explain font and basefont
tags in detail.

17
Web UIT Thiruvananthapuram

Set Font Size

You can set content font size using size attribute. The range of accepted values is from
1(smallest) to 7(largest). The default size of a font is 3.

<!DOCTYPE html>
<html>

<head>
<title>Setting Font Size</title>
</head>

<body>
<fontsize="1">Font size = "1"</font><br/>
<fontsize="2">Font size = "2"</font><br/>
<fontsize="3">Font size = "3"</font><br/>
<fontsize="4">Font size = "4"</font><br/>
<fontsize="5">Font size = "5"</font><br/>
<fontsize="6">Font size = "6"</font><br/>
<fontsize="7">Font size = "7"</font>
</body>

</html>

Specify alternate font faces

A visitor will only be able to see your font if they have that font installed on their computer. So,
it is possible to specify two or more font face alternatives by listing the font face names,
separated by a comma.
<font face = "arial,helvetica">
<font face = "Lucida Calligraphy,Comic Sans MS,Lucida Console">
When your page is loaded, their browser will display the first font face available. If none of the
given fonts are installed, then it will display the default font face Times New Roman.
Note − Check a complete list of HTML Standard Fonts.

Setting Font Color

You can set any font color you like using color attribute. You can specify the color that you
want by either the color name or hexadecimal code for that color.
Note − You can check a complete list of HTML Color Name with Codes.
Example
Live Demo
<!DOCTYPE html>
<html>

<head>
<title>Setting Font Color</title>
</head>

<body>
<fontcolor="#FF00FF">This text is in pink</font><br/>
18
Web UIT Thiruvananthapuram

<fontcolor="red">This text is red</font>


</body>

</html>

The <basefont> Element

The <basefont> element is supposed to set a default font size, color, and typeface for any
parts of the document that are not otherwise contained within a <font> tag. You can use the
<font> elements to override the <basefont> settings.
The <basefont> tag also takes color, size and face attributes and it will support relative font
setting by giving size a value of +1 for a size larger or −2 for two sizes smaller.
Example
<!DOCTYPE html>
<html>

<head>
<title>Setting Basefont Color</title>
</head>

<body>
<basefontface="arial, verdana, sans-serif"size="2"color="#ff0000">
<p>This is the page's default font.</p>
<h2>Example of the &lt;basefont&gt; Element</h2>

<p><fontsize="+2" color="darkgray">
This is darkgray text with two sizes larger
</font>
</p>

<p><fontface="courier"size="-1"color="#000000">
It is a courier font, a size smaller and black in color.
</font>
</p>
</body>

</html>
This will produce the following result −

This is the page's default font.

Example of the <basefont> Element

This is darkgray text with two sizes larger

It is a courier font, a size smaller and black in color.

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

19
Web UIT Thiruvananthapuram

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>
<tableborder="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>
This will produce the following result −

Row 1, Column 1 Row 1, Column 2

Row 2, Column 1 Row 2, Column 2

Here, the border is an attribute of <table> tag and it is used to put a border across all the cells.
If you do not need a border, then you can use border = "0".

Table Heading

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

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

20
Web UIT Thiruvananthapuram

<body>
<tableborder="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>

<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>

</html>

Cellpadding and Cellspacing Attributes

There are two attributes called cellpadding and cellspacing which you will use to adjust the
white space in your table cells. The cellspacing attribute defines space between table cells,
while cellpadding represents the distance between cell borders and the content within a cell.
Example
<!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>

Colspan and Rowspan Attributes


21
Web UIT Thiruvananthapuram

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>
<tableborder="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<tdrowspan="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>
<tdcolspan="3">Row 3 Cell 1</td>
</tr>
</table>
</body>

</html>

Tables Backgrounds

You can set table background using one of the following two ways −
 bgcolor attribute − You can set background color for whole table or just for one cell.
 background attribute − You can set background image for whole table or just for one
cell.
You can also set border color also using bordercolor attribute.
Note − The bgcolor, background, and bordercolor attributes deprecated in HTML5. Do not
use these attributes.
Example
<!DOCTYPE html>
<html>

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

22
Web UIT Thiruvananthapuram

<body>
<tableborder="1"bordercolor="green"bgcolor="yellow">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<tdrowspan="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>
<tdcolspan="3">Row 3 Cell 1</td>
</tr>
</table>
</body>

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

<!DOCTYPE html>
<html>

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

<body>
<table border="1"bordercolor="green" background="/images/test.png">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<tdrowspan="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>
<tdcolspan="3">Row 3 Cell 1</td>
</tr>
</table>
</body>

23
Web UIT Thiruvananthapuram

</html>

Table Height and Width

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

Example
<!DOCTYPE html>
<html>

<head>
<title>HTML Table Width/Height</title>
</head>

<body>
<tableborder="1"width="400"height="150">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>

<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>

</html>

Table Caption

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

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

<body>
<tableborder="1"width="100%">
<caption>This is the caption</caption>

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

<tr>
24
Web UIT Thiruvananthapuram

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


</tr>
</table>
</body>

</html>

Table Header, Body, and Footer

Tables can be divided into three portions − a header, a body, and a foot. The head and foot
are rather similar to headers and footers in a word-processed document that remain the same
for every page, while the body is the main content holder of the table.
The three elements for separating the head, body, and foot of a table are −
 <thead> − to create a separate table header.
 <tbody> − to indicate the main body of the table.
 <tfoot> − to create a separate table footer.
A table may contain several <tbody> elements to indicate different pages or groups of data.
But it is notable that <thead> and <tfoot> tags should appear before <tbody>
Example
<!DOCTYPE html>
<html>

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

<body>
<tableborder="1"width="100%">
<thead>
<tr>
<tdcolspan="4">This is the head of the table</td>
</tr>
</thead>

<tfoot>
<tr>
<tdcolspan="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>
25
Web UIT Thiruvananthapuram

</body>

</html>

HTML – Colors
Colors are very important to give a good look and feel to your website. You can specify colors
on page level using <body> tag or you can set colors for individual tags
using bgcolor attribute.
The <body> tag has following attributes which can be used to set different colors −
 bgcolor − sets a color for the background of the page.
 text − sets a color for the body text.
 alink − sets a color for active links or selected links.
 link − sets a color for linked text.
 vlink − sets a color for visited links − that is, for linked text that you have already clicked
on.

HTML Color Coding Methods

There are following three different methods to set colors in your web page −
 Color names − You can specify color names directly like green, blue or red.
 Hex codes − A six-digit code representing the amount of red, green, and blue that
makes up the color.
 Color decimal or percentage values − This value is specified using the rgb( )
property.
Now we will see these coloring schemes one by one.

HTML Colors - Color Names

You can specify direct a color name to set text or background color. W3C has listed 16 basic
color names that will validate with an HTML validator but there are over 200 different color
names supported by major browsers.
Note − Check a complete list of HTML Color Name.

W3C Standard 16 Colors

Here is the list of W3C Standard 16 Colors names and it is recommended to use them.

Black Gray Silver White

Yellow Lime Aqua Fuchsia

Red Green Blue Purple

Maroon Olive Navy Teal


Example
Here are the examples to set background of an HTML tag by color name −

Live Demo
<!DOCTYPE html>
26
Web UIT Thiruvananthapuram

<html>

<head>
<title>HTML Colors by Name</title>
</head>

<bodytext="blue"bgcolor="green">
<p>Use different color names for for body and table and see the result.</p>

<tablebgcolor="black">
<tr>
<td>
<fontcolor="white">This text will appear white on black background.</font>
</td>
</tr>
</table>
</body>

</html>

HTML Colors - Hex Codes

A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red
value, the next two are a green value(GG), and the last are the blue value(BB).
A hexadecimal value can be taken from any graphics software like Adobe Photoshop,
Paintshop Pro or MS Paint.
Each hexadecimal code will be preceded by a pound or hash sign #. Following is a list of few
colors using hexadecimal notation.

Color Color HEX

#000000

#FF0000

#00FF00

#0000FF

#FFFF00

#00FFFF

#FF00FF

#C0C0C0

#FFFFFF
Example
Here are the examples to set background of an HTML tag by color code in hexadecimal −

Live Demo
27
Web UIT Thiruvananthapuram

<!DOCTYPE html>
<html>

<head>
<title>HTML Colors by Hex</title>
</head>

<bodytext="#0000FF"bgcolor="#00FF00">
<p>Use different color hexa for for body and table and see the result.</p>

<tablebgcolor="#000000">
<tr>
<td>
<fontcolor="#FFFFFF">This text will appear white on black background.</font>
</td>
</tr>
</table>
</body>

</html>

HTML Colors - RGB Values

This color value is specified using the rgb( ) property. This property takes three values, one
each for red, green, and blue. The value can be an integer between 0 and 255 or a percentage.
Note − All the browsers does not support rgb() property of color so it is recommended not to
use it.
Following is a list to show few colors using RGB values.

Color Color RGB

rgb(0,0,0)

rgb(255,0,0)

rgb(0,255,0)

rgb(0,0,255)

rgb(255,255,0)

rgb(0,255,255)

rgb(255,0,255)

rgb(192,192,192)

rgb(255,255,255)
Example
Here are the examples to set background of an HTML tag by color code using rgb() values −

Live Demo
28
Web UIT Thiruvananthapuram

<!DOCTYPE html>
<html>

<head>
<title>HTML Colors by RGB code</title>
</head>

<bodytext="rgb(0,0,255)"bgcolor="rgb(0,255,0)">
<p>Use different color code for for body and table and see the result.</p>

<tablebgcolor="rgb(0,0,0)">
<tr>
<td>
<fontcolor="rgb(255,255,255)">This text will appear white on black background.</font>
</td>
</tr>
</table>
</body>

</html>
HTML - Marquees
An HTML marquee is a scrolling piece of text displayed either horizontally across or vertically
down your webpage depending on the settings. This is created by using HTML <marquees>
tag.
Note − The <marquee> tag deprecated in HTML5. Do not use this element, instead you can
use JavaScript and CSS to create such effects.

Syntax

A simple syntax to use HTML <marquee> tag is as follows −


<marquee attribute_name = "attribute_value"....more attributes>
One or more lines or text message or image
</marquee>

The <marquee> Tag Attributes

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

Sr.No Attribute & Description

1
width
This specifies the width of the marquee. This can be a value like 10 or 20% etc.

2
height
This specifies the height of the marquee. This can be a value like 10 or 20% etc.

3
direction

29
Web UIT Thiruvananthapuram

This specifies the direction in which marquee should scroll. This can be a value like up, down,
left or right.

4
behavior
This specifies the type of scrolling of the marquee. This can have a value like scroll,
slide and alternate.

5
scrolldelay
This specifies how long to delay between each jump. This will have a value like 10 etc.

6
scrollamount
This specifies the speed of marquee text. This can have a value like 10 etc.

7
loop
This specifies how many times to loop. The default value is INFINITE, which means that the
marquee loops endlessly.

8
bgcolor
This specifies background color in terms of color name or color hex value.

9
hspace
This specifies horizontal space around the marquee. This can be a value like 10 or 20% etc.

10
vspace
This specifies vertical space around the marquee. This can be a value like 10 or 20% etc.

Below are few examples to demonstrate the usage of marquee tag.


Examples - 1
<!DOCTYPE html>
<html>

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

<body>
<marquee>This is basic example of marquee</marquee>
</body>

</html>
Examples - 2

30
Web UIT Thiruvananthapuram

<!DOCTYPE html>
<html>

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

<body>
<marqueewidth="50%">This example will take only 50% width</marquee>
</body>

</html>
Examples - 3
<!DOCTYPE html>
<html>

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

<body>
<marqueedirection="right">This text will scroll from left to right</marquee>
</body>

</html>
Examples - 4
<!DOCTYPE html>
<html>

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

<body>
<marqueedirection="up">This text will scroll from bottom to up</marquee>
</body>

</html>
HTML - Text Links
A webpage can contain various links that take you directly to other pages and even specific
parts of a given page. These links are known as hyperlinks.
Hyperlinks allow visitors to navigate between Web sites by clicking on words, phrases, and
images. Thus you can create hyperlinks using text or images available on a webpage.

Linking Documents

A link is specified using HTML tag <a>. This tag is called anchor tag and anything between
the opening <a> tag and the closing </a> tag becomes part of the link and a user can click
that part to reach to the linked document. Following is the simple syntax to use <a> tag.
<a href = "Document URL" ... attributes-list>Link Text</a>
Example

31
Web UIT Thiruvananthapuram

Let's try following example which links http://www.tutorialspoint.com at your page −

<!DOCTYPE html>
<html>

<head>
<title>Hyperlink Example</title>
</head>

<body>
<p>Click following link</p>
<ahref="https://www.tutorialspoint.com"target="_self">Tutorials Point</a>
</body>

</html>

The target Attribute

We have used target attribute in our previous example. This attribute is used to specify the
location where linked document is opened. Following are the possible options −

Sr.No Option & Description

1
_blank
Opens the linked document in a new window or tab.

2
_self
Opens the linked document in the same frame.

3
_parent
Opens the linked document in the parent frame.

4
_top
Opens the linked document in the full body of the window.

5
targetframe
Opens the linked document in a named targetframe.

Example
Try following example to understand basic difference in few options given for target attribute.

<!DOCTYPE html>
<html>

<head>
<title>Hyperlink Example</title>

32
Web UIT Thiruvananthapuram

<basehref="https://www.tutorialspoint.com/">
</head>

<body>
<p>Click any of the following links</p>
<ahref="/html/index.htm"target="_blank">Opens in New</a> |
<ahref="/html/index.htm"target="_self">Opens in Self</a> |
<ahref="/html/index.htm"target="_parent">Opens in Parent</a> |
<ahref="/html/index.htm"target="_top">Opens in Body</a>
</body>

</html>
This will produce the following result, where you can click on different links to understand the
difference between various options given for target attribute.

Use of Base Path

When you link HTML documents related to the same website, it is not required to give a
complete URL for every link. You can get rid of it if you use <base> tag in your HTML
document header. This tag is used to give a base path for all the links. So your browser will
concatenate given relative path to this base path and will make a complete URL.
Example
Following example makes use of <base> tag to specify base URL and later we can use relative
path to all the links instead of giving complete URL for every link.

<!DOCTYPE html>
<html>

<head>
<title>Hyperlink Example</title>
<basehref="https://www.tutorialspoint.com/">
</head>

<body>
<p>Click following link</p>
<ahref="/html/index.htm"target="_blank">HTML Tutorial</a>
</body>

</html>
Now given URL <a href = "/html/index.htm" is being considered as <ahref =
"http://www.tutorialspoint.com/html/index.htm"

Linking to a Page Section

You can create a link to a particular section of a given webpage by using name attribute. This
is a two-step process.
Note − The name attribute deprecated in HTML5. Do not use this attribute.
Use id and title attribute instead.
First create a link to the place where you want to reach with-in a webpage and name it using
<a...> tag as follows −

33
Web UIT Thiruvananthapuram

<h1>HTML Text Links <a name = "top"></a></h1>


Second step is to create a hyperlink to link the document and place where you want to reach

<a href = "/html/html_text_links.htm#top">Go to the Top</a>
This will produce following link, where you can click on the link generated Go to the Top to
reach to the top of the HTML Text Link tutorial.
Go to the Top

Setting Link Colors

You can set colors of your links, active links and visited links
using link, alink and vlink attributes of <body> tag.
Example
Save the following in test.htm and open it in any web browser to see
how link, alink and vlink attributes work.

<!DOCTYPE html>
<html>

<head>
<title>Hyperlink Example</title>
<basehref="https://www.tutorialspoint.com/">
</head>

<bodyalink="#54A250"link="#040404"vlink="#F40633">
<p>Click following link</p>
<ahref="/html/index.htm"target="_blank">HTML Tutorial</a>
</body>

</html>
Just check color of the link before clicking on it, next check its color when you activate it and
when the link has been visited.

Download Links

You can create text link to make your PDF, or DOC or ZIP files downloadable. This is very
simple; you just need to give complete URL of the downloadable file as follows −

Live Demo
<!DOCTYPE html>
<html>

<head>
<title>Hyperlink Example</title>
</head>

<body>
<ahref="https://www.tutorialspoint.com/page.pdf">Download PDF File</a>
</body>

34
Web UIT Thiruvananthapuram

</html>
This will produce following link and will be used to download a file.

File Download Dialog Box

Sometimes it is desired that you want to give an option where a user will click a link and it will
pop up a "File Download" box to the user instead of displaying actual content. This is very
easy and can be achieved using an HTTP header in your HTTP response.
For example, if you want make a Filename file downloadable from a given link then its syntax
will be as follows.
#!/usr/bin/perl

# Additional HTTP Header


print "Content-Type:application/octet-stream; name = \"FileName\"\r\n";
print "Content-Disposition:attachment; filename = \"FileName\"\r\n\n";

# Open the target file and list down its content as follows
open( FILE, "<FileName" );

while(read(FILE, $buffer, 100)){


print("$buffer");
}
HTML - <layer> Tag

Description

The HTML <layer> tag is used to position and animate (through scripting) elements in a page.
A layer can be thought of as a separate document that resides on top of the main one, all
existing within one window.
This tag has support in Netscape 4 and higher versions of it.

Example

This example creates three overlapping layers. The back one is red, the middle one is blue,
and the front one is green.

<!DOCTYPE html>
<html>

<head>
<title>HTML layer Tag</title>
</head>

<body>
<layerid="layer1"top="250"left="50"width="200"
height="200"bgcolor="red">
<p>layer 1</p>
</layer>

<layerid="layer2"top="350"left="150"width="200"
height="200"bgcolor="blue">
<p>layer 2</p>
35
Web UIT Thiruvananthapuram

</layer>

<layerid="layer3"top="450"left="250"width="200"
height="200"bgcolor="green">
<p>layer 3</p>
</layer>
</body>

</html>

Global Attributes

This tag supports all the global attributes described in − HTML Attribute Reference

Specific Attributes

The HTML <layer> tag also supports the following additional attributes −

Attribute Value Description

above layer name The name of the inline layer that will be positioned directly
above the current layer in the z-order.

background URL A filename or URL for an image upon which the inline layer's
text and images will appear.

below layer name The name of the inline layer that will be positioned directly
below the current layer in the z-order.

bgcolor rgb(x,x,x) The color to use for the inline layer background.
#xxxxxx
colorname

clip number The coordinates of the inline layer's viewable area.

height pixels The inline layer's height, in pixels.

left number The position of the left side of the inline layer. If the current
inline layer is part of another layer.called the parent layer-
then the position is relative to the parent layer.

name layer name The name of the inline layer.

pagex number The position of the left side of the inline layer relative to the
browser window.

pagey number The position of the top of the inline layer relative to the
browser window.

src URL The URL of a page that will appear inside the inline layer.

36
Web UIT Thiruvananthapuram

top number The position of the top of the inline layer. If the current inline
layer is part of another layer--called the parent layer--then
the position is relative to the parent layer.

visibility show Determines whether the inline layer is visible.


hide
inherit

width pixels The inline layer's width, in pixels.

z-index number The inline layer's position within the z-order. Inline layers
with higher Z-INDEX values are positioned above inline
layers with lower Z-INDEX values.

Event Attributes

This tag supports all the event attributes described in − HTML Events Reference

Browser Support

Chrome Firefox IE Opera Safari Android

No No No No No No
HTML | <link> rel Attribute
The HTML rel attribute is used to specify the relationship between the current and the
linked document. It is used only when href attribute present.
Syntax:

<link rel="value">
Attribute Values

 alternate: It specifies the alternative link of the document(i.e. print page, translated or
mirror).
 author: It define author of the link
 dns-prefetch: It Specifies that the browser should preemptively perform DNS
resolution for the target resource’s origin
 help: It specifies a link to a help document. Example: <link rel=”help” href=”/help/”>
 icon: It specifies import icon in a given document
 license: It specifies a link to copyright information for the document
 next: It provide the link of next document in series
 pingback: It specifies the address of the pingback serve
 preconnect: It specifies the target should be preemptively to the origin resource
 prefetch: It specifies that the target document should be cached.
 preload: It specifies that the browser must preemptively fetch and cache
 prerender: It specifies that the browser should load
 prev: It specifies the previous document in a selection
 search: It specifies the search tool for the document.
 stylesheet: It Imports a style sheet
Example of HTML link rel Attribute

37
Web UIT Thiruvananthapuram

<!DOCTYPE html>

<html>

<head>

<linkrel="stylesheet"

type="text/css"

href="index_screen.css">

<linkrel="stylesheet"

type="text/css"

href="index_print.css">

</head>

<body>

<center>

<h1>GeeksforGeeks</h1>

<p><ahref="https://ide.geeksforgeeks.org/tryit.php"

target="_blank">

Click here

</a>

</center>

</body>

38
Web UIT Thiruvananthapuram

</html>

Output:

Supported Browsers: The browsers supported by HTML rel Attribute are listed below

 Google Chrome 1
 Edge 12
 Firefox 1.0
 Apple Safari
 Opera
 Internet Explorer

Understanding URL
Every document on the Web has a unique address. This address is known
as Uniform Resource Locator (URL).
Several HTML/XHTML tags include a URL attribute value, including hyperlinks, inline images,
and forms. All of them use the same syntax to specify the location of a web resource,
regardless of the type or content of that resource. That's why it is known a Uniform Resource
Locator.

URL Elements

A URL is made of up several parts, each of which offers information to the web browser to
help find the page. It is easier to learn the parts of a URL, if you look at the example URL given
below, there are three key parts: the scheme, the host address, and the file path. The following
section will discuss each of them:

http://www.tutorialspoint.com/index.htm

The Scheme

The scheme identifies the type of protocol and URL you are linking to and therefore, how the
resource should be retrieved. For example, most web browsers use Hypertext Transfer
Protocol (HTTP) to pass information to communicate with the web servers and this is the
reason a URL starts with http://.
There are other schemes available and you can use either of them based on your requirement:

Sr.No Scheme & Description

1
http://

39
Web UIT Thiruvananthapuram

Hypertext Transfer Protocol (HTTP) is used to request pages from Web servers and send them
back from Web servers to browsers.

2
https://
Secure Hypertext Transfer Protocol (HTTPS) encrypts the data sent between the browser and
the Web server using a digital certificate.

3
ftp://
File Transfer Protocol is another method for transferring files on the Web. While HTTP is a lot
more popular for viewing Web sites because of its integration with browsers, FTP is still
commonly used protocol to transfer large files across the Web and to upload source files to
your Web server.

4
file://
Used to indicate that a file is on the local hard disk or a shared directory on a LAN.

The Host Address

The host address is where a website can be found, either the IP address (four sets of numbers
between 0 and 255, for example 68.178.157.132 ) or more commonly the domain name for a
site such as www.tutorialspoint.com. Note that "www" is not actually part of the domain name
although it is often used in the host address.

The File Path

The filepath always begins with a forward slash character, and may consist of one or more
directory or folder names. Each directory name is separated by forward slash characters and
the filepath may end with a filename at the end. Here index.htm is the filename which is
available in html directory:
https://www.tutorialspoint.com/html/index.htm

Other Parts of the URL

Using credentials is a way of specifying a username and password for a password-protected


part of a site. The credentials come before the host address, and they are separated from the
host address by an @ sign. Note how the username is separated from the password by a
colon. The following URL shows the username admin and the password admin123:
https://admin:admin123@tutorialspoint.com/admin/index.htm
Using the above URL, you can authenticate administrator and if provided ID and Password
are correct then administrator will have access on index.htm file available in admin directory.
You can use a telnet URL to connect to a server as follows :
telnet://user:password@tutorialspoint.com:port/

40
Web UIT Thiruvananthapuram

Another important information is Web Server Port Number. By default HTTP Server runs on
port number 80. But if you are running a server on any other port number then it can be
porvided as follows, assuming server is running on port 8080:
https://www.tutorialspoint.com:8080/index.htm
Fragment identifiers can be used after a filename to indicate a specific part of the page that a
browser should go immediately. Following is an example to reach to the top of page
html_text_links.htm.
https://www.tutorialspoint.com/html/html_text_links.htm#top
You can pass some information to the server using URL. When you use a form on a webpage,
such as a search form or an online order form, the browser can append the information you
supply to the URL to pass information from your browser to the server as follows −
https://www.tutorialspoint.com/cgi-bin/search.cgi?searchTerm=HTML
Here, searchTerm=HTML is passed to the server where search.cgi script is used to parse
this passed information and take further action.

Absolute and Relative URLs

You may address a URL in one of the following two ways:


 Absolute − An absolute URL is the complete address of a resource. For example
http://www.tutorialspoint.com/html/html_text_links.htm
 Relative − A relative URL indicates where the resource is in relation to the current
page. Given URL is added with the <base> element to form a complete URL. For
example /html/html_text_links.htm

Reserved and Unsafe Characters

Reserved characters are those have a specific meaning within the URL. For example, the
slash character separates elements of a pathname within a URL. If you need to include a slash
in a URL that is not intended to be an element separator then you need to encode it as %2F:
Unsafe characters are those have no special meaning within the URL but may have a special
meaning in the context the URL is written. For example, double quotes ("") delimit URL
attribute values in tags. If you need to include a double quotation mark directly in a URL, you
would probably confuse the browser. Instead, you should encode the double quotation mark
to avoid any possible conflict.
You can check HTML URL Encoding tutorial to understand this encoding, reserved and
unsafe characters.

HTML Image

HTML img tag is used to display image on the web page. HTML img tag is an empty tag that
contains attributes only, closing tags are not used in HTML image element.

Let's see an example of HTML image.

<h2>HTML Image Example</h2>


<img src="good_morning.jpg" alt="Good Morning Friends"/>

41
Web UIT Thiruvananthapuram

Attributes of HTML img tag

The src and alt are important attributes of HTML img tag. All attributes of HTML image tag are
given below.

1) src

It is a necessary attribute that describes the source or path of the image. It instructs the
browser where to look for the image on the server.

The location of image may be on the same directory or another server.

2) alt

The alt attribute defines an alternate text for the image, if it can't be displayed. The value of
the alt attribute describe the image in words. The alt attribute is considered good for SEO
prospective.

3) width

It is an optional attribute which is used to specify the width to display the image. It is not
recommended now. You should apply CSS in place of width attribute.

4) height

It h3 the height of the image. The HTML height attribute also supports iframe, image and object
elements. It is not recommended now. You should apply CSS in place of height attribute.

Use of height and width attribute with img tag

You have learnt about how to insert an image in your web page, now if we want to give some
height and width to display image according to our requirement, then we can set it with height
and width attributes of image.

Example:

<img src="animal.jpg" height="180" width="300" alt="animal image">

Note: Always try to insert the image with height and width, else it may flicker while displaying
on webpage.

Use of alt attribute

We can use alt attribute with tag. It will display an alternative text in case if image cannot
be displayed on browser. Following is the example for alt attribute:

<img src="animal.png" height="180" width="300" alt="animal image">

42
Web UIT Thiruvananthapuram

How to get image from another directory/folder?

To insert an image in your web, that image must be present in your same folder where you
have put the HTML file. But if in some case image is available in some other directory then
you can access the image like this:

<img src="E:/images/animal.png" height="180" width="300" alt="animal image">

In above statement we have put image in local disk E------>images folder------>animal.png.

Note: If src URL will be incorrect or misspell then it will not display your image on web page,
so try to put correct URL.

Use <img> tag as a link

We can also link an image with other page or we can use an image as a link. To do this, put
<img> tag inside the <a> tag.

Example:

<ahref="https://www.javatpoint.com/what-is-
robotics"><img src="robot.jpg" height="100" width="100"></a>

HTML <frame> tag (Not supported in HTML5)

HTML <frame> tag define the particular area within an HTML file where another HTML web
page can be displayed.

A <frame> tag is used with <frameset>, and it divides a webpage into multiple sections or
frames, and each frame can contain different web pages.

Note: Do not use HTML <frame> tag as it is not supported in HTML5, instead you can use
<iframe> or <div> with CSS to achieve similar effects in HTML.

Syntax

1. < frame src = "URL" >

Following are some specifications about the HTML <frame> tag

Display Block

Start tag/End tag Start tag(required), End tag(forbidden)

Usage Frames

Example 1
43
Web UIT Thiruvananthapuram

Create Vertical frames:

<!DOCTYPE html>
<html>
<head>
<title>Frame tag</title>
</head>
<frameset cols="25%,50%,25%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>

Frame1.html

<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: #7fffd4;
height: 500px;
}
</style>
</head>
<body>
<div>
<h2>This is first frame</h2>
</div>
</body>
</html>

Frame2.html

<!DOCTYPE html>
<html>
<head>
<style>

44
Web UIT Thiruvananthapuram

div{
background-color: #2f4f4f;
height: 500px;

}
</style>
</head>
<body>
<div>
<h2>This is Second frame</h2>
</div>
</body>
</html>

Frame3.html

<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: #c1ffc1;
height: 500px;
}
</style>
</head>
<body>
<div>
<h2>This is Third frame</h2>
</div>
</body>
</html>

Example 2:

Create Horizontal frames:

<!DOCTYPE html>
<html>
45
Web UIT Thiruvananthapuram

<head>
<title>Frame tag</title>
</head>
<frameset rows="30%, 40%, 30%">
<frame name="top" src="frame1.html" >
<frame name="main" src="frame2.html">
<frame name="bottom" src="frame3.html">
</frameset>
</html>

Attribute
Tag-specific attribute

Attribute Value Description

frameborder 0 It specifies whether to display a border around the frame or


1 not, and its default value is 1

longdsec URL It specifies a page which contains the long description of the
content of the frame.

marginheight pixels It specifies the top and bottom margins of the frame.

marginwidth pixels It defines the height of the margin between frames.

name text It is used to assign the name to the frame.

noresize noresize It is used to prevent resizing of the frame by the user.

scrolling yes It specifies the existence of the scrollbar for overflowing


no content.
auto

src URL It specifies the URL of the document which we want to display
in a frame.

HTML Form

An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.

46
Web UIT Thiruvananthapuram

An HTML form facilitates the user to enter data that is to be sent to the server for processing
such as name, email address, password, phone number, etc. .

Why use HTML Form

HTML forms are required if you want to collect some data from of the site visitor.

For example: If a user want to purchase some items on internet, he/she must fill the form such
as shipping address and credit/debit card details so that item can be sent to the given address.

HTML Form Syntax

<form action="server url" method="get|post">


//input controls e.g. textfield, textarea, radiobutton, button
</form>

HTML Form Tags

Let's see the list of HTML 5 form tags.

Tag Description

<form> It defines an HTML form to enter inputs by the used side.

<input> It defines an input control.

<textarea> It defines a multi-line input control.

<label> It defines a label for an input element.

<fieldset> It groups the related element in a form.

<legend> It defines a caption for a <fieldset> element.

<select> It defines a drop-down list.

<optgroup> It defines a group of related options in a drop-down list.

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.

HTML 5 Form Tags

Let's see the list of HTML 5 form tags.

Tag Description

<datalist> It specifies a list of pre-defined options for input control.

47
Web UIT Thiruvananthapuram

<keygen> It defines a key-pair generator field for forms.

<output> It defines the result of a calculation.

HTML <form> element

The HTML <form> element provide a document section to take input from user. It provides
various interactive controls for submitting information to web server such as text field, text
area, password field, etc.

Note: The <form> element does not itself create a form but it is container to contain all required
form elements, such as <input>, <label>, etc.

Syntax:

<form>
//Form elements
</form>

HTML <input> element

The HTML <input> element is fundamental form element. It is used to create form fields, to
take input from user. We can apply different input filed to gather different information form
user. Following is the example to show the simple text input.

Example:

<body>
<form>
Enter your name <br>
<input type="text" name="username">
</form>
</body>
HTML TextField Control

The type="text" attribute of input tag creates textfield control also known as single line textfield
control. The name attribute is optional, but it is required for the server side component such
as JSP, ASP, PHP etc.

<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
</form>
HTML <textarea> tag in form

The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of <textarea>
can be specify either using "rows" or "cols" attribute or by CSS.

Example:

48
Web UIT Thiruvananthapuram

<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<form>
Enter your address:<br>
<textarea rows="2" cols="20"></textarea>
</form>
</body>
</html>
Label Tag in Form

It is considered better to have label in form. As it makes the code parser/browser/user friendly.

If you click on the label tag, it will focus on the text control. To do so, you need to have for
attribute in label tag that must be same as id attribute of input tag.

NOTE: It is good to use <label> tag with form, although it is optional but if you will use
it, then it will provide a focus when you tap or click on label tag. It is more worthy with
touchscreens.
<form>
<label for="firstname">First Name: </label> <br/>
<input type="text" id="firstname" name="firstname"/> <br/>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"/> <br/>
</form>

HTML 5 Email Field Control

The email field in new in HTML 5. It validates the text for correct email address. You must use
@ and . in this field.

<form>
<label for="email">Email: </label>
<input type="email" id="email" name="email"/> <br/>
</form>
Radio Button Control

The radio button is used to select one option from multiple options. It is used for selection of
gender, quiz questions etc.

If you use one name for all the radio buttons, only one radio button can be selected at a time.

Using radio buttons for multiple options, you can only choose a single option at a time.

<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender" value="female"/>Female <br/>

49
Web UIT Thiruvananthapuram

</form>
Checkbox Control

The checkbox control is used to check multiple options from given checkboxes.

<form>
Hobby:<br>
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
<label for="cricket">Cricket</label> <br>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label> <br>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>
Note: These are similar to radio button except it can choose multiple options at a time
and radio button can select one button at a time, and its display.

Submit button control

HTML <input type="submit"> are used to add a submit button on web page. When user
clicks on submit button, then form get submit to the server.

Syntax:

<input type="submit" value="submit">

The type = submit , specifying that it is a submit button

The value attribute can be anything which we write on button on web page.

The name attribute can be omit here.

Example:

<form>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
HTML <fieldset> element:

The <fieldset> element in HTML is used to group the related information of a form. This
element is used with <legend> element which provide caption for the grouped elements.

Example:

<form>
<fieldset>
<legend>User Information:</legend>
<label for="name">Enter name</label><br>

50
Web UIT Thiruvananthapuram

<input type="text" id="name" name="name"><br>


<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</fieldset>
</form>
HTML Form Example

Following is the example for a simple form of registration.

<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<h2>Registration form</h2>
<form>
<fieldset>
<legend>User personal information</legend>
<label>Enter your full name</label><br>
<input type="text" name="name"><br>
<label>Enter your email</label><br>
<input type="email" name="email"><br>
<label>Enter your password</label><br>
<input type="password" name="pass"><br>
<label>confirm your password</label><br>
<input type="password" name="pass"><br>
<br><label>Enter your gender</label><br>
<input type="radio" id="gender" name="gender" value="male"/>Male <br>
<input type="radio" id="gender" name="gender" value="female"/>Female <br/>
<input type="radio" id="gender" name="gender" value="others"/>others <br/>
<br>Enter your Address:<br>
<textarea></textarea><br>
<input type="submit" value="sign-up">
</fieldset>
</form>
</body>
</html>

Module II
CSS
CSS is used to control the style of a web document in a simple and easy way.
CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions
CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics
to advanced concepts.
Why to Learn CSS?

51
Web UIT Thiruvananthapuram

Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
CSS is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning CSS:
Create Stunning Web site - CSS handles the look and feel part of a web page. Using CSS,
you can control the color of the text, the style of fonts, the spacing between paragraphs, how
columns are sized and laid out, what background images or colors are used, layout
designs,variations in display for different devices and screen sizes as well as a variety of other
effects.
Become a web designer - If you want to start a carrer as a professional web designer, HTML
and CSS designing is a must skill.
Control web - CSS is easy to learn and understand but it provides powerful control over the
presentation of an HTML document. Most commonly, CSS is combined with the markup
languages HTML or XHTML.
Learn other languages - Once you understands the basic of HTML and CSS then other
related technologies like javascript, php, or angular are become easier to understand.
Hello World using CSS.
Just to give you a little excitement about CSS, I'm going to give you a small conventional CSS
Hello World program, You can try it using Demo link.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
<style>
h1 {
color: #36CFFF;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Applications of CSS

52
Web UIT Thiruvananthapuram

As mentioned before, CSS is one of the most widely used style language over the web. I'm
going to list few of them here:
CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages as
you want.
Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every
time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less
code means faster download times.
Easy maintenance - To make a global change, simply change the style, and all elements in
all the web pages will be updated automatically.
Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you can
give a far better look to your HTML page in comparison to HTML attributes.
Multiple Device Compatibility - Style sheets allow content to be optimized for more than one
type of device. By using the same HTML document, different versions of a website can be
presented for handheld devices such as PDAs and cell phones or for printing.
Global web standards - Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to
make them compatible to future browsers.
Audience
This CSS tutorial will help both students as well as professionals who want to make their
websites or personal blogs more attractive.
Prerequisites
You should be familiar with:
Basic word processing using any text editor.
How to create directories and files.
How to navigate through different directories.
Internet browsing using popular browsers like Internet Explorer or Firefox.
Developing simple Web Pages using HTML or XHTML
A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document. 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 are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.
You can put CSS Style Rule Syntax as follows −
53
Web UIT Thiruvananthapuram

selector { property: value }

Example − You can define a table border as follows −


table{ border :1px solid #C00; }
Here table is a selector and border is a property and given value 1px solid #C00 is the value
of that property.
You can define selectors in various simple ways based on your comfort. Let me put these
selectors one by one.
The Type Selectors
This is the same selector we have seen above. Again, one more example to give a color to all
level 1 headings −
h1 {
color: #36CFFF;
}
The Universal Selectors
Rather than selecting elements of a specific type, the universal selector quite simply matches
the name of any element type −
{
color: #000000;
}
This rule renders the content of every element in our document in black.
The Descendant Selectors
Suppose you want to apply a style rule to a particular element only when it lies inside a
particular element. As given in the following example, style rule will apply to <em> element
only when it lies inside <ul> tag.
ul em {
color: #000000;
}
The Class Selectors

54
Web UIT Thiruvananthapuram

You can define style rules based on the class attribute of the elements. All the elements having
that class will be formatted according to the defined rule.
.black {
color: #000000;
}
This rule renders the content in black for every element with class attribute set to black in our
document. You can make it a bit more particular. For example −
h1.black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to given element. Consider the following example

<p class = "center bold">
This para will be styled by the classes center and bold.
</p>
A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document. 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 are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.
You can put CSS Style Rule Syntax as follows −
selector { property: value }

Example − You can define a table border as follows −


table{ border :1px solid #C00; }

55
Web UIT Thiruvananthapuram

Here table is a selector and border is a property and given value 1px solid #C00 is the value
of that property.
You can define selectors in various simple ways based on your comfort. Let me put these
selectors one by one.
The Type Selectors
This is the same selector we have seen above. Again, one more example to give a color to all
level 1 headings −
h1 {
color: #36CFFF;
}
The Universal Selectors
Rather than selecting elements of a specific type, the universal selector quite simply matches
the name of any element type −
{
color: #000000;
}
This rule renders the content of every element in our document in black.
The Descendant Selectors
Suppose you want to apply a style rule to a particular element only when it lies inside a
particular element. As given in the following example, style rule will apply to <em> element
only when it lies inside <ul> tag.
ul em {
color: #000000;
}
The Class Selectors
You can define style rules based on the class attribute of the elements. All the elements having
that class will be formatted according to the defined rule.
.black {
color: #000000;
}
This rule renders the content in black for every element with class attribute set to black in our
document. You can make it a bit more particular. For example −
h1.black {
color: #000000;
}

56
Web UIT Thiruvananthapuram

This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to given element. Consider the following example

<p class = "center bold">
This para will be styled by the classes center and bold.
</p>
The ID Selectors
You can define style rules based on the id attribute of the elements. All the elements having
that id will be formatted according to the defined rule.

#black {
color: #000000;
}
This rule renders the content in black for every element with id attribute set to black in our
document. You can make it a bit more particular. For example −
h1#black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with id attribute set to black.
The true power of id selectors is when they are used as the foundation for descendant
selectors, For example −
#black h2 {
color: #000000;
}
In this example all level 2 headings will be displayed in black color when those headings will
lie with in tags having id attribute set to black.
The Child Selectors
You have seen the descendant selectors. There is one more type of selector, which is very
similar to descendants but have different functionality. Consider the following example −
body > p {
color: #000000;
}
This rule will render all the paragraphs in black if they are direct child of <body> element. Other
paragraphs put inside other elements like <div> or <td> would not have any effect of this rule.
The Attribute Selectors

57
Web UIT Thiruvananthapuram

You can also apply styles to HTML elements with particular attributes. The style rule below
will match all the input elements having a type attribute with a value of text −
input[type = "text"] {
color: #000000;
}
The advantage to this method is that the <input type = "submit" /> element is unaffected, and
the color applied only to the desired text fields.
There are following rules applied to attribute selector.
p[lang] − Selects all paragraph elements with a lang attribute.
p[lang="fr"] − Selects all paragraph elements whose lang attribute has a value of exactly "fr".
p[lang~="fr"] − Selects all paragraph elements whose lang attribute contains the word "fr".
p[lang|="en"] − Selects all paragraph elements whose lang attribute contains values that are
exactly "en", or begin with "en-".

JAVASCRIPT
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages. It is an interpreted, full-fledged programming
language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser. Since then, it has been adopted by all other graphical web
browsers. With JavaScript, users can build modern web applications to interact directly
without reloading the page every time. The traditional website uses js to provide several
forms of interactivity and simplicity.
Features of JavaScript
There are following features of JavaScript:
 All popular web browsers support JavaScript as they provide built-in execution environments.
 JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
 JavaScript is a weakly typed language, where certain types are implicitly cast (depending on
the operation).
 JavaScript is an object-oriented programming language that uses prototypes rather than using
classes for inheritance.
 It is a light-weighted and interpreted language.
 It is a case-sensitive language.

58
Web UIT Thiruvananthapuram

 JavaScript is supportable in several operating systems including, Windows, macOS, etc.


 It provides good control to the users over the web browsers.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
 Displaying clocks etc.
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily interpret the
code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
Advantages of JavaScript comments
There are mainly two advantages of JavaScript comments.
To make code easy to understand It can be used to elaborate the code so that end user
can easily understand the code.
To avoid the unnecessary code It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may be need
to disable the code. In such case, it is better to use comments.

Types of JavaScript Comments


There are two types of comments in JavaScript.
Single-line Comment
Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the statement.
Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>

Let’s see the example of single-line comment i.e. added after the statement.

59
Web UIT Thiruvananthapuram

<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For example:
/* your code here */
It can be used before, after and middle of the statement.
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
 Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are different variables.
Correct JavaScript variables
var x = 10;
var _value="sonoo";

Incorrect JavaScript variables


var 123=30;
var *aa=320;

Example of JavaScript variable


Let’s see a simple example of JavaScript variable.
<script>

60
Web UIT Thiruvananthapuram

var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Output :30
30JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared outside
the function or declared with window object is known as global variable. For example:
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

61
Web UIT Thiruvananthapuram

JavaScript Global Variable


A JavaScript global variable is declared outside the function or declared with window object.
It can be accessed from any function.
Let’s see the simple example of global variable in JavaScript.
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
</script>

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types
of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the
data type. It can hold any type of values such as numbers, strings etc. For example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

62
Web UIT Thiruvananthapuram

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:
ava Try Catch

Data Description
Type

Object represents instance through which we can


access members

Array represents group of similar values

RegExp represents regular expression

We will have great discussion on each data type later.


JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
 Arithmetic Operators
 Comparison (Relational) Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

63
Web UIT Thiruvananthapuram

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus 20%10 = 0
(Remainder)

++ Increment var a=10; a++; Now a =


11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same 10==20 = false


type)

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 =


false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

Operator Description Example

64
Web UIT Thiruvananthapuram

& Bitwise AND (10==20 & 20==33) =


false

| Bitwise OR (10==20 | 20==33) =


false

^ Bitwise XOR (10==20 ^ 20==33) =


false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with (10>>>2) = 2


Zero

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a =


30

-= Subtract and var a=20; a-=10; Now a =


assign 10

65
Web UIT Thiruvananthapuram

*= Multiply and var a=10; a*=20; Now a =


assign 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and var a=10; a%=2; Now a =


assign 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the


condition. It is like if-else.

, Comma Operator allows multiple expressions to


be evaluated as single statement.

delete Delete Operator deletes a property from the


object.

in In Operator checks if object has the given


property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the


generator's iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.
If Statement
If else statement

66
Web UIT Thiruvananthapuram

if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement

Let’s see the simple example of if statement in javascript.


<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if -else
statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
67
Web UIT Thiruvananthapuram

}
Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even or odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){

68
Web UIT Thiruvananthapuram

//content to be evaluated if expression3 is true


}
else{
//content to be evaluated if no expression is true
}
Let’s see the simple example of if else if statement in javascript.
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Output of the above example
a is equal to 20
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It
is just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.
The signature of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

69
Web UIT Thiruvananthapuram

default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>

JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
 for loop
 while loop
 do-while loop
 for-in loop
JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{

70
Web UIT Thiruvananthapuram

code to be executed
}
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Output:
1
2
3
4
5
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15
71
Web UIT Thiruvananthapuram

3) JavaScript do while loop


The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
Code reusability: We can call a function several times so it save coding.
Less coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Functions can have 0 or more arguments.

72
Web UIT Thiruvananthapuram

JavaScript Function Example


Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Output of the above example


JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that has one
argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the example of
function that returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>

Output of the above example


hello javatpoint! How r u?

73
Web UIT Thiruvananthapuram

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object.
But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.
 By object literal
 By creating instance of Object directly (using new keyword)
 By using an object constructor (using new keyword)
JavaScript Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
102 Shyam Kumar 40000

2) By creating instance of Object


The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

74
Web UIT Thiruvananthapuram

Output of the above example


101 Ravi 50000

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be assigned in
the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
Output of the above example
103 Vimal Jaiswal 30000

Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.
The example of defining method in object is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;

this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
75
Web UIT Thiruvananthapuram

document.write(e.id+" "+e.name+" "+e.salary);


e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

Browser Object Model


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:
window.alert("hello javatpoint");
is same as:
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

Window Object
The window object represents a window in browser. An object of window is created
automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript objects are
string, array, date etc.
Note: if html document contains frame or iframe, browser creates additional window
objects for each frame.
Methods of window object
The important methods of window object are as follows:

76
Web UIT Thiruvananthapuram

Method Description

alert() displays the alert box containing message with


ok button.

confirm() displays the confirm dialog box containing


message with ok and cancel button.

prompt() displays a dialog box to get input from the


user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling


function, evaluating expressions etc.

Example of alert() in javascript


It displays alert dialog box. It has message and ok button.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>

Example of confirm() in javascript


It displays the confirm dialog box. It has message with ok and cancel buttons.
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
77
Web UIT Thiruvananthapuram

}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>

Example of prompt() in javascript


It displays prompt dialog box for input. It has message and textfield.
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}</script>
<input type="button" value="click" onclick="msg()"/>

Example of open() in javascript


It displays the content in a new window.
<script type="text/javascript">
function msg(){
open("http://www.javatpoint.com");
}
</script>
<input type="button" value="javatpoint" onclick="msg()"/>

Example of setTimeout() in javascript


It performs its task after the given milliseconds.
<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javatpoint after 2 seconds")
},2000);
}
</script>
<input type="button" value="click" onclick="msg()"/>

78
Web UIT Thiruvananthapuram

Document Object Model


The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
As mentioned earlier, it is the object of window. So
window.document
Is same as document

Properties of document object


Let's see the properties of document object that can be accessed and modified by the
document
object.

Methods of document object


We can access and change the contents of document by its methods.
The important methods of document object are as follows:

79
Web UIT Thiruvananthapuram

Method Description

write("string") writes the given string on the


doucment.

writeln("string") writes the given string on the


doucment with newline
character at the end.

getElementById() returns the element having the


given id value.

getElementsByName() returns all the elements having


the given name value.

getElementsByTagName() returns all the elements having


the given tag name.

getElementsByClassName() returns all the elements having


the given class name.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
80
Web UIT Thiruvananthapuram

</form>

Output of the above example

Enter Name:

Javascript - document.getElementById() method


The document.getElementById() method returns the element of specified id.
In the previous page, we have used document.form1.name.value to get the value of the
input value. Instead of this, we can use document.getElementById() method to get value of
the input text. But we need to define id for the input field.
Let's see the simple example of document.getElementById() method that prints cube of the
given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>

Output of the above example

EnterNo:

Javascript - document.getElementsByName() method


The document.getElementsByName() method returns all the element of specified name.
The syntax of the getElementsByName() method is given below:
document.getElementsByName("name")
Here, name is required.
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
<script type="text/javascript">
81
Web UIT Thiruvananthapuram

function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>

Output of the above example

Male: Female:
Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.
Example of innerHTML property
In this example, we are going to create the html form when user clicks on the button.
In this example, we are dynamically writing the html form inside the div name having the id
mylocation. We are identifing this position by calling the document.getElementById() method.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' col
s='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>

82
Web UIT Thiruvananthapuram

JavaScript Form Validation


It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form
validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
83
Web UIT Thiruvananthapuram

JavaScript Retype Password Validation


<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.jsp" onsubmit="return matchpass()">


Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
84
Web UIT Thiruvananthapuram

Number: <input type="text" name="num"><span id="numloc"></span><br/>


<input type="submit" value="submit">
</form>

JavaScript validation with image


Let’s see an interactive JavaScript form validation example that displays correct and incorrect
image if input is correct or incorrect.
<script>
function validate(){
var name=document.f1.name.value;
var password=document.f1.password.value;
var status=false;

if(name.length<1){
document.getElementById("nameloc").innerHTML=
" <img src='unchecked.gif'/> Please enter your name";
status=false;
}else{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}
if(password.length<6){
document.getElementById("passwordloc").innerHTML=
" <img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}
return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/>
85
Web UIT Thiruvananthapuram

<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
JavaScript email validation
We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
email id must contain the @ and . character
There must be at least one character before and after the @.
There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>
HTML/DOM events for JavaScript
HTML or DOM events are widely used in JavaScript code. JavaScript code is executed with
HTML/DOM events. So before learning JavaScript, let’s have some idea about events.

Events Description

onclick occurs when element is clicked.

86
Web UIT Thiruvananthapuram

ondblclick occurs when element is double-clicked.

onfocus occurs when an element gets focus such as


button, input, textarea etc.

onblur occurs when form looses the focus from an


element.

onsubmit occurs when form is submitted.

onmouseover occurs when mouse is moved over an


element.

onmouseout occurs when mouse is moved out from an


element (after moved over).

onmousedown occurs when mouse button is pressed over


an element.

onmouseup occurs when mouse is released from an


element (after mouse is pressed).

onload occurs when document, object or frameset


is loaded.

onunload occurs when body or frameset is unloaded.

onscroll occurs when document is scrolled.

onresized occurs when document is resized.

onreset occurs when form is reset.

onkeydown occurs when key is being pressed.

onkeypress occurs when user presses the key.

onkeyup occurs when key is released.

87

You might also like