0% found this document useful (0 votes)
199 views

WEB PROGRAMMING I Course Notes

The document provides an introduction to web programming and HTML. It discusses key concepts like HTML, tags, and basic page structure. HTML is used to define elements and structure on webpages. Basic tags include <html>, <head>, <title>, and <body>. Common elements like headings are also introduced, with <h1> through <h6> tags defining different heading sizes. The document serves as course notes for an introduction to web programming class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
199 views

WEB PROGRAMMING I Course Notes

The document provides an introduction to web programming and HTML. It discusses key concepts like HTML, tags, and basic page structure. HTML is used to define elements and structure on webpages. Basic tags include <html>, <head>, <title>, and <body>. Common elements like headings are also introduced, with <h1> through <h6> tags defining different heading sizes. The document serves as course notes for an introduction to web programming class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Academic year 2021/2022

WEB PROGRAMMING I
Course notes
Proposed by Mr. TAFOPA Igor

Lecturer at IME School

Mr. TAFOPA 6-90-83-88-42 1


Academic year 2021/2022
CHAPTER ONE: INTRODUCTION TO WEB PROGRAMMING
1.1INTRODUCTION:
Web programming, also known as web development, is the creation of dynamic web applications.
Examples of web applications are social networking sites like Facebook or e-commerce sites like Amazon.
Hypertext Markup Language (HTML) is one of the three main components of modern
webpages, along with Cascading Style Sheets (CSS) and JavaScript. HTML indicates to the browser what
elements should be included in the webpage (and in what order). CSS indicates how each element should
be styled. JavaScript provides a means for webpage authors to manipulate these elements
programmatically and in response to actions by the end user.

1.2 INTERNET AND ITS SERVICES


The Internet is a heterogeneous worldwide network consisting of a large number of host
computers and local area networks. The Internet uses the TCP/IP suite of protocols. This allows the
integration of a large number of different computers into one single network with highly efficient
communication between them. This way, the user can access information on all kinds of host computers
from a desktop PC, Macintosh, or whatever he/she has available
The most fundamental function of the Internet is to pass electronic information from one
computer to another. A 32-bit Internet Address or IP-Number identifies every computer on the network.
This number is commonly represented as four numbers joined by periods. The Internet uses these numbers
to guide information through the network ("routing"). For human users, however, such numbers are
usually difficult to keep in mind. Therefore, computers are also identified by Domain Names, which are
to some extent similar to mailing addresses. Special programs, called "Name Servers", translate Domain
Names into IP-Addresses.

1.2.1 Internet Services

Internet services allows us to access huge amount of information such as text, graphics, sound
and software over the internet. Following diagram shows the four different categories of Internet
Services.

Mr. TAFOPA 6-90-83-88-42 2


Academic year 2021/2022

a. Communication Services

There are various Communication Services available that offer exchange of information with
individuals or groups. The following table introduces these services:

S.N. Service Description

1 Electronic mail
Used to send electronic message over the internet.

2 Telnet
Used to log on to a remote computer that is attached to internet.

5 Mailing Lists
Used to organize group of internet users to share common information through e-mail.

6 Internet Telephony (VoIP)


Allows the internet users to talk across internet to any PC equipped to receive the call.

Mr. TAFOPA 6-90-83-88-42 3


Academic year 2021/2022
7 Instant Messaging
Offers real time chat between individuals and group of people. Eg. Yahoo messenger,
MSN messenger.

b. Information Retrieval Services

There exist several Information retrieval services offering easy access to information present on
the internet. The following table introduces these services:

S.N. Service Description

1 File Transfer Protocol (FTP)


Enable the users to transfer files.

2 Archie
It has updated database of public FTP sites and their content. It helps to search a file by
its name.

3 Gopher
Used to search, retrieve, and display documents on remote sites.

c. Web Services

Web services allow exchange of information between applications on the web. Using web
services, applications can easily interact with each other.

Mr. TAFOPA 6-90-83-88-42 4


Academic year 2021/2022

d. World Wide Web (WWW)

WWW is also known as W3. It offers a way to access documents spread over the several servers
over the internet. These documents may contain texts, graphics, audio, video, hyperlinks. The
hyperlinks allow the users to navigate between the documents.

1.3 OPERATION OF THE WEB


Web operations (WebOps) is a domain of expertise within IT systems management that involves the
deployment, operation, maintenance, tuning, and repair of web-based applications and systems
1.4ADDRESSING OF WEB DOCUMENTS
 WHAT IS WEB ADDRESS
The web address contains information about the location of the webpage.
It is also known as the URL (uniform resource locator).
Like the address for your home, a web address organizes information about a webpage's
location in a predictable way.

This is how to break down the information using the following URL as an example:
www.supremecourt.gov/opinions/12pdf/11-697_d1o2.pdf

Mr. TAFOPA 6-90-83-88-42 5


Academic year 2021/2022

CHAPTER TWO: HTML

2.1 OVERVIEW

HTML stands for Hyper Text Markup Language. It is a formatting language used to define the
appearance and contents of a web page. It allows us to organize text, graphics, audio, and video
on a web page.

Key Points:

 The word Hypertext refers to the text which acts as a link.

 The word markup refers to the symbols that are used to define structure of the text. The
markup symbols tells the browser how to display the text and are often called tags.

 The word Language refers to the syntax that is similar to any other language.

HTML was created by Tim Berners-Lee at CERN.

HTML Versions

The following table shows the various versions of HTML:

Version Year

HTML 1.0 1991

HTML 2.0 1995

HTML 3.2 1997

Mr. TAFOPA 6-90-83-88-42 6


Academic year 2021/2022
HTML 4.0 1999

XHTML 2000

HTML5 2012

2.2 HTML Tags

A Tag is a command that tells the web browser how to display the text, audio, graphics or video
on a web page.

Key Points:

 Tags are indicated with pair of angle brackets.

 They start with a less than (<) character and end with a greater than (>) character.

 The tag name is specified between the angle brackets.

 Most of the tags usually occur in pair: the start tag and the closing tag.

 The start tag is simply the tag name is enclosed in angle bracket whereas the closing tag is
specified including a forward slash (/).

 Some tags are the empty i.e. they don’t have the closing tag.

 Tags are not case sensitive.

 The starting and closing tag name must be the same. For example <b> hello </i> is invalid
as both are different.

 If you don’t specify the angle brackets (<>) for a tag, the browser will treat the tag name
as a simple text.

Mr. TAFOPA 6-90-83-88-42 7


Academic year 2021/2022
 The tag can also have attributes to provide additional information about the tag to the
browser.

Basic tags

The following table shows the Basic HTML tags that define the basic web page:

Tag Description

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

<html> </html> Specifies the document as a web page.

<head> </head> Specifies the descriptive information about the web documents.

<title> </title> Specifies the title of the web page.

<body> </body> Specifies the body of a web document.

The following code shows how to use basic tags.

<! DOCTYPE HTML>


<html>
<head>
<title> This is the document title</title>
</head>
<body>
<h1>this is heading one </h1>

Mr. TAFOPA 6-90-83-88-42 8


Academic year 2021/2022
<p>this is a paragraph </p>
<body>
</html>

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>

Mr. TAFOPA 6-90-83-88-42 9


Academic year 2021/2022
This will produce the following result:

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>

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

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

</body>

</html>

This will produce the following result:

Here is a first paragraph of text.

Mr. TAFOPA 6-90-83-88-42 10


Academic year 2021/2022
Here is a second paragraph of text.

Here is a third paragraph of text.

2.3 HTML ELEMENTS


An HTML element is defined by a starting tag. If the element contains other content, it ends with
a closing tag, where the element name is preceded by a forward slash as shown below with few
tags:

Start Tag Content End Tag

<p> This is paragraph content. </p>

<h1> This is heading content. </h1>

<div> This is division content. </div>

<br />

So here <p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There are
some HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br />
elements. These are known as void elements.

HTML documents consists of a tree of these elements and they specify how HTML documents
should be built, and what kind of content should be placed in what part of an HTML document.

HTML Tag vs. Element


A starting tag defines an HTML element. If the element contains other content, it ends with a
closing tag.

Mr. TAFOPA 6-90-83-88-42 11


Academic year 2021/2022
For example, <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but
<p>This is paragraph</p> is a paragraph element.

Nested HTML Elements


It is very much allowed to keep one HTML element inside another HTML element:

Example

<!DOCTYPE html>

<html>

<head>

<title>Nested Elements Example</title>

</head>

<body>

<h1>This is <i>italic</i> heading</h1>

<p>This is <u>underlined</u> paragraph</p>

</body>

</html>

This will display the following result:

This is italic heading


This is underlined paragraph

2.4 HTML – ATTRIBUTES

Mr. TAFOPA 6-90-83-88-42 12


Academic year 2021/2022
We have seen few HTML tags and their usage like heading tags <h1>, <h2>, paragraph tag <p>
and other tags. We used them so far in their simplest form, but most of the HTML tags can also
have attributes, which are extra bits of information.

An attribute is used to define the characteristics of an HTML element and is placed inside the
element's opening tag. All attributes are made up of two parts: a name and a value:

• The name is the property you want to set. For example, the paragraph <p> element in the
example carries an attribute whose name is align, which you can use to indicate the
alignment of paragraph on the page.

• The value is what you want the value of the property to be set and always put within
quotations. The below example shows three possible values of align attribute: left, center
and right.

Example

<!DOCTYPE html>

<html>

<head>

<title>Align Attribute Example</title>

</head>

<body>

<p align="left">This is left aligned</p>

<p align="center">This is center aligned</p>

<p align="right">This is right aligned</p>

</body>

</html>

This will display the following result:

Mr. TAFOPA 6-90-83-88-42 13


Academic year 2021/2022
This is left aligned

This is center aligned


This is right aligned

Core Attributes
The four core attributes that can be used on the majority of HTML elements (although not all)
are:

• Id
• Title
• Class
• Style

The Id Attribute
The id attribute of an HTML tag can be used to uniquely identify any element within an HTML
page. There are two primary reasons that you might want to use an id attribute on an element:

• If an element carries an id attribute as a unique identifier, it is possible to identify just that


element and its content.

• If you have two elements of the same name within a Web page (or style sheet), you can
use the id attribute to distinguish between elements that have the same name.

We will discuss style sheet in separate tutorial. For now, let's use the id attribute to distinguish
between two paragraph elements as shown below.

Example

<p id="html">This para explains what is HTML</p>

<p id="css">This para explains what is Cascading Style Sheet</p>

Mr. TAFOPA 6-90-83-88-42 14


Academic year 2021/2022
The title Attribute
The title attribute gives a suggested title for the element. They syntax for the title attribute is
similar as explained for id attribute:

The behavior of this attribute will depend upon the element that carries it, although it is often
displayed as a tooltip when cursor comes over the element or while the element is loading.

Example

<!DOCTYPE html>

<html>

<head>

<title>The title Attribute Example</title>

</head>

<body>

<h3 title="Hello HTML!">Titled Heading Tag Example</h3>

</body>

</html>

The class Attribute


The class attribute is used to associate an element with a style sheet, and specifies the class of
element. You will learn more about the use of the class attribute when you will learn Cascading
Style Sheet (CSS). So for now you can avoid it.

The value of the attribute may also be a space-separated list of class names. For example:

class="className1"

The style Attribute


The style attribute allows you to specify Cascading Style Sheet (CSS) rules within the element.

Mr. TAFOPA 6-90-83-88-42 15


Academic year 2021/2022
<!DOCTYPE html>

<html>

<head>

<title>The style Attribute</title>

</head>

<body>

<p style="font-family:arial; color:#FF0000;">Some text...</p>

</body>

</html>

This will produce the following result:

Some text...

Generic Attributes
Here's a table of some other attributes that are readily usable with many of the HTML tags.
Attribute Options Function

align right, left, center Horizontally aligns tags

valign top, middle, bottom Vertically aligns tags within an HTML


element.

bgcolor numeric, hexidecimal, RGB Places a background color behind an element


values

background URL Places a background image behind an element

Mr. TAFOPA 6-90-83-88-42 16


Academic year 2021/2022
id User Defined Names an element for use with Cascading
Style Sheets.

class User Defined Classifies an element for use with Cascading


Style Sheets.

width Numeric Value Specifies the width of tables, images, or table


cells.

height Numeric Value Specifies the height of tables, images, or table


cells.

title User Defined "Pop-up" title of the elements.

We will see related examples as we will proceed to study other HTML tags. For a complete list of
HTML Tags and related attributes please check reference to HTML Tags List.

2.5 HTML FORMATING

If you use a word processor, you must be familiar with the ability to make text bold, italicized, or
underlined; these are just three of the ten options available to indicate how text can appear in
HTML and XHTML.

Bold Text

Anything that appears within <b>...</b> element, is displayed in bold as shown below −

Example
<!DOCTYPE html>
<html>

<head>
<title>Bold Text Example</title>
</head>

Mr. TAFOPA 6-90-83-88-42 17


Academic year 2021/2022

<body>
<p>The following word uses a <b>bold</b> typeface.</p>
</body>

</html>

This will produce the following result −

Italic Text

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

Example
<!DOCTYPE html>
<html>

<head>
<title>Italic Text Example</title>
</head>

<body>
<p>The following word uses an <i>italicized</i> typeface.</p>
</body>

</html>

This will produce the following result −

Underlined Text

Anything that appears within <u>...</u> element, is displayed with underline as shown below −

Mr. TAFOPA 6-90-83-88-42 18


Academic year 2021/2022
Example
<!DOCTYPE html>
<html>

<head>
<title>Underlined Text Example</title>
</head>

<body>
<p>The following word uses an <u>underlined</u> typeface.</p>
</body>

</html>

This will produce the following result −

Strike Text

Anything that appears within <strike>...</strike> element is displayed with strikethrough, which
is a thin line through the text as shown below −

Example
<!DOCTYPE html>
<html>

<head>
<title>Strike Text Example</title>
</head>

<body>
<p>The following word uses a <strike>strikethrough</strike> typeface.</p>
</body>

Mr. TAFOPA 6-90-83-88-42 19


Academic year 2021/2022

</html>

This will produce the following result −

The following word uses a strikethrough typeface.

Grouping Content

The <div> and <span> elements allow you to group together several elements to create sections
or subsections of a page.

For example, you might want to put all of the footnotes on a page within a <div> element to
indicate that all of the elements within that <div> element relate to the footnotes. You might
then attach a style to this <div> element so that they appear using a special set of style rules.

Example
<!DOCTYPE html>
<html>

<head>
<title>Div Tag Example</title>
</head>

<body>
<div id = "menu" align = "middle" >
<a href = "/index.htm">HOME</a> |
<a href = "/about/contact_us.htm">CONTACT</a> |
<a href = "/about/index.htm">ABOUT</a>
</div>

<div id = "content" align = "left" >


<h5>Content Articles</h5>

Mr. TAFOPA 6-90-83-88-42 20


Academic year 2021/2022
<p>Actual content goes here.....</p>
</div>
</body>

</html>

This will produce the following result –

HOME | CONTACT | ABOUT

Content Articles

Actual content goes here.....

The <span> element, on the other hand, can be used to group inline elements only. So, if you
have a part of a sentence or paragraph which you want to group together, you could use the
<span> element as follows.

Example
<!DOCTYPE html>
<html>

<head>
<title>Span Tag Example</title>
</head>

<body>
<p>This is the example of <span style = "color:green">span tag</span>
and the <span style = "color:red">div tag</span> alongwith CSS</p>
</body>

Mr. TAFOPA 6-90-83-88-42 21


Academic year 2021/2022
</html>

This will produce the following result –

This is the example of span tag and the div tag alongwith CSS

These tags are commonly used with CSS to allow you to attach a style to a section of a page.

2.6 HTML – IMAGE


Images are very important to beautify as well as to depict many complex concepts in simple way on your
web page. This tutorial will take you through simple steps to use images in your web pages.

Insert Image

You can insert any image in your web page by using <img> tag. Following is the simple syntax
to use this tag.

<img src = "Image URL" ... attributes-list/>

The <img> tag is an empty tag, which means that, it can contain only list of attributes and it has
no closing tag.

Example

To try following example, let's keep our HTML file test.htm and image file test.png in the same
directory −

<!DOCTYPE html>
<html>

<head>
<title>Using Image in Webpage</title>
</head>

<body>

Mr. TAFOPA 6-90-83-88-42 22


Academic year 2021/2022
<p>Simple Image Insert</p>
<img src = "/html/images/test.png" alt = "Test Image" />
</body>

</html>
Simple Image Insert

You can use PNG, JPEG or GIF image file based on your comfort but make sure you specify
correct image file name in src attribute. Image name is always case sensitive.

The alt attribute is a mandatory attribute which specifies an alternate text for an image, if the
image cannot be displayed.

Set Image Width/Height

You can set image width and height based on your requirement using width and height attributes.
You can specify width and height of the image in terms of either pixels or percentage of its actual
size.

Example
<!DOCTYPE html>
<html>

<head>
<title>Set Image Width and Height</title>
</head>

Mr. TAFOPA 6-90-83-88-42 23


Academic year 2021/2022
<body>
<p>Setting image width and height</p>
<img src = "/html/images/test.png" alt = "Test Image" width = "150" height = "100"/>
</body>

</html>

Set Image Border

By default, image will have a border around it, you can specify border thickness in terms of pixels
using border attribute. A thickness of 0 means, no border around the picture.

Example
<!DOCTYPE html>
<html>

<head>
<title>Set Image Border</title>
</head>

<body>
<p>Setting image Border</p>
<img src = "/html/images/test.png" alt = "Test Image" border = "3"/>
</body>

</html>

Set Image Alignment

By default, image will align at the left side of the page, but you can use align attribute to set it in
the center or right.

Mr. TAFOPA 6-90-83-88-42 24


Academic year 2021/2022
Example
<!DOCTYPE html>
<html>

<head>
<title>Set Image Alignment</title>
</head>

<body>
<p>Setting image Alignment</p>
<img src = "/html/images/test.png" alt = "Test Image" border = "3" align = "right"/>
</body>

</html>

2.7 HTML TABLES


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

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

Example

<!DOCTYPE html>
<html>

<head>
<title>HTML Tables</title>
</head>

Mr. TAFOPA 6-90-83-88-42 25


Academic year 2021/2022

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

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

</body>
</html>

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

Mr. TAFOPA 6-90-83-88-42 26


Academic year 2021/2022
below, otherwise you can use <th> element in any row. Headings, which are defined in <th> tag
are centered and bold by default.

Example
<!DOCTYPE html>
<html>

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

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

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

</html>

Mr. TAFOPA 6-90-83-88-42 27


Academic year 2021/2022
This will produce the following result –

Name Salary

Ramesh Raman 5000

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>

Mr. TAFOPA 6-90-83-88-42 28


Academic year 2021/2022
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>

</html>

This will produce the following result –

Name Salary

Ramesh Raman 5000

Shabbir Hussein 7000

Colspan and Rowspan Attributes

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

Example
<!DOCTYPE html>
<html>

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

<body>
<table border = "1">
Mr. TAFOPA 6-90-83-88-42 29
Academic year 2021/2022
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>

</html>

This will produce the following result –

Column 1 Column 2 Column 3

Row 1 Cell 2 Row 1 Cell 3


Row 1 Cell 1
Row 2 Cell 2 Row 2 Cell 3

Row 3 Cell 1

Mr. TAFOPA 6-90-83-88-42 30


Academic year 2021/2022

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>
<table border = "1" width = "100%">
<thead>
<tr>
<td colspan = "4">This is the head of the table</td>
</tr>
</thead>

Mr. TAFOPA 6-90-83-88-42 31


Academic year 2021/2022

<tfoot>
<tr>
<td colspan = "4">This is the foot of the table</td>
</tr>
</tfoot>

<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>

</table>
</body>

</html>

This will produce the following result –

2.8 HTML LIST

Mr. TAFOPA 6-90-83-88-42 32


Academic year 2021/2022
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>

</html>

Mr. TAFOPA 6-90-83-88-42 33


Academic year 2021/2022
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">
Example

Following is an example where we used <ul type = "square">

<!DOCTYPE html>
<html>

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

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

Mr. TAFOPA 6-90-83-88-42 34


Academic year 2021/2022
</ul>
</body>

</html>

This will produce the following result –

 Beetroot
 Ginger
 Potato
 Radish

Example

Following is an example where we used <ul type = "circle">

<!DOCTYPE html>
<html>

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

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

Mr. TAFOPA 6-90-83-88-42 35


Academic year 2021/2022
</html>

This will produce the following result –

o Beetroot
o Ginger
o Potato
o Radish

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>

Mr. TAFOPA 6-90-83-88-42 36


Academic year 2021/2022

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

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

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

<!DOCTYPE html>
<html>

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

<body>
<ol type = "I">

Mr. TAFOPA 6-90-83-88-42 37


Academic year 2021/2022
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>

</html>

This will produce the following result –

I. Beetroot
II. Ginger
III. Potato
IV. Radish

HTML Definition Lists

HTML and XHTML supports a list style which is called definition lists where entries are listed
like in a dictionary or encyclopedia. The definition list is the ideal way to present a glossary, list
of terms, or other name/value list.

Definition List makes use of following three tags.

 <dl> − Defines the start of the list

 <dt> − A term

 <dd> − Term definition

 </dl> − Defines the end of the list

Example
<!DOCTYPE html>
<html>

Mr. TAFOPA 6-90-83-88-42 38


Academic year 2021/2022

<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

2.9 HTML FORMS

HTML Forms are required, when you want to collect some data from the site visitor. For example,
during user registration you would like to collect information such as name, email address, credit
card, etc.

Mr. TAFOPA 6-90-83-88-42 39


Academic year 2021/2022
A form will take input from the site visitor and then will post it to a back-end application such as
CGI, ASP Script or PHP script etc. The back-end application will perform required processing
on the passed data based on defined business logic inside the application.

There are various form elements available like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.

The HTML <form> tag is used to create an HTML form and it has following syntax −

<form action = "Script URL" method = "GET|POST">


form elements like input, textarea etc.
</form>

Form Attributes

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

Sr.No Attribute & Description

1
action

Backend script ready to process your passed data.

2
method

Method to be used to upload data. The most frequently used are GET and POST methods.

3
target

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

Mr. TAFOPA 6-90-83-88-42 40


Academic year 2021/2022
4
enctype

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

application/x-www-form-urlencoded − This is the standard method most forms use in


simple scenarios.

mutlipart/form-data − This is used when you want to upload binary data in the form of
files like image, word file etc.

Note − You can refer to Perl & CGI for a detail on how form data upload works.

HTML Form Controls

There are different types of form controls that you can use to collect data using HTML form −

 Text Input Controls

 Checkboxes Controls

 Radio Box Controls

 Select Box Controls

 File Select boxes

 Hidden Controls

 Clickable Buttons

 Submit and Reset Button

Text Input Controls

There are three types of text input used on forms −

 Single-line text input controls − This control is used for items that require only one line
of user input, such as search boxes or names. They are created using HTML <input> tag.

Mr. TAFOPA 6-90-83-88-42 41


Academic year 2021/2022
 Password input controls − This is also a single-line text input but it masks the character
as soon as a user enters it. They are also created using HTMl <input> tag.

 Multi-line text input controls − This is used when the user is required to give details that
may be longer than a single sentence. Multi-line input controls are created using
HTML <textarea> tag.

Single-line text input controls

This control is used for items that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.

Example

Here is a basic example of a single-line text input used to take first name and last name −

<!DOCTYPE html>
<html>

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

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

</html>

This will produce the following result −

Mr. TAFOPA 6-90-83-88-42 42


Academic year 2021/2022
Attributes

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

Sr.No Attribute & Description

1
type

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

2
name

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

3
value

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

4
size

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

5
maxlength

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

Password input controls

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

Mr. TAFOPA 6-90-83-88-42 43


Academic year 2021/2022
Example

Here is a basic example of a single-line password input used to take user password −

<!DOCTYPE html>
<html>

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

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

</html>

Attributes

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

Sr.No Attribute & Description

1
type

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

Mr. TAFOPA 6-90-83-88-42 44


Academic year 2021/2022
2
name

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

3
value

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

4
size

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

5
maxlength

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

Multiple-Line Text Input Controls

This is used when the user is required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.

Example

Here is a basic example of a multi-line text input used to take item description −

<!DOCTYPE html>
<html>

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

Mr. TAFOPA 6-90-83-88-42 45


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

</html>

This will produce the following result −

Attributes

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

Sr.No Attribute & Description

1
name

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

2
rows

Indicates the number of rows of text area box.

Mr. TAFOPA 6-90-83-88-42 46


Academic year 2021/2022
3
cols

Indicates the number of columns of text area box

Checkbox Control

Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox..

Example

Here is an example HTML code for a form with two checkboxes −

<!DOCTYPE html>
<html>

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

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

</html>

Attributes

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

Mr. TAFOPA 6-90-83-88-42 47


Academic year 2021/2022
Sr.No Attribute & Description

1
type

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

2
name

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

3
value

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

4
checked

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

Radio Button Control

Radio buttons are used when out of many options, just one option is required to be selected. They
are also created using HTML <input> tag but type attribute is set to radio.

Example

Here is example HTML code for a form with two radio buttons −

<!DOCTYPE html>
<html>

<head>

Mr. TAFOPA 6-90-83-88-42 48


Academic year 2021/2022
<title>Radio Box Control</title>
</head>

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

</html>

Attributes

Following is the list of attributes for radio button.

Sr.No Attribute & Description

1
type

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

2
name

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

3
value

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

Mr. TAFOPA 6-90-83-88-42 49


Academic year 2021/2022
4
checked

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

Select Box Control

A select box, also called drop down box which provides option to list down various options in the
form of drop down list, from where a user can select one or more options.

Example

Here is example HTML code for a form with one drop down box

<!DOCTYPE html>
<html>

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

<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>

</html>

Attributes

Mr. TAFOPA 6-90-83-88-42 50


Academic year 2021/2022
Following is the list of important attributes of <select> tag −

Sr.No Attribute & Description

1
name

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

2
size

This can be used to present a scrolling list box.

3
multiple

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

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

Sr.No Attribute & Description

1
value

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

2
selected

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

3
label

An alternative way of labeling options

Mr. TAFOPA 6-90-83-88-42 51


Academic year 2021/2022
File Upload Box

If you want to allow a user to upload a file to your web site, you will need to use a file upload
box, also known as a file select box. This is also created using the <input> element but type
attribute is set to file.

Example

Here is example HTML code for a form with one file upload box −

<!DOCTYPE html>
<html>

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

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

</html>

Attributes

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

Sr.No Attribute & Description

Mr. TAFOPA 6-90-83-88-42 52


Academic year 2021/2022
1
name

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

2
accept

Specifies the types of files that the server accepts.

Button Controls

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

Sr.No Type & Description

1
submit

This creates a button that automatically submits a form.

2
reset

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

3
button

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

Mr. TAFOPA 6-90-83-88-42 53


Academic year 2021/2022
4
image

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

Example

Here is example HTML code for a form with three types of buttons −

<!DOCTYPE html>
<html>

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

<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>

</html>

Hidden Form Controls

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

Mr. TAFOPA 6-90-83-88-42 54


Academic year 2021/2022
page then the value of hidden control will be sent to the web server and there it will decide which
page will be displayed next based on the passed current page.

Example

Here is example HTML code to show the usage of hidden control −

<!DOCTYPE html>
<html>

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

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

</html>

Mr. TAFOPA 6-90-83-88-42 55


Academic year 2021/2022

CHAPTER THREE: CSS


3.1 OVERVIEW
What is CSS?
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify
the process of making web pages presentable. CSS handles the look and feel part of a web page. Using
CSS, you can control the color of the text, the style of fonts, the spacing between paragraphs, how
columns are sized and laid out, what background images or colors are used, as well as a variety of
other effects. CSS is easy to learn and understand but it provides a powerful control over the
presentation of an HTML document. Most commonly, CSS is combined with the markup languages
HTML or XHTML.
Advantages of CSS
 CSS saves time: You can write CSS once and then reuse the 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.
Mr. TAFOPA 6-90-83-88-42 56
Academic year 2021/2022
 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. Therefore,
less code means faster download times.
 Easy maintenance: To make a global change, simply change the style, and all the 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 cellphones or for printing.
 Global web standards: Now HTML attributes are being deprecated and it is being
recommended to use CSS. So it’s a good idea to start using CSS in all the HTML pages to
make them compatible with future browsers

3.2 CSS SYNTAX


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 the value
either red or #F1F1F1 etc.

You can put CSS Style Rule Syntax as follows:

selector { property: value }

Mr. TAFOPA 6-90-83-88-42 57


Academic year 2021/2022
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 the 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

We have seen above this same selector. 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

Mr. TAFOPA 6-90-83-88-42 58


Academic year 2021/2022
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, the style rule will apply to <em> element only when
it lies inside the <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;


}

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

Mr. TAFOPA 6-90-83-88-42 59


Academic year 2021/2022
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
within 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;


}

Mr. TAFOPA 6-90-83-88-42 60


Academic year 2021/2022
This rule will render all the paragraphs in black if they are a direct child of the <body> element.
Other paragraphs put inside other elements like <div> or <td> would not have any effect of this
rule.

Grouping Selectors

You can apply a style to many selectors if you like. Just separate the selectors with a comma, as
given in the following example:

h1, h2, h3 { color: #36C; font-weight: normal; letter-spacing:


.4em; margin-bottom: 1em; text-transform: lowercase;
}

This define style rule will be applicable to h1, h2 and h3 element as well. The order of the list is
irrelevant. All the elements in the selector will have the corresponding declarations applied to
them.

You can combine the various class selectors together as shown below:

#content, #footer, #supplement { position: absolute; left: 510px;


width: 200px;
}

3.3 CSS INCLUSION


There are four ways to associate styles with your HTML document. Most commonly used methods
are inline CSS and External CSS.

1. Embedded CSS - The <style> Element

Mr. TAFOPA 6-90-83-88-42 61


Academic year 2021/2022
You can put your CSS rules into an HTML document using the <style> element. This tag is placed
inside the <head>...</head> tags. Rules defined using this syntax will be applied to all the elements
available in the document. Here is the generic syntax:

<head>

<style type="text/css" media="...">

Style Rules

............

</style>

</head>

Attributes

Attributes associated with <style> elements are:

Attribute Value Description

type text/css Specifies the style sheet language as a content-type


(MIME type). This is a required attribute.

media screen tty Specifies the device, the document will be displayed on.
tv Default value is all. This is an optional attribute.
projection
handheld
print
braille

aural
all

Mr. TAFOPA 6-90-83-88-42 62


Academic year 2021/2022
Example

Following is an example of embed CSS based on the above syntax:

<head>

<style type="text/css" media="all"> h1{ color: #36C; }


</style>

</head>

2. Inline CSS - The style Attribute

You can use style attribute of any HTML element to define style rules. These rules will be applied
to that element only. Here is the generic syntax:

<element style="...style rules....">

Attributes

Attribute Value Description

style style The value of style attribute is a combination of style declarations


rules separated by semicolon (;).

Example

Following is the example of inline CSS based on the above syntax:

<h1 style ="color:#36C;"> This is inline CSS </h1>

It will produce the following result:

Mr. TAFOPA 6-90-83-88-42 63


Academic year 2021/2022
This is inline CSS

3. External CSS - The <link> Element

The <link> element can be used to include an external stylesheet file in your HTML document.

An external style sheet is a separate text file with .css extension. You define all the Style rules
within this text file and then you can include this file in any HTML document using <link>
element.

Here is the generic syntax of including external CSS file:

<head>

<link type="text/css" href="..." media="..." />

</head>

Attributes

Attributes associated with <style> elements are:

Attribute Value Description

type text/css Specifies the style sheet language as a content-type (MIME type).
This attribute is required.

Mr. TAFOPA 6-90-83-88-42 64


Academic year 2021/2022
href URL Specifies the style sheet file having Style rules. This attribute is a
required.

media screen tty Specifies the device the document will be displayed on. Default
tv value is all. This is an optional attribute.
projection
handheld
print
braille

aural

all

Example

Consider a simple style sheet file with a name mystyle.css having the following rules:

h1, h2, h3 { color: #36C; font-weight: normal; letter-spacing:


.4em; margin-bottom: 1em; text-transform: lowercase;
}

Now you can include this file mystyle.css in any HTML document as follows:

<head>

<link type="text/css" href="mystyle.css" media="all" />

</head>

Mr. TAFOPA 6-90-83-88-42 65


Academic year 2021/2022
4. Imported CSS - @import Rule

@import is used to import an external stylesheet in a manner similar to the <link> element. Here
is the generic syntax of @import rule.

<head>

<@import "URL";

</head>

Here URL is the URL of the style sheet file having style rules. You can use another syntax as well:

<head>

<@import url("URL");

</head>

Example

Following is the example showing you how to import a style sheet file into an HTML document:

<head>

@import "mystyle.css";

</head>

CSS Comments

Many times, you may need to put additional comments in your style sheet blocks. So, it is very
easy to comment any part in the style sheet. You can simply put your comments inside /*.....this is
a comment in style sheet.....*/.

Mr. TAFOPA 6-90-83-88-42 66


Academic year 2021/2022
You can use /* ....*/ to comment multi-line blocks in similar way you do in C and C++
programming languages.

Example

/* This is an external style sheet file */ h1, h2, h3 { color: #36C; font-weight: normal; letter-
spacing: .4em; margin-bottom: 1em; text-transform: lowercase;
}

/* end of style rules. */

3.4 CSS MEASUREMENT UNITS


Before we start the actual exercise, we would like to give a brief idea about the CSS
Measurement Units. CSS supports a number of measurements including absolute
units such as inches, centimeters, points, and so on, as well as relative measures
such as percentages and em units. You need these values while specifying various
measurements in your Style rules e.g. border="1px solid red".

We have listed out all the CSS Measurement Units along with proper Examples:
Unit Description Example

Defines a measurement as a p {font-size: 16pt; line-height:


% percentage relative to another value,
typically an enclosing element. 125%;}

cm Defines a measurement in div {margin-bottom: 2cm;}


centimeters.

em A relative measurement for the height p {letter-spacing: 7em;}


of a font in em spaces. Because an em
unit is equivalent to the size of a given
font, if you assign a font to 12pt, each
"em" unit would be 12pt; thus, 2em
would be 24pt.

Mr. TAFOPA 6-90-83-88-42 67


Academic year 2021/2022
ex This value defines a measurement p {font-size: 24pt; line-height:
relative to a font's x-height. The x-
3ex;}
height is determined by the height of
the font's lowercase letter x.

in Defines a measurement in inches. p {word-spacing: .15in;}

mm Defines a measurement in p {word-spacing: 15mm;}


millimeters.

pc Defines a measurement in picas. A p {font-size: 20pc;}


pica is equivalent to 12 points; thus,
there are 6 picas per inch.

pt Defines a measurement in points. A body {font-size: 18pt;}


point is defined as 1/72nd of an inch.

px Defines a measurement in screen p {padding: 25px;}


pixels.

Mr. TAFOPA 6-90-83-88-42 68


Academic year 2021/2022
3.5 COLORS
CSS uses color values to specify a color. Typically, these are used to set a color either for the
foreground of an element (i.e., its text) or else for the background of the element. They can also
be used to affect the color of borders and other decorative effects.

You can specify your color values in various formats. Following table lists all the possible formats

Format Syntax Example

Hex Code #RRGGBB p{color:#FF0000;}

Short Hex Code #RGB p{color:#6A7;}

RGB % rgb(rrr%,ggg%,bbb%) p{color:rgb(50%,50%,50%);}

RGB Absolute rgb(rrr,ggg,bbb) p{color:rgb(0,0,255);}

keyword aqua, black, etc. p{color:teal;}

These formats are explained in more detail in the following sections −

CSS 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, Jasc
Paintshop Pro, or even using Advanced Paint Brush.

Each hexadecimal code will be preceded by a pound or hash sign '#'. Following are the examples
to use Hexadecimal notation.

Mr. TAFOPA 6-90-83-88-42 69


Academic year 2021/2022
Color Color HEX

#000000

#FF0000

#00FF00

#0000FF

#FFFF00

#00FFFF

#FF00FF

#C0C0C0

#FFFFFF

Mr. TAFOPA 6-90-83-88-42 70


Academic year 2021/2022

CHAPTER FOUR: JAVA SCRIPT

OVERVIEW

What is JavaScript ?

JavaScript is a dynamic computer programming language. It is lightweight and most commonly


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

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

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

 JavaScript is a lightweight, interpreted programming language.

 Designed for creating network-centric applications.

 Complementary to and integrated with Java.

 Complementary to and integrated with HTML.

 Open and cross-platform

Client-Side JavaScript

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

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

Mr. TAFOPA 6-90-83-88-42 71


Academic year 2021/2022
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail
address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.

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

Advantages of JavaScript

The merits of using JavaScript are:

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

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

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

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

Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the following


important features −

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

 JavaScript cannot be used for networking applications because there is no such support
available.

Mr. TAFOPA 6-90-83-88-42 72


Academic year 2021/2022
 JavaScript doesn't have any multi-threading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.

SYNTAX

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

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

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

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

The script tag takes two important attributes

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

 Type − This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".

So your JavaScript segment will look like −

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


JavaScript code
</script>
Example
<html>

Mr. TAFOPA 6-90-83-88-42 73


Academic year 2021/2022
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result −
Hello World!

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

JavaScript in Internet Explorer

Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −

 Follow Tools → Internet Options from the menu.

 Select Security tab from the dialog box.

 Click the Custom Level button.

 Scroll down till you find Scripting option.

 Select Enable radio button under Active scripting.

 Finally click OK and come out

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

JavaScript in Firefox

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

Mr. TAFOPA 6-90-83-88-42 74


Academic year 2021/2022
 Open a new tab → type about: config in the address bar.

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

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

 In the search bar, type javascript.enabled.

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

If JavaScript Enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it
gets enabled upon clicking toggle.

JavaScript in Chrome

Here are the steps to turn on or turn off JavaScript in Chrome −

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

 Select Settings.

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

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

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

PLACEMENT

There is a flexibility given to include JavaScript code anywhere in an HTML document. However
the most preferred ways to include JavaScript in an HTML file are as follows −

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

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

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

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

Mr. TAFOPA 6-90-83-88-42 75


Academic year 2021/2022
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.

JavaScript in <head>...</head> section

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

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

<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

JavaScript in <body>...</body> section

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

<html>

Mr. TAFOPA 6-90-83-88-42 76


Academic year 2021/2022
<head>
</head>

<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<p>This is web page body </p>


</body>
</html>

JavaScript in <body> and <head> Sections

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

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

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

Mr. TAFOPA 6-90-83-88-42 77


Academic year 2021/2022
<!--
document.write("Hello World")
//-->
</script>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />


</body>
</html>

JavaScript in External File

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

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

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

<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>

<body>
.......
</body>
</html>

Mr. TAFOPA 6-90-83-88-42 78


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

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

function sayHello() {
alert("Hello World")
}

VARIABLES

Variables are containers for storing data (values).

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

<script type = "text/javascript">


<!--
var money;
var name;
//-->
</script>

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

<script type = "text/javascript">


<!--
var money, name;
//-->
</script>

Mr. TAFOPA 6-90-83-88-42 79


Academic year 2021/2022
Storing a value in a variable is called variable initialization.

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

<script type = "text/javascript">


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

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

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.

JavaScript Variable Scope

The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.

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

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

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

Mr. TAFOPA 6-90-83-88-42 80


Academic year 2021/2022

<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>

This produces the following result −

local

JavaScript Variable Names

While naming your variables in JavaScript, keep the following rules in mind.

 You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.

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

 JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.

Mr. TAFOPA 6-90-83-88-42 81


Academic year 2021/2022
JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the following table. They cannot be used
as JavaScript variables, functions, methods, loop labels, or any object names.

abstract else instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

Mr. TAFOPA 6-90-83-88-42 82


Academic year 2021/2022
default if return volatile

delete implements short while

do import static with

double in super

OPERATORS

What is an Operator?

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

 Arithmetic Operators

 Comparison Operators

 Logical (or Relational) Operators

 Assignment Operators

 Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators

JavaScript supports the following arithmetic operators −

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

Mr. TAFOPA 6-90-83-88-42 83


Academic year 2021/2022
Sr.No. Operator & Description

1
+ (Addition)

Adds two operands

Ex: A + B will give 30

2
- (Subtraction)

Subtracts the second operand from the first

Ex: A - B will give -10

3
* (Multiplication)

Multiply both operands

Ex: A * B will give 200

4
/ (Division)

Divide the numerator by the denominator

Ex: B / A will give 2

5
% (Modulus)

Outputs the remainder of an integer division

Ex: B % A will give 0

Mr. TAFOPA 6-90-83-88-42 84


Academic year 2021/2022
6
++ (Increment)

Increases an integer value by one

Ex: A++ will give 11

7
-- (Decrement)

Decreases an integer value by one

Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

Example

The following code shows how to use arithmetic operators in JavaScript.

<html>
<body>

<script type = "text/javascript">


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

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");

Mr. TAFOPA 6-90-83-88-42 85


Academic year 2021/2022
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);

Mr. TAFOPA 6-90-83-88-42 86


Academic year 2021/2022
//-->
</script>

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


</body>
</html>

Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...

Comparison Operators

JavaScript supports the following comparison operators −

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

Sr.No. Operator & Description

1
= = (Equal)

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

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

Mr. TAFOPA 6-90-83-88-42 87


Academic year 2021/2022
2
!= (Not Equal)

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

Ex: (A != B) is true.

3
> (Greater than)

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

Ex: (A > B) is not true.

4
< (Less than)

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

Ex: (A < B) is true.

5
>= (Greater than or Equal to)

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

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

6
<= (Less than or Equal to)

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

Ex: (A <= B) is true.

Mr. TAFOPA 6-90-83-88-42 88


Academic year 2021/2022
Example

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

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

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

Mr. TAFOPA 6-90-83-88-42 89


Academic year 2021/2022

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and different operators and then try...
</body>
</html>

Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...

Logical Operators

JavaScript supports the following logical operators −

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

Mr. TAFOPA 6-90-83-88-42 90


Academic year 2021/2022
Sr.No. Operator & Description

1
&& (Logical AND)

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

Ex: (A && B) is true.

2
|| (Logical OR)

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

Ex: (A || B) is true.

3
! (Logical NOT)

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

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

Example

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

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

document.write("(a && b) => ");

Mr. TAFOPA 6-90-83-88-42 91


Academic year 2021/2022
result = (a && b);
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...

Bitwise Operators

JavaScript supports the following bitwise operators −

Assume variable A holds 2 and variable B holds 3, then −

Mr. TAFOPA 6-90-83-88-42 92


Academic year 2021/2022
Sr.No. Operator & Description

1
& (Bitwise AND)

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

Ex: (A & B) is 2.

2
| (BitWise OR)

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

Ex: (A | B) is 3.

3
^ (Bitwise XOR)

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


Exclusive OR means that either operand one is true or operand two is true, but not
both.

Ex: (A ^ B) is 1.

4
~ (Bitwise Not)

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

Ex: (~B) is -4.

5
<< (Left Shift)

It moves all the bits in its first operand to the left by the number of places specified in
the second operand. New bits are filled with zeros. Shifting a value left by one position

Mr. TAFOPA 6-90-83-88-42 93


Academic year 2021/2022
is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying
by 4, and so on.

Ex: (A << 1) is 4.

6
>> (Right Shift)

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

Ex: (A >> 1) is 1.

7
>>> (Right shift with Zero)

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

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

Example

Try the following code to implement Bitwise operator in JavaScript.

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

document.write("(a & b) => ");


result = (a & b);
document.write(result);

Mr. TAFOPA 6-90-83-88-42 94


Academic year 2021/2022
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>

Mr. TAFOPA 6-90-83-88-42 95


Academic year 2021/2022
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

Assignment Operators

JavaScript supports the following assignment operators −

Sr.No. Operator & Description

1
= (Simple Assignment )

Assigns values from the right side operand to the left side operand

Ex: C = A + B will assign the value of A + B into C

2
+= (Add and Assignment)

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

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

3
−= (Subtract and Assignment)

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

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

Mr. TAFOPA 6-90-83-88-42 96


Academic year 2021/2022
4
*= (Multiply and Assignment)

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

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

5
/= (Divide and Assignment)

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

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

6
%= (Modules and Assignment)

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

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

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

Example

Try the following code to implement assignment operator in JavaScript.

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

Mr. TAFOPA 6-90-83-88-42 97


Academic year 2021/2022
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);
//-->

Mr. TAFOPA 6-90-83-88-42 98


Academic year 2021/2022
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

Miscellaneous Operator

We will discuss two operators here that are quite useful in JavaScript: the conditional operator (?
:) and the typeof operator.

Conditional Operator (? :)

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

Sr.No. Operator and Description

1
? : (Conditional )

If Condition is true? Then value X : Otherwise value Y

Example

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

<html>

Mr. TAFOPA 6-90-83-88-42 99


Academic year 2021/2022
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

typeof Operator

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

Mr. TAFOPA 6-90-83-88-42 100


Academic year 2021/2022
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.

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

Type String Returned by typeof

Number "number"

String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

Example

The following code shows how to implement typeof operator.

<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;

Mr. TAFOPA 6-90-83-88-42 101


Academic year 2021/2022
var b = "String";
var linebreak = "<br />";

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


document.write("Result => ");
document.write(result);
document.write(linebreak);

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


document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...

JavaScript if else statements

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

 if statement

 if...else statement

 if...else if... statement.

Mr. TAFOPA 6-90-83-88-42 102


Academic year 2021/2022
1. If statement

The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.

Syntax

The syntax for a basic if statement is as follows −

if (expression) {
Statement(s) to be executed if expression is true
}

Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be not executed. Most of the times,
you will use comparison operators while making decisions.

Example

Try the following example to understand how the if statement works.

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

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Mr. TAFOPA 6-90-83-88-42 103


Academic year 2021/2022
2. if...else statement

The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.

Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block
are executed.

Example

Try the following code to learn how to implement an if-else statement in JavaScript.

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

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>

Mr. TAFOPA 6-90-83-88-42 104


Academic year 2021/2022
</body>
</html>

3. if...else if... statement

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.

Syntax

The syntax of an if-else-if statement is as follows −

if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}

There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true condition,
if none of the conditions is true, then the else block is executed.

Example

Try the following code to learn how to implement an if-else-if statement in JavaScript.

<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";

Mr. TAFOPA 6-90-83-88-42 105


Academic year 2021/2022
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

Javascript switch case

Flow Chart

The following flow chart explains a switch-case statement works.

Mr. TAFOPA 6-90-83-88-42 106


Academic year 2021/2022

Syntax

The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.

switch (expression) {
case condition 1: statement(s)
break;

case condition 2: statement(s)


break;
...

case condition n: statement(s)

Mr. TAFOPA 6-90-83-88-42 107


Academic year 2021/2022
break;

default: statement(s)
}

The break statements indicate the end of a particular case. If they were omitted, the interpreter
would continue executing each statement in each of the following cases.

We will explain break statement in Loop Control chapter.

Example

Try the following example to implement switch-case statement.

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;

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


break;

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


break;

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


break;

Mr. TAFOPA 6-90-83-88-42 108


Academic year 2021/2022
case 'F': document.write("Failed<br />");
break;

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


}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...

Break statements play a major role in switch-case statements. Try the following code that uses
switch-case statement without any break statement.

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");

Mr. TAFOPA 6-90-83-88-42 109


Academic year 2021/2022
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

JavaScript – events

What is an Event ?

JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.

Please go through this small tutorial for a better understanding HTML Event Reference. Here we
will see a few examples to understand a relation between Event and JavaScript −

onclick Event Type

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

Mr. TAFOPA 6-90-83-88-42 110


Academic year 2021/2022
Example

Try the following example.

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

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

Output

onsubmit Event Type

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

Mr. TAFOPA 6-90-83-88-42 111


Academic year 2021/2022
Example

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

Try the following example.

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

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

onmouseover and onmouseout

These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and

Mr. TAFOPA 6-90-83-88-42 112


Academic year 2021/2022
the onmouseout triggers when you move your mouse out from that element. Try the following
example.

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

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

Output

HTML 5 Standard Events

The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript
function to be executed against that event.

Mr. TAFOPA 6-90-83-88-42 113


Academic year 2021/2022
Attribute Value Description

Offline script Triggers when the document goes offline

Onabort script Triggers on an abort event

onafterprint script Triggers after the document is printed

onbeforeonload script Triggers before the document loads

onbeforeprint script Triggers before the document is printed

onblur script Triggers when the window loses focus

Triggers when media can start play, but might has to stop for
oncanplay script
buffering

Triggers when media can be played to the end, without stopping


oncanplaythrough script
for buffering

onchange script Triggers when an element changes

onclick script Triggers on a mouse click

oncontextmenu script Triggers when a context menu is triggered

Mr. TAFOPA 6-90-83-88-42 114


Academic year 2021/2022
ondblclick script Triggers on a mouse double-click

ondrag script Triggers when an element is dragged

ondragend script Triggers at the end of a drag operation

ondragenter script Triggers when an element has been dragged to a valid drop target

Triggers when an element is being dragged over a valid drop


ondragleave script
target

ondragover script Triggers at the start of a drag operation

ondragstart script Triggers at the start of a drag operation

ondrop script Triggers when dragged element is being dropped

ondurationchange script Triggers when the length of the media is changed

Triggers when a media resource element suddenly becomes


onemptied script
empty.

onended script Triggers when media has reach the end

onerror script Triggers when an error occur

Mr. TAFOPA 6-90-83-88-42 115


Academic year 2021/2022
onfocus script Triggers when the window gets focus

onformchange script Triggers when a form changes

onforminput script Triggers when a form gets user input

onhaschange script Triggers when the document has change

oninput script Triggers when an element gets user input

oninvalid script Triggers when an element is invalid

onkeydown script Triggers when a key is pressed

onkeypress script Triggers when a key is pressed and released

onkeyup script Triggers when a key is released

onload script Triggers when the document loads

onloadeddata script Triggers when media data is loaded

Triggers when the duration and other media data of a media


onloadedmetadata script
element is loaded

Mr. TAFOPA 6-90-83-88-42 116


Academic year 2021/2022
onloadstart script Triggers when the browser starts to load the media data

onmessage script Triggers when the message is triggered

onmousedown script Triggers when a mouse button is pressed

onmousemove script Triggers when the mouse pointer moves

onmouseout script Triggers when the mouse pointer moves out of an element

onmouseover script Triggers when the mouse pointer moves over an element

onmouseup script Triggers when a mouse button is released

onmousewheel script Triggers when the mouse wheel is being rotated

onoffline script Triggers when the document goes offline

onoine script Triggers when the document comes online

ononline script Triggers when the document comes online

onpagehide script Triggers when the window is hidden

Mr. TAFOPA 6-90-83-88-42 117


Academic year 2021/2022
onpageshow script Triggers when the window becomes visible

onpause script Triggers when media data is paused

onplay script Triggers when media data is going to start playing

onplaying script Triggers when media data has start playing

onpopstate script Triggers when the window's history changes

onprogress script Triggers when the browser is fetching the media data

onratechange script Triggers when the media data's playing rate has changed

onreadystatechange script Triggers when the ready-state changes

onredo script Triggers when the document performs a redo

onresize script Triggers when the window is resized

onscroll script Triggers when an element's scrollbar is being scrolled

Triggers when a media element's seeking attribute is no longer


onseeked script
true, and the seeking has ended

Mr. TAFOPA 6-90-83-88-42 118


Academic year 2021/2022
Triggers when a media element's seeking attribute is true, and the
onseeking script
seeking has begun

onselect script Triggers when an element is selected

onstalled script Triggers when there is an error in fetching media data

onstorage script Triggers when a document loads

onsubmit script Triggers when a form is submitted

Triggers when the browser has been fetching media data, but
onsuspend script
stopped before the entire media file was fetched

ontimeupdate script Triggers when media changes its playing position

onundo script Triggers when a document performs an undo

onunload script Triggers when the user leaves the document

Triggers when media changes the volume, also when volume is


onvolumechange script
set to "mute"

Triggers when media has stopped playing, but is expected to


onwaiting script
resume

Mr. TAFOPA 6-90-83-88-42 119


Academic year 2021/2022

JavaScript cookies

What are Cookies ?

Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol.
But for a commercial website, it is required to maintain session information among different
pages. For example, one user registration ends after completing many pages. But how to maintain
users' session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor experience
or site statistics.

How It Works ?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

Cookies are a plain text data record of 5 variable-length fields −

 Expires − The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.

 Domain − The domain name of your site.

 Path − The path to the directory or web page that set the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.

 Secure − If this field contains the word "secure", then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.

 Name=Value − Cookies are set and retrieved in the form of key-value pairs

Mr. TAFOPA 6-90-83-88-42 120


Academic year 2021/2022
Cookies were originally designed for CGI programming. The data contained in a cookie is
automatically transmitted between the web browser and the web server, so CGI scripts on the
server can read and write cookie values that are stored on the client.

JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

Storing Cookies

The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.

document.cookie = "key1 = value1;key2 = value2;expires = date";

Here the expires attribute is optional. If you provide this attribute with a valid date or time, then
the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.

Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.

Example

Try the following. It sets a customer name in an input cookie.

<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;

Mr. TAFOPA 6-90-83-88-42 121


Academic year 2021/2022
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>

<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>

Output

Now your machine has a cookie called name. You can set multiple cookies using multiple key =
value pairs separated by comma.

Reading Cookies

Reading a cookie is just as simple as writing one, because the value of the document.cookie object
is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.

You can use strings' split() function to break a string into key and values as follows −

Example

Try the following example to get all the cookies.

Mr. TAFOPA 6-90-83-88-42 122


Academic year 2021/2022
<html>
<head>
<script type = "text/javascript">
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );

// Get all the cookies pairs in an array


cookiearray = allcookies.split(';');

// Now take key value pair out of this array


for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>

<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>

Mr. TAFOPA 6-90-83-88-42 123


Academic year 2021/2022
Note − Here length is a method of Array class which returns the length of an array. We will
discuss Arrays in a separate chapter. By that time, please try to digest it.

Note − There may be some other cookies already set on your machine. The above code will
display all the cookies set on your machine.

Setting Cookies Expiry Date

You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting
the ‘expires’ attribute to a date and time.

Example

Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.

<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>

Mr. TAFOPA 6-90-83-88-42 124


Academic year 2021/2022
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

Output

Deleting a Cookie

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return
nothing. To do this, you just need to set the expiry date to a time in the past.

Example

Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
month behind the current date.

Live Demo

<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"

document.cookie = "name=" + cookievalue;


document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );

Mr. TAFOPA 6-90-83-88-42 125


Academic year 2021/2022
}
//-->
</script>
</head>

<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

JavaScript page redirect

What is Page Redirection ?

You might have encountered a situation where you clicked a URL to reach a page X but internally
you were directed to another page Y. It happens due to page redirection. This concept is different
from JavaScript Page Refresh.

There could be various reasons why you would like to redirect a user from the original page. We
are listing down a few of the reasons −

 You did not like the name of your domain and you are moving to a new one. In such a
scenario, you may want to direct all your visitors to the new site. Here you can maintain
your old domain but put a single page with a page redirection such that all your old domain
visitors can come to your new domain.

 You have built-up various pages based on browser versions or their names or may be based
on different countries, then instead of using your server-side page redirection, you can use
client-side page redirection to land your users on the appropriate page.

Mr. TAFOPA 6-90-83-88-42 126


Academic year 2021/2022
 The Search Engines may have already indexed your pages. But while moving to another
domain, you would not like to lose your visitors coming through search engines. So you
can use client-side page redirection. But keep in mind this should not be done to fool the
search engine, it could lead your site to get banned.

How Page Re-direction Works ?

The implementations of Page-Redirection are as follows.

Example 1

It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors
to a new page, you just need to add a line in your head section as follows.

<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
//-->
</script>
</head>

<body>
<p>Click the following button, you will be redirected to home page.</p>

<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>

</body>

Mr. TAFOPA 6-90-83-88-42 127


Academic year 2021/2022
</html>

Example 2

You can show an appropriate message to your site visitors before redirecting them to a new page.
This would need a bit time delay to load a new page. The following example shows how to
implement the same. Here setTimeout() is a built-in JavaScript function which can be used to
execute another function after a given time interval.

<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

<body>
</body>
</html>

Output
You will be redirected to tutorialspoint.com main page in 10 seconds!
Example 3

The following example shows how to redirect your site visitors onto a different page based on
their browsers.

<html>

Mr. TAFOPA 6-90-83-88-42 128


Academic year 2021/2022
<head>
<script type = "text/javascript">
<!--
var browsername = navigator.appName;
if( browsername == "Netscape" ) {
window.location = "http://www.location.com/ns.htm";
} else if ( browsername =="Microsoft Internet Explorer") {
window.location = "http://www.location.com/ie.htm";
} else {
window.location = "http://www.location.com/other.htm";
}
//-->
</script>
</head>

<body>
</body>
</html>

Mr. TAFOPA 6-90-83-88-42 129

You might also like