0% found this document useful (0 votes)
46 views274 pages

Unit 1 & 2 Web Design - MGT

Uploaded by

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

Unit 1 & 2 Web Design - MGT

Uploaded by

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

Unit I

1 1 Web Site Basics

Syllabus
Web Essentials : Clients, Servers, and Communication. The Internet-Basic Internet Protocols -The
World Wide Web-HTTP request message-response message-Web Clients Web Servers.

Contents
1.1 Web Essentials
1.2 Internet Protoco........................................................ Dec.-09,11, May-14, ............ Marks 8
1.3 HTTP Request and Response Message.................. June-09, May-12, 13,14,
................................................................................. Dec.-12, 13 ........................... Marks 8
1.4 Features of HTTP Protocol
1.5 Web Clients ............................................................. Dec.-11, ............................... Marks 8
1.6 Web Server .............................................................. May-10,12,13 ..................... Marks 12
1.7 Client, Sever and Communication
Two Marks Questions with Answers

(1 - 1)
Web Technology 1-2 Web Site Basics

1.1 Web Essentials

1.1.1 What is Web Technology?


 Web technology is a technology that acts as an interface between web client and web server. It
includes markup languages, programming interfaces, online presentation tools, Java applets,
video editing tools and so on.
 The commonly used client side scripting languages are HTML, JavaScript, CSS, XML and so
on.
 The commonly used server side technologies are ASP, JSP, Java Servlets, PHP and so on.

1.1.2 Concept of Internet

Definition : Internet is global system in which millions of computers are connected together. It is
basically a network of networks.

 Using internet many people can share resources and can communicate with each other. To have
internet service one must go to the service providers. That means your computer must be
connected to the Internet Service Providers (ISP) through phone-line modem or DSL.
 There are some privately owned internet service providers from which we can hire the internet
services.

1.1.3 Concept of World Wide Web

Definition : World Wide Web (WWW) is collections of software and corresponding protocols used to
access the resources over the network.

 The world wide web is a information system in which various documents containing
information are interlinked together. User can access this information or write the information
via computers. This information is typically stored on the web pages and through web browsers
we can access these web pages.
 The web pages may contain the information in the form of text, audio, video, images and
graphics. We can navigate between the web pages using hyperlinks.
 The concept of WWW was introduced by Sir Tim Berners-Lee the contractor at the European
Organization for Nuclear Research (CERN), Switzerland in 1980. He built a personal
database of people and software models and used hypertext so that each new page of
information was linked to an existing page.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1-3 Web Site Basics

1.1.4 Internet or WWW?


 The term internet and WWW is often used interchangeably, but these are two different terms.

 The internet is collection of computers and other devices (such as printers, scanners etc.)
connected together whereas World Wide Web (WWW) is collection of software and
corresponding protocols used to access the resources over the network.
 The world wide web contains huge amount of documents, images and other resources which can
be accessed using the hyperlinks.
 Thus people use internet through the Web.

1.2 Internet Protocol Dec.-09, 11, May - 14


Various protocols used in internetworking are -

(1) File Transfer Protocol (FTP)


 The file transfer protocol sets the rules for transferring files between computers.
 When user wants to download a file from the server FTP is used.
 FTP uses two connections between client and server. One connection is used for actual data
transfer and other is used for control information (used for commands). This separation of
data and commands makes the FTP more efficient.

Fig. 1.2.1 Two connections used in FTP processing

 When client makes a request for particular file download then using the data transfer
connection actual data gets transmitted from server to the client.
 At the same time server keeps track of how much data is sent so far and how much is
remaining. This tracking can be done using the control transfer connection.
 Hence during the file downloading/uploading we can see a message about how many bytes
are getting transferred and how much time is remaining.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1-4 Web Site Basics

(2) HTTP
 The Hyper Text Transfer Protocol (HTTP) is a request/response protocol.
 It is a communication protocol used to transfer the information on local area network and
World Wide Web (WWW).
 It is the network protocol used to deliver virtually all files and other data (collectively called
resources) on the World Wide Web, whether they're HTML files, image files, query results,
or anything else. Usually, HTTP takes place through TCP/IP sockets.
 It is also called as a stateless protocol because this protocol is not able to maintain the
previous conversation/information.

(3) SNMP

 Simple Network Management Protocol (SNMP) is a protocol which enables network


administrators to manage network devices and to diagnose network problems.
 The network management system is based on two main elements : a supervisor and agents.
o The supervisor is the terminal at which the network administrator requests for network
management.
o The agents are found at the level of each interface connecting the managed devices to
the network. With the help of these agents information on the different objects (such as
switch, hub, routers) can be collected.

(4) SMTP
 Simple Mail Transfer Protocol (SMTP) is a simple protocol which is extensively used for
transfer of e-mails to remote servers.
 It is an asynchronous protocol, because it allows delayed delivery of message.
 With the help of mail transfer agent and user agent the SMTP sends and receives the emails.

(5) POP3
 Post Office Protocol version 3 (POP3) is used by local email clients (such as Microsoft
Outlook Express).
 The POP3 protocol works only at the receivers end and has no work at the sender’s end.
 The POP protocol has two parts, a client POP i.e. receiver’s POP and a server POP i.e.
reciever’s email server. The client i.e. the receiver opens TCP connection with receiver’s
POP server. This client must be authenticated first by using the user name and password.
Then the client can receive the emails from the mailbox.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1-5 Web Site Basics

(6) TCP
 The Transmission Control Protocol is used for,
1. Safe delivery of data
2. Error detection
3. Assurance of the correct sequencing of data being received.
 This protocol is called connection oriented protocol because before sending the data this
protocol requires that two computers have established connections.
 The TCP allows the transmission of arbitrary amount of data by breaking it into stream of
separate IP packets.
 These IP packets are numbered so that it could be reassembled properly at arrivals. Along
with the data an acknowledgement is also sent/received in order to know whether the
reliable connection has occurred or not.

(7) UDP
 The user datagram protocol is a connectionless protocol without any error detection
facility.
 This protocol is used for simply transmission of data.
 The UDP is known as an unreliable protocol however this is much faster than TCP.

(8) IP
 Internet Protocol (IP) is a network layer protocol which consists of addressing information.
 Using this information the communication between uniquely addressed computers is
possible.

University Questions

1. Explain the various Internet protocols used for client server communication.
AU : Dec.-09, Marks 8,May-14, Marks 8
2. Explain TCP/IP in detail. AU : Dec.-11, Marks 8

1.3 HTTP Request and Response Message


AU : June-09, May-12, 13,14, Dec.-12, 13, Marks 8
 The basic feature of HTTP protocol is that it follows the request response model.
 The client makes a request for desired web page by giving the URL in the address bar. This
request is submitted to the web server and then web server gives the response to the web
browser by returning the required web page.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1-6 Web Site Basics

1. HTTP Request Message Structure


The basic structure of request message is given by following general form -
<Start line>

<Header fields>

<Blank Line>

<Message Body>

<start Line>

The start line consists of three parts which are separated by a single space. These parts are -
i) Request method ii) Request-URI iii) HTTP version
(i) Request Method : Various methods used for making the request are enlisted in the following
table
HTTP method Description
GET The GET method is used to retrieve information from a specified URI and is
assumed to be a safe, repeatable operation by browsers.
POST The POST method is used to request the server for desired web page and the
request made is accepted as a new subordinate of the resource identified.
The POST method is used for operations that have side effects and cannot be
safely repeated. For example, transferring money from one bank account to
another has side effects and should not be repeated without explicit approval
by the user.
HEAD The HEAD method is identical to GET. The only difference is that the server
should not return a message-body in the response. The meta-information
contained in the HTTP headers in response to a HEAD request should be
similar to the information sent in response to a GET request.
OPTION This method supports for the specified URL. It can be used to check the
functionality of a web server by requesting '*' instead of a specific resource.
PUT This method uploads a representation of the specified resource.
DELETE This method is useful in deleting the specified resource.
TRACE When request is made using TRACE method the server echoes back the
received request so that a client can see what intermediate servers are adding
or changing in the request.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1-7 Web Site Basics

(ii) Request-URI:
 The Uniform Resource Identifier (URI) is a string used to identify the names or resources
on the Internet.
 The URI is a combination of URL and URN.
 The URL stands for Uniform Resource Locator and URN stands for Uniform Resource
Name.
 The web address denotes the URL and specific name of the place or a person or item
denotes the URN. For example
urn : ISBN 978-81-8431-123-2
specifies the address of some book.
 If the URI is written in the form of http: then it is both an URI and URL but there are some
other URI which can also be used as URL. For example
URL Intended server

ftp://ftp.mywebsite.com/index.txt File can be located on FTP server

telnet://mywebsite.org Telnet server

mailto:[email protected] Mail box

http://www.mywebsite.com Web server

(iii) HTTP Version : The first HTTP version was HTTP/0.9 but the official version of HTTP was
HTTP/1.1
<Header Field> and <Message Body>
 The host header filed is associated with the http request.
 The header fields are in the form of field name and field value.
 Thus typical structure of http request is given be following example -

Fig. 1.3.1 HTTP request message structure


TM
Technical Publications - An up thrust for knowledge
Web Technology 1-8 Web Site Basics

2. HTTP Response Message Structure


The basic structure of response message is given by following general form -
<Status line>

<Header fields>

<Blank Line>

<Message Body>
<Status Line>

Status line is similar to the start line in the request message. It consists of three fields.
HTTP version Status code reason phrase

The HTTP version denotes the HTTP version such as HTTP/1.1. The status code is a numeric
code indicating the type of response. The reason phrase is in the text string form and presents the
information about the status code.
For example -

Following table explains some commonly used status codes.


Status code Reason phrase Description

200 OK This is a standard response for successful request.

201 Created It shows that the request is fulfilled and a new resource is
being created.

202 Accepted When the request is accepted for processing but is not
processed yet is denoted by this status code.

301 Moved The URI for requested resource is moved at some another
permanently location.

401 Unauthorized The requested resource is protected by some password and


the user has not provided any password.

403 Forbidden The requested resource is present on the server but the server
is not able to respond it.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1-9 Web Site Basics

404 Not Found The requested resource is not present currently but may be
available in future.

500 Internal Server It is a generic error message that appears due to software
Error internal failure.
<Header Fields>
The header field in response message is similar to that of request message.
<Message Body>
The message body consists of response message.
For example
HTTP/1.1 200 OK
Date: Sat, 30 Mar 2019 07:59:01 GMT
Server: Apache/2.0.50 (Unix) mod_perl/1.99_10 Perl/v5.8.4
mod_ssl/2.0.50 OpenSSL/0.9.7d DAV/2 PHP/4.3.8
Last-Modified: Mon, 23 Feb 2009 08:32:41 GMT
Accept-Ranges: bytes
Content-Length: 2010
Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>...</html>
The response header fields are enlisted in following table
Header field Description
Date It represents the date and time at which the response is generated.
Server The name of the server which is responding
Last-Modified The date and time at which the response is last modified.
Accept-ranges It specifies the unit which is used by the client to accept the range request.
For example if there is a large document and only a single web page is
currently needed then this specifies the Accept-range.

University Questions

1. Write short note on HTTP protocol AU : June-09, Marks 6


2. Explain the structure of HTTP request and response messages.
AU : May-12, Dec.-12,Dec.- 13 Marks 8
3. Write and explain HTTP request message format. AU : May-13, Marks 4
4. Write the header format of Request and Response between Client/Server and explain it.
AU : May-14, Marks 8

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 10 Web Site Basics

1.4 Features of HTTP Protocol


1. It is a communication protocol used between web browser and web server.
2. This protocol is based on request-response messaging. That means client makes the request
of desired web page and then the server responds it by sending the requested resource.
3. It is a stateless protocol. That means HTTP protocol can not remember the previous user’s
information nor it remembers the number of times the user has visited particular website.
4. The request-response message consists of plain text in fairly readable form.
5. The HTTP protocol has a cache control. This is an advanced feature of HTTP. Most of the
web browsers automatically store(Cache) the recently visited web pages. This is very useful
feature because if the user requests the same web page that has been visited already then it
can be displayed from the cache memory instead of requesting the web server and bringing it
from there.

1.5 Web Clients AU : Dec.-11, Marks 8


 Web client is a kind of software that runs on the clients machine.

 This software sends the HTTP request to the server and then processes the HTTP response.

 Various forms of web client software are -


(1) Web browsers
(2) Browsers running on mobile phones
(3) Software robots which crawl on the web for retrieving the information
(4) User agents which assists the user in browsing the web.
 Web browser is a kind of software which is basically used to use resources on the web.
 Over the networks, two computers communicate with each other. In this communication, when
request is made by one computer then that computer is called a client and when the request gets
served by another computer then that computer is called server. Thus exchange of information
takes place via Client-Server communication.
 When user wants some web document then he makes the request for it using the web browser.
 The browsers are the programs that are running on the clients’ machines. The request then gets
served by the server and the requested page is then returned to the client. It is getting displayed
to the client on the web browser.
 The commonly used web browsers are (i) Internet explorer (ii) Mozilla Firefox (iii) Netscape
Navigator (iv) Opera (v) Google Chrome (vi) Safari.
 Web browser supports variety of protocols but the most commonly used protocol on the web
browser is Hyper Text Transfer Protocol(HTTP). This protocol is typically used when browser
communicates with the server.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 11 Web Site Basics

1.5.1 Functions Defined by Web Browser


Various functions of web browser are -
1. Reformats the URL and send a valid HTTP request.
2. When user gives the address of particular web site it is in the form of domain name. The web
browser coverts the DNS to corresponding IP address.
3. The web browser establishes a TCP connection with the Web browser while processing the
user’s request.
4. The web browsers send the HTTP request to the web server.
5. The web server processes the HTTP request sent by the web browser and returns the desired
web page to the client machine. The web browser on the client’s machine displays this web
page in appropriate format.

1.5.2 URL
 The Uniform Resource Locator (URL) is unique address for the file that has to be accessed over
the internet.
 When we want to access some website we enter it’s URL in the address bar of the web browser.
 For example if we want to access www.google.com then we must specify its URL in the address
bar as shown

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 12 Web Site Basics

However any other file such as some text file or image file or some HTML file can also be
specified. The URL contains name of the protocol such as http://
 The URL may contain the name of the protocol as such as ftp. For example
ftp://ftp.funet.fi/pub/standards/RFC/rfc2166.txt
 The protocol identifier and the resource name are separated by a colon and two forward slashes.
The syntax of writing URL is as given below,
protocol://username@hostname/path/filename
 Sometimes instead of domain name servers IP addresses can also be use. For example,
http://192.168.0.1
But use of IP address as URL is not preferred because human can not remember numbers very
easily but they can remember names easily.

Absolute and Relative URL


 The absolute URL is a URL which directly point to a file. It exactly specifies exact location of a
file or directory on the internet. Each absolute URL is unique. For example -
http://www.vtubooks.com/home.aspx
 The relative URL points to the file or a directory in relation to the present directory. For
example
 Consider the absolute address which refers an image mother.jpg
http://www.mywebsite.com/myphotos/mother.jpg
 For the above given absolute address the relative address will be -
../myphotos/mother.jpg
That means from the current URL the directory myphotos will be searched for the image
mother.jpg. The two peroids .. instruct the server to move up one directory which is the root
directory, then enter myphotos directory (/myphotos) and finally point at mother.jpg. Thus using
relative URL writing of long path name can be avoided.

University Question

1. Explain the use of relative URL with example. AU : Dec.-11, Marks 8

1.6 Web Server AU : May-10,12,13 , Marks 12

 Web server is a special type of server to which the web browser submits the request of web page
which is desired by the client.
 There are some popularly used web servers such as Apache and IIS from Microsoft.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 13 Web Site Basics

Functions of web server


Various functions of web server are -
1. The web servers accepts the requests from the web browsers.
2. The user request is processed by the web server.
3. The web servers respond to the users by providing the services which they demand for over
the web browsers.
4. The web servers serve the web based applications.
5. The DNS translate the domain names into the IP addresses.
6. The servers verify given address exists, find necessary files ,run appropriate scripts exchange
cookies if necessary and returns back to the browser.
7. Some servers actively participate in session handling techniques.

1.6.1 Apache
 It is an excellent server because of its two important features : Reliability and Efficiency.

 Secondly it is more popular because it is an open source software. That means it is freely
available to anybody. Apache web server is best suitable for UNIX systems but it can also be
used on Windows box.
 The apache web server can be configured as per the requirements using the file httpd.conf. This
file is present in the Apache software package.

1.6.2 IIS
 The Internet Information Services or Internet Information Server is a kind of web server
provided by Microsoft.
 This server is most popular on Windows platform.
Following are some differences between Apache and IIS servers
Sr. No. Apache web server IIS web server
1. Apache web server is useful on both IIS web server is used on Windows
Unix based systems and on Windows platform.
platform.
2. It is an open source product. It is a vendor specific product and can
be used on windows products only.
3. The Apache web server can be For IIS server, the behaviour is
controlled by editing the configuration controlled by modifying the window
based management programs called IIS
TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 14 Web Site Basics

file httpd.conf snap in. We can access IIS snap-in


through the
Control-Panel->Administrative Tools.

University Questions

1. Explain briefly the IIS Web Server. AU : May-10, Marks 8


2. Explain in detail the functions of web server. May-12, Marks 8
3. Explain the capabilities of web client and web server. May-13, Marks 12

1.7 Client, Sever and Communication


 In this architecture, there are 3 components.
1) Client PC or Web client
2) An application server or web server
3) A database server.

Working

Step 1 : The client PC or web client submits the request for desired web page to the web
server.
Step 2 : The work of server is distributed among application server and database servers.
Application server possess the required communication functions.
Step 3 : The data required by this business logic is present on database server. The required
data is returned to application servers
Step 4 : The web server or application server prepares the response page and sends it to the
web client.

Fig. 1.7.1 Client Server Communication


TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 15 Web Site Basics

Advantages :
1. High performance and persistent objects take part in communication.
2. This architecture is scalable. That means it can support increased number of users and
resources.
3. High degree of flexibility in deployment platform and configurations.
4. Code/data reusability can be achieved.
5. Improved data integrity
6. Improved security as clients can not directly access the database.
7. The maintenance and modifications can be done effectively without disturbing other modules
in the architecture.

Disadvantages :
1. The complexity gets increased.
2. Cost for network maintenance and deployment is increased.

Two Marks Questions with Answers

Q.1 List any two types of web servers with its application usage. AU : May-09
Ans. : There are two types of web servers one is vendor specific and another one is open
source. The example of vendor specific web server is IIS and example of open source web server
is Apache.
The IIS web server is used on Windows and Apache web server can be used on both Unix
and Windows platform.
Q.2 Why is HTTP called as stateless protocol ? AU : Dec.-09
Ans. : The HTTP protocol can not remember the previous user’s information nor it remembers
the number of times the user has visited the particular web page. That means it can not
remember the previous states. Hence HTTP is called stateless protocol.
Q.3 What is a web server ? Explain its functionalities. AU : Dec.-09
Ans. : Web server is a special type of server to which the web browser submits the request of
web page which is desired by the client. For example: IIS ,Apache.
Web server processes the request of the user which it submits using the web browser.
Sometimes the web servers access the database system and fetche the required information. The
required web page is compiled and sent to the user in his/her web browser.
Q.4 State the use of web server logs and list the contents of a message log. AU : May-11

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 16 Web Site Basics

Ans. : Web server log records the information about the server activity. It stores the
information about every http request processed by the server. A web server may produce more
than one message logs.
Every message log contains variety of debugging information and other information
generated by web application. Following information is present in the message log -
A. Host name or IP address of the client machine making the request.
B. Name of the user.
C. Date and time of response along with the time zone.
D. Start line of HTTP request.
E. HTTP status code of response.
F. Number of bytes sent in body of response.
Q.5 What is the use of cache control in HTTP response header ?
Ans. : Cache is used as a temporary repository. Use of cache improves the performance. Many
web browsers store web pages viewed by the client in the cache memory. This brings efficiency
in browsing the web page. The cache control help the user to display the web page quickly.
Q.6 List some basic internet protocols. AU : May-13
Ans. : Following are some basic Internet protocols.
i. http ii. ftp iii. smtp iv. pop3.
Q.7 For handling the mails which protocol is used ?
Ans. : There are two commonly used protocols for handling the emails. Simple Mail Transfer
Protocol (SMTP) is a simple protocol which is used to transfer emails to remote servers. Another
protocol is POP3 i.e. Post Office Protocol Version 3. This protocol works only at the receivers
end and has no work at the sender’s end.
Q.8 Give the functionalities of IP protocol.
Ans. : There are two functionalities provided by Internet Protocol -
Decomposition of the initial information flow into packets of standardized size and
reassembling of data at the destination.
The Internet protocol routes the packet through successive networks, from the source
machine to the destination which can be identified by its IP address.
Q.9 What is the difference between WWW and Internet ?
Ans. : The WWW and Internet are the two different terms. The Internet is a collection of
computers and other devices such as printers, scanners etc. connected together whereas WWW is
collection of software and corresponding protocol used to access the resources over the network.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 17 Web Site Basics

Thus World Wide Web (WWW) contains huge amount of documents, images and other
resources which can be accessed using the hyperlinks. People use Internet through web.
Q.10 Explain any two functionalities of web browser.
Ans. : Various functions of web browser are -
1. Reformat the URL and send a valid HTTP request.
2. When user gives the address of particular website it is in the form of domain name.
The web browser converts the DNS to corresponding IP address.
3. The web browser establishes a TCP connection with the web browser while
processing the user’s request.
4. The web browsers send the HTTP request to the web server.
Q.11 What is URL ? Write different parts of URL.
Ans. : The general format of URL is -
Scheme:Address
That is
protocol://username@hostname/path/filename
The scheme specifies the communication protocol. Different schemes have different forms
of addresses.
Various schemes that are used are http, ftp, gopher, file, mailto, news and so on.
Example : http://www.vtubooks.com/index.aspx
Q.12 Define URI. AU : May-11
Ans. : The Uniform Resource Identifier (URI) is a string used to identify the names or resources
on the Internet. The URI is a combination of URL and URN. The URL stands for Uniform
Resource Locator and URN stands for Uniform Resource Name. The web address denotes the
URL and specific name of the place or a person or item denotes the URN. For example
urn:ISBN 978-81-8431-123-2
specifies the address of some book.
Every URI consists of two parts, the part before the colon : denotes the scheme and the part
after colon depends upon the scheme. The URIs are case insensitive but generally written in
lower case. If the URI is written in the form of http: then it is both an URI and URL.
Q.13 What is GET and POST request ?
Ans. : The GET method is used to retrieve the information from a specified URI. The POST
method is used to request the server for desired web page. This is supposed to be a safe method
of retrieving the information.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 18 Web Site Basics

Q.14 What is www ?


Ans. : The WWW is a World Wide Web which is a collection of software and corresponding
protocols used to access the resources over the network. The WWW contains huge amount of
documents, images, and other resources which can be accessed using hyperlinks. Thus Internet
can be used through the web.
Q.15 What is TCP ?
Ans. : The TCP stands for Transmission Control Protocol. This is the connection oriented
protocol which help in communicating two machines. Using TCP the message gets transferred in
an orderly manner.
Q.16 List any four common browsers. AU : Dec.-11
Ans. : The common browsers are Internet Explorer, Mozilla Firefox, Google Chrome, Safari

Q.17 State the uses of Internet protocol. AU : May-12


Ans. : Following are the uses of Internet protocols -
i) The Internet protocol is used to decompose the initial information flow into packets of
the standard size. At the destination these packets are reassembled back.
ii) The Internet protocol routes the data packets so that transmission of data is possible to
the machine having desired IP address.
Q.18 State the functions of DNS and protocol used. AU : Dec.-12
Ans. : Following are the functions that are carried out by DNS –
1. Accepting and then requesting the programs to convert domain names to IP addresses.
2. Accepting and then requesting the other DNS servers to convert domain names to IP
addresses.
Q.19 Explain the way in which a DNS server resolves the address ? AU : Dec.-13
Ans. : Using the domain name space the computer which is to be accessed is identified
uniquely. The internet logically arranges the domain names in an hierarchical form. Secondly,
the DNS server maintains the huge database of domain names. The desired address is searched
in this database and if the IP address of corresponding name is found then IP address is returned
to user computer.
Q.20 List the two forms of URL and its uses. AU : May-14
Ans. : The two forms of URL are Absolute URL and Relative URL. The absolute URL directly
points to a file whereas the relative URL points to the file or directory in relation to the present
directory. The URL is a unique address of the file which is accessed over the internet.

TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 19 Web Site Basics

Q.21 Differentiate between internet and intranet. AU : CSE : Dec.-15

Ans. :

Sr. Internet Intranet


No.

1. Internet is a network of computers and it Intranet is a network of computers but it is


is open for all. designed for specific group of users.

2. The number of users of internet are The number of users of intranet are limited.
unlimited.

3. Internet contains different sources of The intranet contains limited information on


information on variety of subjects. limited subjects.

4. Internet contains large number of Internet can be accessed from the intranet but
intranets. with restrictions.

5. It is a collection of various LANs, WANs It is mostly any of LAN, WAN or MAN.


and MANs.



TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 20 Web Site Basics

Notes

TM
Technical Publications - An up thrust for knowledge
Unit I

1 2 HTML

Syllabus
Markup Languages : XHTML. An Introduction to HTML History-Versions-Basic XHTML Syntax and
Semantics-Some Fundamental HTML Elements-Relative URLs-Lists-tables-Frames-Forms-HTML
5.0.

Contents
2.1 Markup Languages: XHTML .................................... Dec.-11, ................................ Marks 4
2.2 Introduction to HTML
2.3 History and Versions
2.4 XHTML Syntax and Semantics ................................ Dec.-11, ................................ Marks 4
2.5 Some Fundamental HTML Elements ....................... Dec.-13, ................................ Marks 8
2.6 Relative URLs .......................................................... Dec.-08, 09, .......................... Marks 2
2.7 Lists .......................................................................... Dec.-11, May-11, ................. Marks 8
2.8 Tables ...................................................................... May-12, Dec.-13, ................ Marks 8
2.9 Frames ..................................................................... May-13, 14, Dec.-09, ......... Marks 16
2.10 Forms ....................................................................... May-09, Dec.-12, ............... Marks 16
2.11 HTML 5.0
Two Marks Questions with Answers

(2 - 1)
Web Technology 2-2 HTML

2.1 Markup Languages : XHTML AU : Dec.-11, Marks 4


 XHTML stands for EXtensible HyperText Markup Language
 The XHTML syntax rules are specified by the file xhtml11.dtd file. Hence specify the name of
this file at the beginning of XHTML script.

Difference between HTML and XHTML


Sr. HTML XHTML
No.
1. The HTML tags are case The XHTML is case sensitive and all the tags in
insensitive. Hence <body> or XHTML document must be written in lower case.
<BODY> or <Body> are treated as
one and the same.
2. We can omit the closing tags For every tag there must be a closing tag. Some
sometimes in HTML document. browsers get confused if the closing tag is not given.
There are two ways by which we can mention the
closing tags
<a href =”TajMahal.html”> </a>
or
<a href=”Tajmahal.html”/>
3. In HTML the attribute values it In every XHTML document the attribute values must
not always necessary to quote the be quoted.
attribute values. In fact numeric
attribute values are rarely quoted in
HTML. Only if some special
characters or white spaces are
present in the attribute values then
only it is essential to put quotes
around them in HTML.
4. In HTML there are some implicit In every XHTML the attribute values must be
attribute values. specified explicitly.
5. In HTML even if we do not follow In XHTML document the nesting rules must be
the nesting rules strictly it does not strictly followed. These nesting rules are-
cause much difference. A form element can not contain another form
element.
An anchor element does not contain another form
element.
List element can not be nested in the list elements.
If there are two nested elements then the inner
TM
Technical Publications - An up thrust for knowledge
Web Technology 2-3 HTML

element must be enclosed first before closing the


outer element.
Text elements can not be directly nested in form
elements.

University Question

1. List the two differences between HTML and XHTML with respect to elements.
AU : Dec.-11, Marks 4

2.2 Introduction to HTML


 HTML stands for HyperText Markup Language. Hypertext is simply a piece of text that works
as a link.
 Markup Language is language of writing layout information within documents.

 Basically an HTML document is a plain text file.

 It contains rich text. The rich text means text with tags.

 HTML is not a case sensitive language.

 Any HTML program can be written in simple Notepad or WordPad text editors. The extension
to this program should be either html or htm.
 This program then can be opened in some web browser and the corresponding web page can be
viewed. Let us create our first web page using HTML.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2-4 HTML

HTML Document
<html>
<head>
<title>My webpage</title>
</head>
<body>
This is my first Web Page!!!
</body>
</html>

Script Explanation
1) Note that the program consists of some strings enclosed within angular brackets. Such
strings are called tags.
2) The HTML program should be written within <html> and </html>. The <html> indicates the
start of html program and </html> denotes end of html program. Use of slash (/) in the
angular bracket indicates end of that particular tag.
3) Any HTML program has two prominent parts : head and body. The head part acts as a
header of a file and contains some information like setting the title of web page.

Comments in HTML
 The comment in HTML can be denoted as follows -
<!--It is a comment statement -->
 There should not be a space between angular bracket and exclamation mark. This comment is
beginning with <!-- and ending with -->. Also note one thing that there should not be any --
inside the comment.

2.3 History and Versions


 Tim Berners-Lee is the person who defined HTML. In 1990, Tim Berners-Lee was working
at CERN (European Organization for Nuclear Research). He included the elements that could
define title, paragraphs, hyperlink, headings, simple lists, address blocks and so on. But in that
version of HTML there was no facility for producing tables or fill-in forms and images within a
document.
 In 1994, Tim Berners-Lee launched the World Wide Web Consortium (W3C) for producing
standards for web technologies. W3C also defined the standards for HTML. As an outcome of
W3C’s efforts HTML 2.0 adopted web standard within it.
 The W3C released its HTML 4 recommendation in December 1997. The version 4.01 is then
introduced.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2-5 HTML

 The meta language used to define the syntax for HTML 4.01 is SGML (Standard Generalized
Markup Language).
 In 1998, the W3C introduced the EXtensible Markup Language (XML) which is a restricted
version of SGML. Then a new version of HTML came up, which is called XHTML. (eXtensible
HyperText Markup Language). The syntaxes of XHTML are defined using XML, rather than
SGML.
 The HTML 5.0 is the fifth revision of HTML standard of World Wide Consortium(W3C) which
is finalized in October 2014.

2.4 XHTML Syntax and Semantics AU : Dec.-11, Marks 4


 An XHTML document consists of three main parts :

1. DOCTYPE declaration
2. <head> section
3. <body> section.
 The basic document structure is :
<!DOCTYPE...>
<html>
<head>
<title>...</title>
</head>
<body>



</body>
</html>
 The DOCTYPE declaration should be as given below -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
 The DOCTYPE specifies the document Type. The Document type is specified by the Document
Type Definition (DTD).
 The XHTML syntax rules are specified by the file xhtml11.dtd file. Hence we are specifying
the name of this file at the beginning.

Three Flavors of XHTML :


There are three types of XHTML DTDs and those along with their uses are as given below -
1. XHTML 1.0 Strict : When we want a clean markup code then this type of dtd is used.
2. XHTML 1.0 Transitional : When we want to use some html features in the existing
TM
Technical Publications - An up thrust for knowledge
Web Technology 2-6 HTML

XHTML document.
3. XHTML 1.0 Frameset : When want to make use of frames in the XHTML document.

University Question

1. Explain about XHTML DTD. AU : Dec.-11, Marks 4

2.5 Some Fundamental HTML Elements AU : Dec.-13, Marks 8

 In all HTML/XHTML documents the root element is <html> which has two children : head and
body.
 Any text contained within the head element does not appear directly in the client area of web
browser. The head element is used for providing certain information to web browser. The
<title> element is used to give title to the web page. Note that this title does not appear in client
area. Rather it appears at the top of web browser.
 The <body> element contains the information
which is to be displayed in the client area of web
browser.
 The body element can contain several
fundamental elements such as <p>, <h1>, <div>,
<a>, <hr>, <br> and so on. The elements within
the body part is for deciding the layout of your
web page. Fig. 2.5.1 Element tree

2.5.1 Heading
 There are header tags which help to display the text as some header.

 The header tag is denoted by h1, h2 and so on upto h6.

 Following HTML document along with its output is itself self explanatory.

HTML Document [headerDemo.html]


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> This is a first header </h1>
<h2> This is a second header </h2>
<h3> This is a third header </h3>
<h4> This is a forth header </h4>
<h5> This is a fifth header </h5>
TM
Technical Publications - An up thrust for knowledge
Web Technology 2-7 HTML

<h6> This is a sixth header </h6>


</body>
</html>
Output

2.5.2 Paragraphs
Following are the tags that are used for creating paragraphs
Tag Meaning

<p> This tag should be put at the end of every paragraph.

<pre> This tag is used to preserve the white spaces and lines in the text.

<div> This tag is used to make division of sections in the XHTML document.

For example

HTML Document[TextFormat.html]
<!DOCTYPE html>
<html >
<head>
</head>
<body>
<p>
Once upon a time, there was a king who kept a monkey as a pet.
The monkey served the king by all the possible ways.
</p>
<div>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2-8 HTML

It was very hot in those days. So one day, when the king was sleeping, monkey was
fanning the king. Suddenly monkey noticed a fly on the chest of the king. The monkey
tried to swish it away. But fly would go away for one moment and come back again.
</div>
<div> So monkey decided to teach a lesson to the fly.</div>
<pre>
The monkey then looked for something to hit a fly.
It then found a stick.
It picked up the stick and tried to beat the fly using stick.
Hmmm at last it found a fly and
with all the force it hit the fly as a result of which the king died.

Lesson from the story:Never keep a fool servant !!!


</pre>
</body>
</html>
Output

2.5.3 Line Break


For the line break the <br/> tag is used. This is a single line break tag. Generally this tag is
kept at the end of every line.

For example
<!DOCTYPE html>
<html>
<head>
<title>Line Break Demo</title>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2-9 HTML

</head>
<body>
<p>
Here the line breaks <br/> and new line starts.
Again line breaks<br/> Bye.
</p>
</body>
</html>
Output

2.5.4 Setting Font Style


The font style can be of various types such as boldface, italics, and strikethrough.
Tag Purpose

<b> </b> Displays the text in bold

<i> </i> Displays the text in italics

<strong </strong> Displays the text in bold

<strike> </strike> Displays the text with strike

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 10 HTML

Following HTML document illustrates this –

HTML Document [FontStyle.html]


<!DOCTYPE html>
<html>
<head>
<title>Font Style Demo</title>
</head>
<body>
<b> This is a bold text </b> <br/>
<i> This is in italics</i> <br/>
<strong> This is strongly emphasized text</strong> <br/>
<strike> This is striked text </strike>
<center> This will appear at the center</center> <br/>
</body>
</html>
Output

2.5.5 Text Alignment


We can align the text at left, right or at the center using a <div> tag. Here is a HTML program
which shows the text aligned left, right and centre.

HTML Document[TextAlign.html]
<!DOCTYPE html >
<html>
<head>
<title>Font Style Demo</title>
</head>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 11 HTML

<body>
<div align="center">This line is aligned at center</div>
<div align="left">This line is aligned at left</div>
<div align="right">This line is aligned at right</div>
</body>
</html>
Output

2.5.6 Setting the Font and Color


We can set the font, size and color of the text in the web page. The tag <basefont> is used for
this purpose. The optional attributes used with <basefont> tag are as given below :
Attribute Value Purpose

color Color value such as “red”, “yellow” It displays the text with specified color.
and so on.

face Font-family such as “arial”, It displays the text with specific font family.
“verdana”,”sans-serif” and so on.

size Number The text of specified size will be displayed


using this attribute value.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 12 HTML

For example –

HTML Document[SetFont.html]
<!DOCTYPE html>
<html >
<head>
<title>Setting the Text </title>
</head>
<body>
<basefont face="arial" size="10">
Varsha is sweet and <br/>
Jayashree is very naughty!!<br/>
But Sachin is a serious guy<br/>
And Rashmi is a new-comer in this group
</body>
</html>
Output

The <basefont> tag is supported in Internet Explorer 9 and not by FireFox, Chrome, Opera and
so on.
Most of the web designers prefer to have their web pages white in color. HTML allows the web
developer to use color attribute for coloring the text or for setting the background color.
First of all we will learn how to display a text colourful on the webpage.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 13 HTML

HTML Document[ColorFont.html]
<!DOCTYPE html>
<html>
<head>
<title>coloring the text</title>
</head>
<body>
<basefont face="arial" size="5" color="blue">
Great people are simple and <br>
<font face="Times new roman" color="red" size="8">
Simple people are great!!!<br>
<font face="GoudyHandtooled BT" color="green" size="14">
Great people rule the world.
</body>
</html>
Output

Script Explanation :
1) In the above HTML document, we have used font face tag to set the font.
2) Using the attributes color and size we can specify values color and size in double quotes.
We can set the background color of the web page using the attribute bgcolor. Following
program sets the background color of the web page to red.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 14 HTML

HTML Document[BgColor.html]
<!DOCTYPE html>
<html>
<head>
<title>Coloring the background</title>
</head>
<body bgcolor="#FFFF00">
<h3>This is document has colored background</h3>
</body>
</html>

Script Explanation :
1) In above document we have specified background color using the bgcolor attribute.
2) The color can be specified by either using the color name in double quotes or using the
hex.code as given in above document.
3) The first two digits of Hex code represents the Red value, then next two digits specify the
green value and final two digits specify the blue value. Hence the corresponding output will
be as follows -
Output

Note that the background color is specified by the hexadecimal value. Following table shows
the hex. and corresponding decimal values -
Decimal value Hexadecimal value
1 1
2 2
3 3

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 15 HTML

4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 D
14 E
15 F

In HTML, the colors are specified by beginning with # and the FF denotes 255. In this color
code first two digits specify the amount of red color then next two digits specify the green color
and the last two digits specify blue color
# FF 00 00
red colour
Hence is used to set the background color red. Each pair of digits specifies 0 to 255 color
values. Thus hexadecimal color coding helps us to specify.
256 * 256 * 256 = 16777216 colors.
The color can also be specified by its name as follows -
<html>
<body bgcolor=yellow>
</html>
Following is a list of colors that can be specified for setting the background colors
Aqua Navy

Black Olive

Blue Purple

Fuchsia Red

Gray Silver

Green Teal

Lime White

Maroon Yellow

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 16 HTML

2.5.7 Special Character


 In HTML certain symbols are treated as special. For example - < i.e. less than symbol is
considered as special symbol because it is used as the beginning of the tag.
 Hence we cannot directly use certain symbols such as <, >, “,© and so on.

 To print these symbols we use the units which are called as reference. This reference always
begins with ampersand (&) sign. Such reference is called as entity reference.
 Following table enlists some characters and entity references –

Character Meaning Entity Reference

< less than &lt;

> greater than &gt;

& ampersand &amp;

“ double quote &quot;

’ apostrophes &apos;

© copyright &copy;

 Another type of entity reference that is used frequently is &nbsp; that is non breaking space
character.
 This entity reference is useful for defining the space between two string and informing browser
for not performing the word wrapper between the strings.
 Following is a sample script that makes use of &nbsp.

HTML Document[SpaceDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Space Demo</title>
</head>
<body>
<h3>
Method 1:
</h3>
<p>
Jony&nbsp;Jony&nbsp;Yes&nbsp;Papa&nbsp&nbsp;&nbsp;&nbsp;&nbsp;Eating
&nbsp;sugar&nbsp;no&nbsp; Papa&nbsp;&nbsp;&nbsp;Open&nbsp;Your&nbsp;
mouth&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ha!Ha!Ha
</p>
<h3>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 17 HTML

Method 2:
</h3>
<p>
Jony Jony Yes Papa Eating sugar no Papa Open Your mouth Ha!Ha!Ha
</p>
</body>
</html>
Output

Ex. 2.5.1 : How Divide and Pound symbol can be put on HTML document ?
Sol. : With the help of entity references denoted using & these two symbols can be put in HTML
document. The code can be
<html> Output
<head>

</head>

<body>

<p>This &divide symbol</p>

<p>This &pound symbol</p>

</body>

</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 18 HTML

University Question

1. State and explain any four HTML elements in detail. AU : Dec.-13, Marks 8

2.6 Relative URLs AU : Dec.-08, 09, Marks 2

 There is a common practice to specify the web link in the web page. The link acts as a pointer to
some web page or some resource.
 Use of hyperlink in the web page allows that page to link logically with other page.

 We can use hyperlinks by using a tag <a> and by specifying the URL for href.

 The value assigned to href specifies the target of the link.

 The <a> means beginning of the web link and </a> means end of the web link.

 The most important attribute of the <a> element is the href attribute, which indicates the link's
destination.
 By default, links will appear as follows in all browsers :
1) An unvisited link is underlined and blue.
2) A visited link is underlined and purple
3) An active link is underlined and red
 Following are the steps to be followed to specify web link in the web page.
Step 1 : The beginning of web link can be specified by the tag <a href = “ “. Inside the
double quotes mention the URL of desired link.
Step 2 : Write some text that should act as a hyperlink.
Step 3 : End the web link </a>
Here is a sample program which implements the above given idea -

HTML Document [HyperlnkDemo.html]


<!DOCTYPE html>
<html>
<head>
<title> Use of Hyperlink on the web Page </title>
</head>
<body>
click here to get a
<a href="http://www.vtubooks.com">book</a> on engineering
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 19 HTML

Output

If you click on the hyperlink book then you will get the following output.

The target attribute


 If we want to get that link opened in another window we can mention _target property. Various
targets can be -
 _self loads the page into the current window.

 _blank loads the page into a new separate browser window.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 20 HTML

Ex.2.6.1 : Develop a HTML page to use image as a link to another page. AU : Dec.-08, Marks 2
Sol. :

Step 1 : Write the HTML document containing an hyperlink to an image. When we click on
the image the html page referred by the <a href> tag must get opened.
XHTML Document[ImgLink.html]
<!DOCTYPE html>
<html>
<head>
<title> Image Demo </title>
</head>
<body>
<h1> Indian Heritage </h1>
</p>
<a href="TajMahal.html" target ="_blank">
<img src= "TajMahal.jpg" alt= "Taj Mahal!!" />
</a>
<br/>History of Taj Mahal
<br/>
</body>
</html>
Step 2 : Write the HTML document(TajMahal.html) mentioned by the <a href> tag in Step 1
as follows.
HTML Document[TajMahal.html]
<!DOCTYPE html>
<html>
<head>
<title> Information on TajMahal </title>
</head>
<body>
<h1> Indian Heritage </h1>
<p>
Taj Mahal is one of the wonders of the World. It is located in Agra,India.
<br/>
Taj Mahal is built by <strong>Shah Jahan</strong> in memory of his wife <strong>Mumtaz
Mahal</strong>
<br/>
It is considered to be the excellent example of Mughal Architecture
</p>
<br/>
</body>
</html>
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 21 HTML

Step 3 : Open some web browser and specify the file name ImgLink.html in the address bar
and you will get following output.
Output

2.6.1 Plying an Audio File


Using HTML script we can play the audio files. The simplest way to play audio file is the use
of hyperlinks. Following script shows how simple it is to a play a sound file using HTML
<html>
<body>
<h2>Playing The Audio</h2>
<form>
<a href="chimes.wav">Click here to Play the sound</a>
</form>
</body>
</html>
The above script executes in almost all the web browsers such as Internet explorer, Mozilla
Firefox, Opera and so on. But the above HTML document launches the Media player software and
then the audio file is played within it. For playing the audio files using hyperlinks it is necessary to
get the audio file downloaded first.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 22 HTML

2.6.2 Uses of Links


Following are the uses of the hyperlinks for a web document -
1. One can link logically related documents together using the links in the web page.
2. Use of link enhances the readability of the web document.
3. User can click on the link and can learn more about a subtopic and then can return to the
main topic. This navigation within the web pages is possible due to the links.

University Question

1. How are audio files played through HTML? Explain with an example.
AU : Dec.-09, Marks 2

2.7 Lists AU : Dec.-11, May-11, Marks 8

 List is nothing but the collections of items or elements. There are two types of lists - unordered
lists and ordered lists.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 23 HTML

 The unordered list is useful for simply listing the items but if we want the items in
some specific sequence then the ordered lists are used. Let us discuss how to use
these types lists in the HTML document.

2.7.1 Unordered List


Following HTML document makes use of unordered list.

HTML Document [UnordLstDemo.html]


<!DOCTYPE html>
<html>
<head>
<title> Use of Unordered List </title>
</head>
<body>
<h2>All About Computer ...</h2>
Following are some popular operating systems used in computer
<ul type="disc">
<li>DOS</li>
<li>Windows 98</li>
<li>Windows XP</li>
<li>Windows Professional</li>
<li>Windows Vista</li>
<li>Unix</li>
</ul>
Following are some core subjects on computer science
<ul type="circle">
<li>Operating system</li>
<li>Computer Network</li>
<li>Database management Systems</li>
<li>Web Programming</li>
<li>Software Engineering</li>
</ul>
Following are some popular Web browsers
<ul type="square">
<li>Intenet Explorer</li>
<li>Mozilla Firefox</li>
<li>Netscape Navigator</li>
</ul>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 24 HTML

Output

Script Explanation :
In above script we have used the tag <ul> for specifying the unordered list. The list items can
be mentioned using the tag <li> Due to which the list items can appear in bulleted form. The style
of the bullet can be as given below -

tags meaning

<ul> and </ul> Beginning and end of the bulleted list

<li> and </li> Displays the bulleted text on separate line.

<ul type=”circle”> Displays the circular bullets.

<ul type=”disc”> Displays the solid round bullets.

<ul type=”square”> Displays the squared bullets.

2.7.2 Ordered List


The ordered list is a list of items which must follows some specific sequence. We can number
the text using <ol> tag. Following table shows various styles by which the list can be numbered.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 25 HTML

tags meaning
<ol> and </ol> Beginning and end of the numbered list
<li> and </li> Displays the numbered text on separate line.
<ol type=“A”> Displays the list in following manner
A.
B.
C.

<ol type=“i”> Displays the list in following manner


i.
ii.
iii.

<ol type=“I”> Displays the list in following manner


I.
II.
III.

<ol type=“1”> Displays the list in following manner


1.
2.
3.

Here is one illustrative program -

HTML Document [OrdLstDemo.html]


<!DOCTYPE html>
<html>
<head>
<title> Ordered List Demo </title>
</head>
<body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 26 HTML

<h4>This is a typical List</h4>


<ol type="A">
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Forth</li>
<li> and so on</li>
</ol>
<h4>The list is starting from 5</h4>
<ol start="5">
<li>Ice cream</li>
<li>Mango</li>
<li>Juice</li>
<li>Pop Corn</li>
<li> and so on</li>
</ol>
</body>
</html>
We can have the nested ordered list. Here is an example of it
Output

HTML Document [OrdLstDemo1.html]


<!DOCTYPE html>
<html>
<head>
<title> Ordered List Demo </title>
</head>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 27 HTML

<body>
<h4>Information of Nations</h4>
<ol type="1">
<li>India
<ol type="i">
<li>National Bird: Peacock</li>
<li>National animal:Tiger</li>
<li>National game:Hockey</li>
</ol>
</li>
<li>Australia
<ol type="i">
<li>National Bird: Emu</li>
<li>National animal:Kangaroo</li>
<li>National game:Cricket</li>
</ol>
</li>
</ol>
</body>
</html>
Output

University Questions

1. Explain the purpose and way of creating lists in HTML documents.


AU :Dec.-11, Marks 8
2. State the types of lists supported by HTML and explain them in detail.
AU : May-11, Marks 8

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 28 HTML

2.8 Tables AU : Dec.-13, May-12, Marks 8


 For systematic arrangement of information we often require tabular structure. HTML allows us
to create tables on the web pages.
 Many web designers are using invisible tables on the web pages.
 The biggest advantage of using tables on the web pages is that the information gets arranged
systematically.
 The table is a matrix of rows and columns and the area formed due to intersection of a row and a
column is called cell.

2.8.1 Basic Table Tag


 To create a table on the web page the table beginning tag is <table> and </table> tag is used for
ending the table.
 Within <table> … </table> tag we can create rows and columns.
 The rows are created using <tr> </tr> and columns are created using <td> </td>

 Example

HTML Document[TabDemo.html]
<!DOCTYPE html>
<html>
<head>
<title> Table Demo </title>
</head>
<body>
<br/><br/>
<center>
<table border="5">
<caption align="bottom">
<b> Table Demo </b>
</caption>
<tr>
<td>This is Left cell-row 1</td>
<td>This is Right cell -row 1</td>
</tr>
<tr>
<td>This is Left cell-row 2</td>
<td>This is Right cell-row 2</td>
</tr>
</table>
</center>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 29 HTML

Output

Script Explanation
1) In above program, the parameter border=“5” is set in order to set the table border. You can
give any value to set the desired border.
2) The caption to the table is given by the parameter caption, we can set this caption either at the
top or at the bottom by using the parameter align.
3) Then using the tag <tr> the table row can be set. The <td> tag is used to create columns from
left to right.
4) Thus in the above program we are filling up the table values from top to bottom and from left
to right. Just refer the output provided along with the program for clear understanding of look
and feel of the table.

Ex. 2.8.1: Write HTML document to create a table with header to each column.
Sol. : We can set the header to each column of the table by <th> tag. Here is a simple HTML
program that simply adds the header to each column.
HTML Document [TabDemo1.html]
<!DOCTYPE html >
<html >
<head>
<title> Table Demo </title>
</head>
<body>
<br/><br/>
<center>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 30 HTML

<table border="3">
<caption align="bottom">
<b> Students Record </b>
</caption>
<th>Name</th>
<th>Marks</th>
<tr align=center>
<td>Lekhana</td>
<td>89</td>
</tr>
<tr align=center>
<td>Savita</td>
<td>92</td></tr>
</tr>
</table>
</center>
</html>
Output

The data in each row can be aligned centrally by using <tr align=center> Other types of
alignment can be left or right by <tr align=left> or <tr align=right> respectively.

Ex. 2.8.2 : Discuss the process of dividing the table into columns with an example. How would you
give headers to the table columns ?
Sol. : The process of dividing the table into column is as follows –
1. Create a table using the tag <table>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 31 HTML

2. Set the border to the table using attribute border=”some value”


3. Create rows using the tag <tr> and for each row create the columns using <td> </td> tags.
4. The header for the table column can be given using the tag <th> </th>

Ex. 2.8.3 : Following HTML document divides the table in columns and gives the header to the
column.
Sol. :
<!DOCTYPE html>
<html>
<head>
<title>Table Demo</title>
</head>
<body>
<table border ="1">
<th>Name</th>
<th>Marks</th> Output
<tr>
<td>AAA</td>
<td>50</td>
</tr>
<tr>
<td>BBB</td>
<td>90</td>
</tr>
</table>
</body>
</html>

2.8.2 Setting Background to Table


We can decorate our tables by setting the background of the table. Either some color can be set
as table background or some image can be set as a table background. Here is an illustration -
HTML Document[TabDemoBack.html]
<!DOCTYPE html >
<html>
<head>
<title> Table Decoration </title>
</head>
<body>
<table border="2">
<caption align="top">
<b>Background color</b>
</caption>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 32 HTML

<th bgcolor=yellow>Name</th>
<th bgcolor=yellow>Marks</th>
<tr align=center>
<td bgcolor=red>A</td>
<td bgcolor=green>92</td> Setting the background color
</tr>
<tr align=center>
to each cell
<td bgcolor=green>B</td>
<td bgcolor=red>90</td>
</tr>
</table>

<table border="5" background="backgr1.jpg" align="right">


<caption align="top">
<b>Background image</b>
</caption>
<th>Name</th>
<th>Marks</th> Setting the
<tr align=center> background image
<td>C</td>
<td>88</td>
</tr>
<tr align=center>
<td>D</td>
<td>77</td>
</tr>
</table>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 33 HTML

2.8.3 Rowspan and Colspan


Sometimes we may require adding sub-columns or sub-rows to categorize the information
properly. In such a situation colspan and rowspan can be used.
The rowspan is used to extend the row vertically and colspan is used to extend the column
horizontally. For example -
When rowspan=2 then the row can be extended vertically by two cells.
First Second <td rowspan=2>First
rowspan Third <td>Second</td><td>Third</td>

When colspan=2 then the column can be extended horizontally by two cells.
First Second <td>First <td>Second
Third <td colspan=2>Third

colspan

Ex. 2.8.4 : Explain the structure of HTML documents, write code to display following table :
College Name
Sr. No. Section A Section B
X Y X Y
1
2
3
Sol. :

<html>
<head>
<title>My Table</title>

</head>
<body>
<table border=1>
<tr>
<td rowspan="3">
<p align=center>Sr.No.</p>
<p>&nbsp</td>
</td>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 34 HTML

<td colspan="4">
<p align="center">College Name</p>
</td>
</tr>
<tr>
<td width="40%" colspan="2" align="center">Section A</td>
<td width="40%" colspan="2" align="center">Section B</td>
</tr>
<tr>
<td align="center">X</td>
<td align="center">Y</td>
<td align="center">X</td>
<td align="center">Y</td>
</tr>
<tr>
<td align="center">1</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
<td align="center">&nbsp</td>
</tr>
</table>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 35 HTML

Output

Ex. 2.8.5 : Write HTML code to draw table given below :

Image (20%) Company Name (80%)

Schedule
1
Type 1
2
3
Type 2
4
Sol. : ImageDemo.html
<html>
<head>
<title>My Table</title>
</head>
<body>
<table border=1>
<tr>
<td width="20%" align=center><img src="logo.jpg"/></td>
<th width="80%" align=center>TopTech Solutions</th>
</tr>
<tr>
<td>&nbsp</td>
<td align=center>Schedule</td>
</tr>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 36 HTML

<tr>
<td align=center>1</td>
<td rowspan="2" align=center>Type 1</td>
</tr>
<tr>
<td align=center>2</td>
</tr>
<tr>
<td align=center>3</td>
<td rowspan="2" align=center>Type 2</td>
</tr>
<tr>
<td align=center>4</td>
</tr>
</table>
</body>
</html>
Output

Ex. 2.8.6 : Write HTML code to draw table given below.


Items Price

Shirt Trouser Rs. 1000/-

Rs. 400/- Rs. 600/-

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 37 HTML

Sol. :
<html>
<head>
<title>Item-Price List</title>
</head>
<body>
<table border=1>
<tr>
<th colspan="2"><center>Items</center></th>
<th>Price</th>
</tr>
<tr>
<th><center>Shirt</center></th>
th><center>Trouser</center></th>
<td rowspan="2"><center>Rs.<br/>1000/-</center></td>
<tr>
<td><center>Rs.400/-</td>
<td><center>Rs.600/-</td>
</tr>
</table>
</body>
</html>
Output

Ex. 2.8.7 : Write HTML code which includes table, Hyperlink, character formatting ordered and
unordered list to display your resume.
Sol. : resume.html
<html>
<head>
<title>RESUME APPLICATION</title>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 38 HTML

</head>
<body>
<center><h2>RESUME</h2></center>
<a href="my_photo.jpg">PHOTO</a>
<br/><br/>
<strong>Name: </strong> Mr.Sachin Patil<br/>
<strong>Address: </strong> D10,SunEmpire,SunCityRd,Pune<br/>
<strong>Sex: </strong>Male<br/>
<strong>Phone: </strong>9229229221<br/>
<strong>Email: </strong>[email protected]
<br/><br/>
<strong>Educational Qualification:</strong>
<table border=2>
<tr>
<th>Examination</th>
<th>Year Of Passing</th>
<th>Board/University</th>
<th>Marks obtained</th>
</tr>
<tr>
<td>S.S.C</td><td>1991</td><td>Pune</td><td>93%</td>
</tr>
<tr>
<td>H.S.C</td><td>1993</td><td>Pune</td><td>90%</td>
</tr>
<tr>
<td>B.E.(Computer)</td><td>1997</td><td>Pune</td><td>72%</td>
</tr>
<tr>
<td>M.Tech(Computer)</td><td>2001</td><td>IIT(Kanpur)</td><td>A grade</td>
</tr>
</table>
<strong>
<br/><br/>
Programming Languages known:
</strong>
<ul>
<li>Cobol
<li>C
<li>C++
<li>Visual C++
<li>Visual Basic
<li>Java
</ul>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 39 HTML

<br/><br/>
<div align=left>Date:</div>
<div align=right>Place:</div>
<br/>
<div align=left>Signature</div>
</body>
</html>
Output

Ex. 2.8.8 : Create the following table using HTML tags.


Name of Train Place Destination Time Arrival Departure Fare
Rajdhani Mumbai Delhi 07.30 08.45 Rs. 989.00
Madras Mail Mumbai Madras 09.00 10.15 Rs. 450.00
Konkan Exp. Mumbai Manglore 13.30 14.45 Rs. 756.00
Deccan Exp. Mumbai Pune 16.00 17.30 Rs. 345.00
Sol. :
<html>
<head>
<title> Train Time Table </title>
</head>
<body>
<table border="1">
<tr>
<th rowspan=2>Name of Train</th>
<th rowspan=2>Place</th>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 40 HTML

<th rowspan=2>Destination</th>
<th colspan=2>Time</th>
<th rowspan=2>Fare</th>
</tr>
<tr><th>Arrival</th><th>Departure</th></tr>
<tr>
<td>Rajdhani</td><td>Mumbai</td><td>Delhi</td>
<td>7.30</td><td>08.45</td>
<td>Rs.989.00</td>
</tr>
<tr>
<td>Madras Mail</td><td>Mumbai</td><td>Madras</td>
<td>09.00</td><td>10.15</td>
<td>Rs.450.00</td>
</tr>
<tr>
<td>Konkan Exp.</td><td>Mumbai</td><td>Manglore</td>
<td>13.30</td><td>14.45</td>
<td>Rs.756.00</td>
</tr>
<tr>
<td>Deccan Exp.</td><td>Mumbai</td><td>Pune</td>
<td>16.00</td><td>17.30</td>
<td>Rs.345.00</td>
</tr>

</table>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 41 HTML

Ex. 2.8.9 : Differentiate between <table width=”400” height=”200”> and <table


width=”100%” and height=”50%”>
Sol. : (i) <table width=”400” height=”200”> denotes that the table width is 400 pixels and height is
200 pixels. It denotes the absolute value
For example
<html>
<head>
</head>
<body>
<table border="1" width="100" height="50">
<tr>
<th>Name</th>
<th>City</th>
<th>Age</th>
</tr>
<tr>
<td>AAA</td><td>Mumbai</td><td>10 yrs.</td>
</tr>
<tr>
<td>BBB</td><td>Pune</td><td>20 yrs.</td>
</tr>
<tr>
<td>CCC</td><td>Chennai</td><td>50 yrs.</td>
</tr>
</table>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 42 HTML

ii) On the other hand <table width=”100%” and height=”50%”> denotes the width of the
table is 100% of the screen and height is 50% of the browser screen. It denotes the relative
value
For example
<html>
<head>
</head>
<body>
<table border="1" width="100%" height="50%">
<tr>
<th>Name</th>
<th>City</th>
<th>Age</th>
</tr>
<tr>
<td>AAA</td><td>Mumbai</td><td>10 yrs.</td>
</tr>
<tr>
<td>BBB</td><td>Pune</td><td>20 yrs.</td>
</tr>
<tr>
<td>CCC</td><td>Chennai</td><td>50 yrs.</td>
</tr>
</table>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 43 HTML

Review Questions

1. Explain how tables can be inserted into HTML document with an example.
AU : May-12,Marks 8
2. Explain the way in which data can be presented in a tabular form using HTML.
AU : Dec.-13, Marks 8

2.9 Frames AU : May-13, 14, Dec.-09, Marks 16

 HTML frames allow us to present documents in multiple views.

 Using multiple views we can keep certain information visible and at the same time other views
are scrolled or replaced.
 For example, within the same window, one frame can display a
company information, a second frame can be a navigation menu
and a third frame may display selected document that can be
scrolled through or replaced by navigating in the second frame.
 Various frames can be set in one browser window .

 To set the frames in the browser window we use frame set.

 For example -
Fig. 2.9.1 Frames
<frameset cols="150,*">
will allow us to divide the window into two columns (i.e. in two vertical frames). One frame
occupying the size of 150 pixels and the other occupies the remaining portion of the window. Here
* means any number of pixels.
 Similarly
<frameset rows="*,120">
will divide the window into two rows (i.e. in two horizontal frames). The second part of
horizontal frame will be of 120 pixels and upper horizontal frame will occupy remaining portion of
the window.
 Similarly we can also specify the frameset in percentage form. For example
<frameset rows="30%,70%">
Using frameset we can divide the rows and columns in any number of frames. For example
<frameset rows = “20%,30%,50%” cols = “30%,*”>
This will create a frames in the browser’s window as follows -

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 44 HTML

Fig. 2.9.2 Frames


 In every layout frame we can load the desired html page by using frame src. For example
<frame src="D:\\html_examples\\bulleted1.html" name="Left_Vertical">
By this statement we are loading the web page bulleted1.html in the specific frame and the
frame is named as Left_Vertical.
Attributes in frameset tag
Attribute Value Purpose
cols pixels It specifies the number and size
% of columns in a frameset

*
rows pixels It specifies the number and size
% of rows in a frameset.

Attributes of frame tag


The <frame> tag has no end tag. The <frame> tag defines one frame within a <frameset> tag.
Various attributes of frame tag are
Attribute Value Purpose

frameborder 0 or 1 Value 1 specifies that the frame is displayed with border and 0
indicates that there is no border.
name Some name It specifies name of the frame
Nosize Due to this attribute we cannot resize the particular frame.
scolling yes, no or auto It specifies whether or not to display the scrollbar along with the frame.
src URL It specifies the name of the Document to be displayed within the frame.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 45 HTML

Example of Browser containing frame


Step 1 : Create a main HTML document which will display three HTML documents in three
vertical frames

FrameSet.html
<!DOCTYPE html>
<html>
<frameset cols="25%,*,50%">
<frame src="frame1.html">
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
Step 2 : Create frame1.html, frame2.html and frame3.html files as follows –

Frame1.html
<!DOCTYPE html>
<html>
<body>
<h1> Frame 1 </h1>
</body>
</html>

Frame2.html
<!DOCTYPE html>
<html>
<body>
<h1> Frame 2 </h1>
</body>
</html>

Frame3.html
<!DOCTYPE html>
<html>
<body>
<h1> Frame 3 </h1>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 46 HTML

Output

Script Explanation :
The above HTML document, the <frameset> tag is used to define frameset. The col attribute is
used to create the three column frames.

2.9.1 Frames with Scrollbars


<!DOCTYPE html>
<html>
<frameset cols="25%,*,50%">
<frame src="frame1.html" scrolling=no>
<frame src="frame2.html" scrolling=auto>
<frame src="frame3.html">
</frameset>
</html>
Output

To set the scroll bar we should assign the value auto to the scrolling parameter and if we do not
want the scroll bar accompanying the frame then we must assign the value no to the scrolling
parameter.
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 47 HTML

Ex. 2.9.1 : Create XHTML document that has two frames. The left frame displays the
contents.html and the right frame displays the cars.html where second frame is the target of link
from the first frame. [Note : Contents.html is a list of links for the cars description]
Sol. :

Step 1 : We will create the basic html file that contains the left and right frames. The HTML
document is as follows :

CarDemo.html
<!DOCTYPE html >
<html>
<head>
<title>My Frames Page</title>
</head>
<frameset cols="50%,50%">
<frame src="contents.html" name="Left_Vertical" noresize />
<frame src="Description.html" name="Right_Vertical" scrolling=no/>
</frameset>
</html>
Step 2 : Following is a HTML document that displays the contents that are loaded at first.
The left frame HTML document is as follows –

contents.html
<!DOCTYPE html >
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<h3>
<a href="Innova.html" target="Right_Vertical">Toyota Innova</a>
<h3/>
<h3>
<a href="Scorpio.html" target="Right_Vertical">Mahindra Scorpio</a>
<h3/>
<h3>
<a href="Etios.html" target="Right_Vertical">Toyota Etios Liva</a>
<h3/>
</body>
</html>
The right frame HTML document is as follows-

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 48 HTML

Description.html
<!DOCTYPE html >
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<center>
<h3> WELCOME <h3/>
This page displays the details of a car you have chosen.
</center>
</body>
</html>
Step 3 : Following are the three html documents each containing the description of each car.

Innova.html
<!DOCTYPE html >
<html>
<head>
<title>My Frames Page</title>
</head>
<body>
<h2> TOYOTA INNOVA</h2>
<ul type="disc">
<li>Price: Rs.9,35,731-Rs.14,82,852</li>
<li><td>Mileage: </td><td>10Kmpl(City) and 13 Kmpl(hwy)</li>
</ul>
</body>
</html>

Scorpio.html
<!DOCTYPE html>
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<h2> MAHINDRA SCORPIO</h2>
<ul type="disc">
<li>Price: </td><td>Rs.7,49,583-Rs.12,85,479</li>
<li>Mileage: </td><td>12Kmpl(City) and 16 Kmpl(hwy)</li>
</ul>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 49 HTML

Etios.html
<!DOCTYPE html>
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<h2> TOYOTA ETIOS LIVA</h2>
<ul type="disc">
<li> Price: </td><td>Rs.4,46,276-Rs.6,86,426</li>
<li> Mileage: </td><td>17Kmpl(City) and 19 Kmpl(hwy)</li>
</ul>
</body>
</html>
Step 4 : Open the suitable web browser and invoke the CarDemo.html(created in Step 1), the
output will be as follows -

Ex. 2.9.2 : Create a HTML document for a company home page and explain.
AU : May-13, Marks 16
Sol. : For creation of this web page the frames are used.
Step 1 : The main page is created as follows -
Main.html
<?xml version = "1.0" encoding ="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<frameset rows="20%,80%">
<frame src="logo.html">
<frameset cols="30%,70%">
<frame src="menu.html">
<frame src="contents.html">
</frameset>
</frameset>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 50 HTML

Step 2 : In the main page a layout of the company home page is created. Various html files
that are called in this HTML document are as given below -

Menu.html
<html>
<head><title>LOGO</title></head>
<body bgcolor="aqua">
<h3><a href="about.html"> About us<a/></h3>
<h3><a href="download1.html"> Free Downloads<a/></h3>
<h3><a href="download2.html"> Download Catalogue<a/></h3>
<h3><a href="download3.html">Download Orderform<a/></h3>
<h3><a href="catalogues.html">Catalogues<a/></h3>
<h3><a href="distributors.html">Distributors<a/></h3>
<h3><a href="Contacts.html">Contact Us<a/></h3>
<h3><a href="feedback.html">Feedback<a/></h3>
</body>
</html>

Logo.html
<html>
<head><title>LOGO</title></head>
<body bgcolor="magenta">
<h1><img src="books.jpg"/> Technical Publications</h1>
</body>
</html>

Contents.html
<html>
<head><title>LOGO</title></head>
<body bgcolor="khaki">
<center>
<h2>BOOKS</h2>
</center>
<p>TECHNICAL PUBLICATIONS is known for commitment to quality and innovation. We are
Leaders in our chosen scholarly and educational markets, serving the book Industry & Academic
Institutions.
</p>
<p>We have been in the industry for the last 18 years and are known for the quality and scholarly
publications in Engineering books. We publish more than 1000 titles of text books, for various
Universities across the India.
</p>
<p>We are specialized in Engineering text books and have been publishing titles for various
Engineering branches such as Electrical, Electronics, Computer Science, Information
Technology,Mechanical etc. and other management

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 51 HTML

books.
</p>
</body>
</html>
Step 3 : Open the suitable web browser and type the address for main.html. The output will
be as follows -

University Questions

1. Explain FRAME and IFRAME tags and attributes. AU : May-14, Marks 8


2. Write down HTML tags to explain frame within a frame. AU : Dec.-09, Marks 2

2.10 Forms AU : May-09, Dec.-12, Marks 16

 Form is a typical layout on the web page by which a user can interact with the web page.

 Typical component of forms are text, text area, checkboxes, radio buttons and push buttons.

 HTML allows us to place these form components on the web page and send the desired
information to the destination server.
 All these form contents appear in the <form> tag. The form has an attribute action which gets
executed when user clicks a button on the form.
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 52 HTML

 Various attributes of form are -

Attribute Description

action It specifies the url where the form should be submitted.


method It specifies the HTTP methods such as GET, POST
name This attribute denotes the name of the form.
target It specifies the target of the address in the action attribute.

Let us learn various form components with the help of simple HTML documents.

2.10.1 Text
 Text is typically required to place one line text. For example if you want to enter some name
then it is always preferred to have Text field on the form.
 The text field can be set using
<input type="text" size=”30” name =”username” value=" ">
The input type is text and the value of this text field is “ ” That means the blank text field is
displayed initially and we can enter the text of our choice into it. There is size parameter which
allows us to enter some size of the text field.
 Some other parameters or attributes can be
o maxlength that allows us to enter the text of some maximum length.
o name indicates name of the text field.
o align denotes the alignment of the text in the text field. The alignment can be left, right,
bottom and top.
Example Code
HTML Document [TextDemo.html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Page</title>
</head>
<body>
<form>
<b>Input String:</b><br/><input type="text" size="25" value="">
</form>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 53 HTML

Output

Script Explanation :
In above document
1) we have the label “Input String” just before the <input> tag. We can also specify the label
by using the <label> tag as follows -
<label>Input String: <br/><input type="text" size="25" value=""></label>
2) Thus the label gets bound to the text box. This aspect is always beneficial for a web
programmer because using label control we can focus on the corresponding text box
contents.
3) Initially the text box field is blank. We can type some text inside this text box.

Ex. 2.10.1 : How will you create password field in a HTML form ?
Sol. : The password field is typically created on the form. Hence following code can be written to
create it -
<form name=”form1”>
Password:<input type=”password”/>
</form>

2.10.2 Text Area


 Text field is a form component which allows us to enter single line text, what if we want to have
multiple line text? Then you must use textarea component.

HTML Document [TextareaDemo.html]


<!DOCTYPE html>
<html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 54 HTML

<head>
<title>My Page</title>
</head>
<body>
<form>
Enter the Desired text here
<textarea cols="40" rows="5" name="myname">
</textarea>
</form>
</body>
</html>
Output

Various parameters that can be set for the text area can be
 row denotes total number of rows in the text area.

 col specifies total number of columns in the text area.

 name denotes the name of the text area which can be utilised for handling that component for
some specific purpose.
 wrap can be virtual or physical. If the wrap is virtual then the line breaks get disappeared
when the text is actually submitted to the server. But if the wrap is assigned to the physical then
the line breaks (if any) appear as it is in the text.

2.10.3 Checkbox
 It is the simplest component which is used particularly when we want to make some selection
from several options.
 For having the checkbox we have to specify the input type as checkbox. For example
<input type="checkbox" name="option1" value="mango" checked="checked">Mango<br/>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 55 HTML

 If we want to get the checkbox displayed as checked then set checked="checked"

Example Code

HTML Document[ChkBoxDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>My Form with Check box</title>
</head>
<body>
<form name ="checkboxForm">
<div align="center"><br>
Select the fruit(s) of your choice<br/>
<input type="checkbox" name="option1" value="mango"
checked="checked">Mango<br/>
<input type="checkbox" name="option2" value="apple">Apple<br/>
<input type="checkbox" name="option3" value="guava">Guava<br/>
</div>
</form>
</body>
</html>
Output

Script Explanation
1) In the above program to set some checkbox in checked state we can mention the attribute
checked as checked.
2) We can set the value attribute as “ “ but this then the checkbox will not get associated with
any value. The Mango, Apple and Guava are the labels of the checkboxes.
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 56 HTML

2.10.4 Radio Button


 This form component is also use to indicate the selection from several choices.
 Using input type=“radio” we can place radio button on the web page.
 This component allows us to make only one selection at a time.
 We can create a group of some radio button component.
 Following HTML document displays the radio buttons for two different groups.

HTML Document[RadioButDemo.html]
<!DOCTYPE html>
<html >
<head>
<title>My Form with radio buttons Page</title>
</head>
<body>
<form name="myform">
<div align="left"><br>
<b>Select Fruit which you like the most</b><br/>
<input type="radio" name="group1" value="Mango">Mango<br/>
<input type="radio" name="group1" value="Apple" checked> Apple<br/>
<input type="radio" name="group1" value="Grapes"> Grapes
<br/><br/><br/>
<b>Select Flower which you like the most</b><br/>
<input type="radio" name="group2" value="Rose"> Rose<br/>
<input type="radio" name="group2" value="Lotus">Lotus<br/>
<input type="radio" name="group2" value="Jasmine" checked>Jasmine<br/>
</div>
</form>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 57 HTML

Ex. 2.10.2 : What is the difference between group of checkbox buttons and group of radio
buttons ?
Sol. :  The checkbox and radio buttons are used for making the selection from a group of choices.
 When a user selects (checks) a checkbox, its value gets assigned as the current value of the
checkbox group's control name.
 A checkbox group's control name may get paired with several current values if the user selects
more than one checkbox.
 Radio buttons work just like checkboxes except they are typically set up to be mutually
exclusive of one another, i.e. when one is selected, all the others are automatically deselected.

2.10.5 Button
 We can create the button using <input type =”button”> tag.

 There are two types of buttons that can be created in HTML. One is called submit button and
the another one is reset button.
 Various parameters of submit button are
1) name denotes the name of the submit button.
2) value is for writing some text on the text on the button.
3) align specifies alignment of the button.

Example Code

HTML Document[Button.html]
<!DOCTYPE html>
<html >
<head>
<title> My Page </title>
</head>
<body>
<form name="myform" action="http://www.localhost.com/cgi-bin/hello.cgi" method="POST">
<div align="center">
<br/><br/>
<input type="text" size="35" value=" ">
<br><input type="submit" value="Send">
<input type="reset" value="Reset"><br>
</div>
</form>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 58 HTML

Output

Script Explanation
1) In above HTML document, we have used the form whose name is “myform”.
2) There are two attributes associated with the form tag and those are action and method. The
action parameter indicates the address and the cgi script where the contents should go and
method parameter is for the methods for submitting the data. The method can be get or post.
Thus by specifying the action and method for a form we can send the desired data at desired
location.

2.10.6 Menus
 HTML allows us to have pop down menu on the web page so that the desired selection can be
made.
 The parameter select is for the menu component and option parameter is for setting the values
to the options of drop down menu.
 We can make some specific option selected by selected value = .

 In the following HTML document we have created one drop down menu in which various fruits
are enlisted. By default “Banana” is set as selected.

HTML Document [Menu.html]


<!DOCTYPE html>
<html >
<head>
<title> My Page </title>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 59 HTML

</head>
<body>
<form name="myform">
<div align="center">
<select name="My_Menu">
<option value="Mango">Mango</option>
<option value="Strawberry">Strawberry</option>
<option selected value="Banana">Banana </option>
<option value="Apple">Apple</option>
</select>
</div>
</form>
</body>
</html>
Output

Ex. 2.10.3 : Create a HTML document that has the form with the following controls
a) A text box to collect the customer name.
b) Four checkboxes, one for the following items :
i. Four HTML textbooks for ` 1000 ii. Eight XML textbooks for ` 2000
iii. Four Javabeans books for ` 2500 iv. Eight UML textbooks for ` 1500
c) A collection of radio buttons that are labelled as follows –
i. Cash ii.Cheque/DD iii Creadit card.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 60 HTML

Sol. :
<!DOCTYPE html>
<html >
<body>
<center><h2>REGISTRATION FORM</h2></center>
<hr/>
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" size="25"value=""></td>
</tr>
<tr>
<td>Select the desired Items:</td>
<td>
<select name="f">
<option value="4 HTML Books(Rs. 1000)">4 HTML Books(Rs. 1000)</option>
<option value="8 XML Books(Rs. 2000)">8 XML Books(Rs. 2000)</option>
<option value="4 JavaBeans Books(Rs.2500)">4 JavaBeans Books(Rs.2500)</option>
<option value="8 UML Books(Rs.1500)">8 UML Books(Rs.1500)</option>
</select>
</td>
</tr>
<tr>
<td>
Mode of Payment:
</td>
</tr>
<tr>
<td><input type="radio" name="group1" value="Cash">Cash</td>
</tr>
<tr>
<td><input type="radio" name="group1" value="Cheque/DD">Cheque/DD</td>
</tr>
<tr>
<td><input type="radio" name="group1" value="Credit Card">Credit Card</td>
</tr>
<tr></tr><tr></tr><tr></tr>
<td><input type="submit" value="Submit"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
</body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 61 HTML

Ex. 2.10.4 : Write a form to collect details of a user such as name, address, radio button to choose
subject of book he wants to buy, dropdown to choose favorite author, comments for the last book
he read.
Sol. :

<!DOCTYPE html >


<html >
<head>
<title>My Page</title>
</head>
<body>
<form>
<b>Name:</b><input type="text" size="20" value=""><br/>
<b>Address:</b><input type="text" size="35" value=""><br/>
<b>Subjects:</b><br/>
<input type="radio" name="authors" value="Web Programming">Web Programming<br/>
<input type="radio" name="authors" value="Computer Network">Computer Network<br/>
<input type="radio" name="authors" value="Software Engineering">
Software Engineering<br/>
<input type="radio" name="authors" value="Data Structures">Data Structures<br/>
<b>Select favorite Author:</b>
<select name="MyMenu">
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
<option value="DDD">DDD</option>
</select>
</br>
<b>Comments:</b></br>
<textarea cols="30" rows="10" name="comments">
</textarea>
<br/><br/>
<input type="submit" value="Submit"/>
<input type="reset" value="Clear"/>
</form>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 62 HTML

Output

Ex. 2.10.5 : Design a simple HTML form for registration of a student.


Sol. : HTML Form for Student Registration
<!DOCTYPE html>
<html >
<head>
<title>My Page</title>
</head>
<body>
<form>
<b>Student Name:</b><input type="text" size="20" value=""><br/><br/>
<b>Address:</b><input type="text" size="35" value=""><br/><br/>
<b>Email:</b><input type="text" size="20" value=""><br/><br/>
<b>Password:</b><input type="password" size="10" value=""><br/><br/>
<b>Select Course:</b><br/><br/>
<input type="radio" name="courses" value="Computer Engineering">

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 63 HTML

Computer Engineering<br/><br/>
<input type="radio" name="courses" value="E&TC Engineering">
E&TC Engineering<br/><br/>
<input type="radio" name="courses" value="Mechanical Engineering">
Mechanical Engineering<br/><br/>
<input type="radio" name="courses" value="Civil Engineering">
Civil Engineering<br/><br/>
<b>Select Payment Mode:</b>
<select name="MyMenu">
<option value="Cheque">Cheque</option>
<option value="Cash">Cash</option>
<option value="Card">Card</option>
</select>
<br/><br/><br/>
<input type="submit" value="Submit"/>
<input type="reset" value="Clear"/>
</form>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 64 HTML

Ex. 2.10.6 : Write and explain any five HTML form objects for a typical online user registration
process.
AU : May-09, Marks 8
Sol. : The five objects that can be used in the registration form are -
1. Text Field 2. Radio Button 3. Check Box
4. Submit Button 5. Reset Button
A sample application using all these form objects is as given below -
Registration.html
<html>
<head>
<title>Online Baking System</title>
</head>
<body bgcolor="khaki">
<center>
<h2>On-line Registration Form</h2>
</center>
<form name="form1">
<table>
<tr><td><b>Name:</b></td><td><input type="text" name="userName"></tr>
<tr><td><b>Password:</b></td><td><input type="password"name="pwd"></tr>
<tr>
<td><b>Sex:</b></td>
<td><input type="radio" name="group1" value="Male">Male</td>
<td><input type="radio" name="group1" value="Female">FeMale</td>
</tr>
<tr><td><b>Account Type:</b></td>
<td><select name="MyMenu">
<option value="Savings Account">Savings Account</option>
<option value="Current Account">Current Account</option>
</select>
</td>
</tr>
<tr><td><b>Account Number:</b></td><td><input type="text" name="AccNo"></tr>
<tr><td><b>Facilities:</b></td>
<td><input type="checkbox" name="option1" value="ATM card">ATM Card</td></tr>
<tr><td></td><td><input type="checkbox" name="option2" value="Cheque book">
Cheque book</td></tr>
</table>
<br/><br/>
<center>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</center>
</form>
</body>
</html>
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 65 HTML

Ex. 2.10.7 : Create a registration form for an educational web site with E-learning resources. All
form controls should have appropriate name attributes. Use the GET method for form submission
and specify an empty string for the action attribute. AU : Dec.-12, Marks 16
Sol. :
<!DOCTYPE html>
<html>
<head><title>My Form </title></head>
<body>
<h3> E-learning Resource Registration Form</h3>
<form name="myform" action ="" method="get" >
<div align="left"><br>
Name:<input type="text" name="name" value="">
<br/><br/>
Address:<input type="text" name="add" value="">
<br/><br/>
Phone:<input type="text" name="ph" value="">
<br/><br/>
Sex:
<input type="radio" name="group1" value="Male">Male
<input type="radio" name="group1" value="Female">Female<br/>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 66 HTML

<br/><br/>
Select the Course of your choice:
<select name="My_Menu">
<option value="Computer">Computer</option>
<option value="Information Technology">Information Technology</option>
<option selected value="Mechanical">Mechanical </option>
<option value="Electronics and Telecommunication">
Electronics and Telecommunication</option>
<option value="Electrical">Electrical</option>
</select>
<br/><br/><br/>
<input type="button" value="Submit">
</div>
</form>
</body>
</html>

2.11 HTML 5.0


 The HTML 5.0 is the fifth revision of HTML standard of World Wide Consortium(W3C) which
is finalized in October 2014.
 The earlier version was HTML 4.0 which was released in 1997.

 The objective of this markup language version was - i) to provide support for latest multimedia
and ii) to make the script readable and consistently understood by the developer.
 The HTML5 adds many new syntactic features. It includes the elements such as <video>,
<audio> and <canvas> elements. It also has integration of Scalable Vector
Graphics(SVG)contents and MathML for mathematical Formula.

2.11.1 Features of HTML 5.0


1. The XHTML doctype is just impossible to memorize (!DOCTYPE html PUBLIC "…).
Hence a new HTML doctype is <!DOCTYPE html>
2. There are new graphic elements such as <canvas> and <svg> in HTML5.0
3. The support for multimedia elements such as <audio> and <video>
4. It has support for <header>, <footer>, <article>, and <section>
5. It has support for new form controls such as number, date, time, calendar, and range.
6. It has a rich set of Application Programming Interface(API) for geolocations, HTML Drag
and Drop, Local Storage, Application cache and so on.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 67 HTML

2.11.2 Difference between HTML and HTML5


Sr. HTML HTML5
No.

1. The DOCTYPE declaration is much longer such as The DOCTYPE declaration is simple
<!DOCTYPE html PUBLIC "-//W3C//DTD <!DOCTYPE html>
XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
2. <audio> and <video> tags are not supported. <audio> and <video> tags are
supported for playing audio and video
files.
3. Finding out geographic location is impossible using The HTML5 supports the API for
HTML identifying the geographic location.
4. It supports the tag such as <applet>, <big>, The tags that are removed from
<center>, <font>, <frame>, <strike> HTML5 are
<applet>, <big>, <center>, <font>,
<frame>, <strike>
5. Does not allow JavaScript to run in browser. It allows JavaScript to run in
JavaScript runs in same thread as browser interface. background.
6. There is no support for <canvas> The <canvas> tag is for 2D drawing.
7. It needs external plugins such as flash. The need for external plugin is
reduced.

Two Marks Questions with Answers

Q.1 How to write comment statements in HTML ?


Ans. : The comments in HTML can be denoted as follows -
<!- -It is a comment statement -->
There should not be a space between angular bracket and exclamation mark. This comment is
beginning with <!-- and ending with -->. There should not be any character such as -- inside the
comment.
Q.2 What is the use of <pre> tag in HTML ?
Ans. : The pre tag can be used to preserve the white spaces and lines in the text.

Q.3 What is non breaking space character in HTML ?

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 68 HTML

Ans. : The &nbps is a non breaking space character. This entity is useful for defining the space
between two strings and informing browser for not performing the word wrapper between the
strings.
Q.4 What is cellpadding and cell spacing attributes ?
Ans. : The cellpadding allows to have some space between the contents of each cell and its
borders. The distance between each cell is called cell spacing.
Q.5 What is the need of using form in HTML ?
Ans. : Form is a typical layout on the web page by which user can interact with the web page.
The components that can be placed on the form are text box, check box, radio buttons, push
buttons and so on. Thus form is typically used to create an interactive Graphical User Interface.
Q.6 What is the purpose of using frames in HTML?
Ans. : The XHTML frames allows the web designer to present the web document in multiple
views. Using multiple views one can keep the information visible and at the same time other
views can be scrolled or replaced. For example, within the same window, one frame can display
a company information, the second frame can be a navigation menu and third frame may display
selected document that can be scrolled through or replaced by navigating in the second frame.
Q.7 What is the use of markup language in Web technology ? Give examples of some markup
languages.
Ans. : The markup language is used to layout the information on the web page. Various markup
languages are HTML, XHTML, DHTML, JavaScript.
Q.8 How will you create password field in a HTML form ? AU : Dec.-11
Ans. : The password field is typically created on the form. Hence following code can be written
to create it -
<form name=”form1”>
Password:<input type=”password”/>
</form>
Q.9 List and explain any two HTML elements. AU : May -12

Ans. :
Element Meaning

<title> This element is used to specify the title of the web page. This
element is defined within the <head> part.

<p> This element is generally defined in the <body> part. It is


used to create a paragraph.

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 69 HTML

Q.10 List and explain any two special characters in HTML

Ans. :
Special Character Entity Reference Meaning

< &lt To display the less than character.

& &amp To display the ampersand.

Q.11 How would you insert an image file named elephant.jpg at the very top of a web page ?

Ans. :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<p>
<img src= "elephant.jpg" alt= "Light!!" />
</p>
</body>
</html>
Q.12 Is it possible to insert white space in the web page while writing some paragraph ?

Ans. : Yes. We can insert the white space in the paragraph by using the entity reference &nbps
i.e. non breaking character space.
Q.13 What are the uses of hyperlinks in HTML ?
Ans. : Following are the uses of hyperlinks for the web document -
i) To logically link one page with another
ii) Use of link to enhance readability of the web document.
iii) The navigation from one page to another is possible.
Q.14 What is the advantage of using tables on the web document ?
Ans. : Using tables the information can be arranged systematically in row-wise and column-
wise manner.
Q.15 Write HTML code to display an image. AU : Dec.-12

Ans. :
<html>
<head>
<title> Image Demo </title>
</head>
<body>
<img src= "lamp1.jpg" alt= "Light!!" />

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 70 HTML

</body>
</html>
Q.16 List and explain the three flavors of HTML AU : May -13

Ans. : The three flavors of HTML are as follows -


1. XHTML 1.0 Strict : When we want a clean markup code or markup then this type is used.
To get the font, color, layout effects this flavor can be used along with the CSS.
2. XHTML 1.0 Transitional : By this type we can use the deprecated or presentational
elements but frames are not allowed.
3. XHTML 1.0 Frameset : We can use this type when we want to use Frames to partition the
browser window into two or more frames.
Q.17 How XHTML is more advantageous than HTML ? Specify. AU : May-14
Ans. : The XHTML is convenient to use if some one needs to reprocess the document using
XML. This reprocessing is always needed when we want to send the XHTML document on
some other devices say PDA. XML’s stricter syntax rules make automatic processing of
XHTML much easier and cheaper than ordinary HTML.
Q.18 Enlist any five features of HTML5.0.

Ans. :
1. It has a rich set of Application Programming Interface(API) for geolocations, HTML Drag
and Drop, Local Storage, Application cache and so on.
2. There are new graphic elements such as <canvas> and <svg> in HTML5.0
3. The support for multimedia elements such as <audio> and <video>
4. It has support for <header>, <footer>, <article>, and <section>
5. The XHTML doctype is just impossible to memorize(!DOCTYPE html PUBLIC "…).
Hence a new HTML doctype is <!DOCTYPE html>
Q.19 How do the hyperlinks appear by default ?
Ans. : By default the hyperlinks are unvisited, underlined and blue.

Q.20 Mention the HTML tag that can be used to make a picture a link.
Ans. : The href tag around img can be used to make a picture a link. For example -
<a href = “http://www.myhome.com”> <img src =
http://myhome.com/gallery/sampleflat.jpg></a>
Q.21 What are HTML forms ?
Ans. : HTML form is an element used to allow a user to input data on the web page. The
element used in <form>. The main attributes are action and method. For example
<form action =http://www.mywebpage.com/ method=get></form>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 71 HTML

Q.22 What do you mean by row spanning and column spanning ?

Ans. : The row spanning is used to combine two or more rows and columns spanning is used to
combine two or more columns.
Q.23 Explain the format of HTML document.
Ans. : The format of HTML document is as follows -
<html>
<head>
<title>
</title>
</head>
<body>
… HTML statements
</body>
</html>
Q.24 What are the uses of HTML form ?
Ans. : The HTML forms can be used in variety of applications such as

1. For creating registration forms


2. For creating the login forms
3. For gathering user information
4. For conducting surveys.
Q.25 How you use Form's Action Attribute and Submit Button in HTML ?
Ans. : The action attribute specifies where to send the form-data when a form is submitted.
For example - On clicking the submit button, the mypage.php page will be invoked for
further processing.
<form action="mypage.php" method="get">
First name: <input type="text" name="name"><br>
<input type="submit" value="Submit">
</form>
Q.26 How to use Line Break and Horizontal Line tags in HTML ?
Ans. :  The line break tag is denoted by <br/>

 The horizontal line can be inserted in the HTML document by <hr> tag.
Q.27 How you define href,target and name Attributes ?
Ans. : The href tag is used to have hyperlink in the HTML document. The target attribute
specifies where to open the linked document. For example - Following created hyperlink helps
the user to open the web document in another page.
<a href="/" target="_blank">The home page will open in another tab.</a>

TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 72 HTML

Q.28 Why we use XHTML ?

AU : Dec.-17
Ans. : The XHTML is used for following reasons -
i) It creates strict standard for making web pages.
ii) It reduces the incompatibility between various web browsers, and hence is compatible for
almost all the web browsers.
iii) It creates a standard that can be used on variety of different devices without change.
Q.29 What is HTML canvas and what are the uses of it ? AU :Dec.-18

Ans. :
 The < canvas > is an element in HTML 5.0 which creates rectangular area on HTML page
on which we can draw graphs.
 The uses of it are
i) For drawing graphics such as boxes, circles, text, adding images.
ii) Online, offline games.
iii) Animations
iv) Interactive video and audio.



TM
Technical Publications - An up thrust for knowledge
Unit II

1 3 CSS

Syllabus
Style Sheets : CSS-Introduction to Cascading Style Sheets-Features-Core Syntax-Style Sheets and
HTML- Style Rule Cascading and Inheritance-Text Properties-Box Model Normal Flow Box Layout-
Beyond the Normal Flow-CSS3.0.

Contents
3.1 Introduction to Cascading Stylesheet
3.2 Features ................................................................... May-11,14, ........................... Marks 8
3.3 Core Syntax
3.4 Selectors
3.5 Style Sheet and HTML
3.6 Style Rule Cascading and Inheritance
3.7 Text Properties ......................................................... Dec.11, ................................. Marks 8
3.8 Box Model
3.9 Color
3.10 Background Image ................................................... May-09, 13, .......................... Marks 8
3.11 Normal Flow Box Layout
3.12 Beyond Normal Flow
3.13 CSS 3.0
Two Marks Questions with Answers

(3 - 1)
Web Technology 3-2 CSS

3.1 Introduction to Cascading Stylesheet


 The CSS stands for Cascading Style Sheet.

 The Cascading Style Sheet is a markup language used in the web document for presentation
purpose.
 The primary intension of CSS was to separate out the web content from the web presentation.

 Various elements such as text, font and color are used in CSS for presentation purpose. Thus
CSS specification can be applied to bring the styles in the web document.

3.2 Features
 By combining CSS with the html document, considerable amount of flexibility into the content
submission can be achieved.
 Similarly, separating out the style from actual contents help in managing large-scale complex
sites. Thus CSS facilitates publication of content in multiple presentation formats.
 If CSS is used, effectively then global style sheet can be applied to a web document. This helps
in maintaining the consistency in the web document.
 If a small change needs to be done in the style of web content, then CSS makes it more
convenient.
 All above mentioned advantages of CSS show the need for it in web development

University Question

1. Explain the features of cascading style sheets. AU : May-11,14, Marks 8

3.3 Core Syntax


 The style specification is specified differently for each different level. For instance :

 For inline cascading style sheets the style appears in side the tag for defining the value.
<p style="font-size: 30pt ;font-family:Script">
 For the document cascading style sheet the style specification appear as the content of a style
element within the header of a document.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3-3 CSS

The type attribute tells the browser that what it is reading is text which is affected by the
Cascading Style Sheet. The type specification is necessary because there is one more specification
used in JavaScript.
 The External style sheet makes use of style specification in the same manner as in document
cascading style sheet.
The most commonly used CSS properties are enlisted in the following table -

Property Type Property


Fonts font
font-family
font-size
font-style
font-weight
@font-face
Text letter-spacing
line-height
text-align
text-decoration
text-indent
Color and background background
background-color
background-image
background-position
background-repeat
color
Borders border
border-color
border-width
border-style
border-top
border-top-color
border-top-width

TM
Technical Publications - An up thrust for knowledge
Web Technology 3-4 CSS

Spacing padding
padding-bottom, padding-left, padding-right,
padding-top
margin
margin-bottom, margin-left, margin-right,
margin-top
Sizing height
max-height
max-width
min-height
min-width
width
Layout bottom, left, right, top
clear
display
float
overflow
position
visibility
z-index
Lists list-style
list-style-image
list-style-type

3.4 Selectors

3.4.1 Simple Selector Form


 The simple selector form is a single element to which the property and value is applied.

 We can also apply property and value to group of elements.

 Following is an illustration for simple selector form.

HTML Document[SimpleSel.html]
<!DOCTYPE html>
<html >

TM
Technical Publications - An up thrust for knowledge
Web Technology 3-5 CSS

<head>
<title>Simple Selector Form</title>
<style type="text/css">
h1
{
font-family:Arial;
color:green;
} We can apply style to
h2,h3 more than one selector
{
font-family:Monotype Corsiva;
color:red;
font-size: 28pt;
}
</style>
` </head>
<body>
<h1>India is My Country</h1>
<h2>All the Indians are my brothers and sisters</h3>
<h3>I love my country</h3>
</body>
</html>
Output

Similarly the style can also be applied to the elements at specific positions.

For example :
body b p {font-size:18pt;}
Note that there are more than one element to which the style is applied and these elements are
separated by the white spaces.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3-6 CSS

3.4.2 Class Selectors


 Using class selector we can assign different styles to the same element.

 These different styles appear on different occurrences of that element.


For example
HTML Document[ClassSel.html]
<!DOCTYPE html>
<html>
<head>
<title>Class Selector Form</title>
<style type="text/css">
h1.RedText
{
font-family:Monotype Corsiva;
color:red;
font-size: 14pt;
}
h1.BlueText
{
font-family:Arial;
color:blue;
font-size: 10pt;
}
</style>
</head>
<body>
<h1 class ="RedText">India is My Country</h1>
<h1 class="BlueText">All the Indians are my brothers and sisters</h1>
<h3>I love my country</h3>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3-7 CSS

Script Explanation :
Note that in above given script we have used two different classes for the element h1. One class
selector is for displaying the string in red color and another is for displaying the string in blue
color. This definition is given in the head section. In the body section these class names appear in
double quotes inside the h1 tag.

Ex. 3.4.1 : Create a HTML document that displays a table of basketball scores at national games
in which the team names have their respective team colors. The score of the leading/wining team
should appear larger and in different font than the losing team. Use CSS.
Sol. : Football.html
<!DOCTYPE html>
<html >
<head>
<style type="text/css">
tr.one
{
background-color:pink;
color:blue;
}
tr.two
{
font-family:cursive;
background-color:black;
color:yellow;
font-size:50px;

} Output
tr.three
{
background-color:green;
color:white;
}
</style>
</head>
<body>
<table border="3">
<th>Team</th>
<th>Score</th>
<tr class="one"><td>ABC</td><td>7</td>
</tr>
<tr class="two"><td>XYZ</td><td>10</td>
</tr>
<tr class="three"><td>PQR</td><td>5</td>
TM
Technical Publications - An up thrust for knowledge
Web Technology 3-8 CSS

</tr>

</body>
</html>

3.4.3 Generic Selectors


 We define the class in generalised form.

 In the sense, that particular class can be applied to any tag.

 Here is the HTML document which makes use of such generic selector.

HTML Document [ClassSel1.html]


<!DOCTYPE html>
<html>
<head>
<title>Generic Class Selector Form</title>
<style type="text/css">
.RedText
{
font-family:Monotype Corsiva;
color:red;
}
</style>

</head>
<body>
<center>
<h1> Tongue Twister</h1>
</center>
<h2 class="RedText">
She sells sea shells on the sea shore.
</h2>
<h3 class="RedText">
The shells she sells are sea shells, I'm sure.
</h3>
<h4 class="RedText">
And if she sells sea shells on the sea shore,
</h4>
<p class="RedText">
Then l'm sure she sells seashore shells.
</p>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3-9 CSS

Output

Note that the class selector must be preceded by a dot operator.

3.4.4 Id Selectors
 The id selector is similar to the class selector but the only difference between the two is that
class selector can be applied to more than one elements where as using the id selector the style
can be applied to the one specific element.
 The syntax of using id selector is as follows -
#name_of_id {property:value list;}
 Following HTML document makes use of id selector

HTML Document[IdSel.html]
<!DOCTYPE html>
<html>
<head>
<title>id Selector</title>
<style type="text/css">
#top
{
font-family:Monotype Corsiva;
color:blue;
font-size:16pt;
}
</style>
</head>
<body>
<div id="top">

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 10 CSS

It is the mark of an educated mind to be able to


entertain a thought without accepting it.
</div>
<p>
-Aristotle
</p>
</body>
</html>
Output

3.4.5 Universal Selectors


This selector is denoted by * (asterisk). This selector can be applied to all the elements in the
document.

HTML Document[UniverSel.html]
<!DOCTYPE html>
<html >
<head>
<title>Universal Selector</title>
<style type="text/css">
*{
color:green;
}
</style>
</head>
<body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 11 CSS

<h2> Famous Proverbs</h2>


<hr/>
<ul type="disc">
<li>A friend in need is a friend indeed</li>
<li>Cleanliness is next to Godliness</li>
<li>All is fair in love and war</li>
<li>An apple a day keeps the doctor away</li>
<li>God helps them who help themselves</li>
<br/><br/>
<em>
-From My Collection.
</em>
</body>
</html>
Output

As we have defined the universal selector that sets the green color. Hence the text that is
appearing on the above web page is in green color.

3.4.6 Attribute Selector


 CSS allows authors to specify rules that match elements which have certain attributes defined in
the source document.
 The syntax is
[att] - Match when the element sets the "att" attribute, whatever the value of the attribute.
[att=val] - Match when the element's "att" attribute value is exactly "val".
 Example : In the following example all the <a> elements get selected with a target attribute.
<!DOCTYPE html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 12 CSS

<html>
<head>
<style>
a[target] {
background-color: red;
}
</style>
</head>
<body>
<p>The links with a target attribute gets a RED background:</p>
<h1><a href="https://www.google.com">Google</a> </h1>
<h2><a href="http://www.facebook.com" target="_blank">Facebook</a></h2>
</body>
</html>

Output

3.4.7 Pseudo Classes


Using pseudo classes we can give special effects on the selectors. There some pseudo classes
which are more commonly used and those are -
 Focus

 Hover

 Hyperlink
In the following XHTML documents we have used these pseudo classes.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 13 CSS

HTML Document[PsedoCls.htmll]
<!DOCTYPE html>
<html>
<head>
<title>Pseudo classes</title>
<style type="text/css">
input:focus

{
background-color:skyblue;
color:white;
}
</style>
</head>

<body>
<form>
Enter some string:<input type="text" name="my_txt"/>
<br/>
<input type="submit" value="Enter"/>
</form>
</body>
</html>

Output

Let us now see one more illustration in which the pseudo class is used.

HTML Document[PsedoCls1.html]
<!DOCTYPE html>
<html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 14 CSS

<head>
<title>Pseudo classes for hyperlinks</title>
<style type="text/css">
a.ColoredTxt:link {color: red}
a.ColoredTxt:visited {color: blue} We have defined two
a.ColoredTxt:hover {color: green} pseudo classes named
ColoredTxt and BigTxt
a.BigTxt:link {color: red}
a.BigTxt:visited {color: blue}

a.BigTxt:hover {font-size: 200%}

</style>
</head>
<body>
<h3>Move Mouse over following text</h3>
<p>
<em>
<a class="ColoredTxt" href="mypage.html" target="_blank">The text
changes color
</a>
</em>
</p>
<p>
<em>
<a class="BigTxt" href="mypage.html" target="_blank">The text is getting
Big in size
</a>
</em>
</p>
</body>

Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 15 CSS

3.4.8 Contextual Selector


 "Contextual selectors" in CSS allow you to specify different styles for different parts of your
document.
 You can assign styles directly to specific HTML tags, or you can create independent classes and
assign them to tags in the HTML.

For example –
<!DOCTYPE html>
<html>
<head>
<style>
pb{
font-family: Times, serif; /* Font family */
font-weight: bold; /* heavy faced type*/
color: blue; /* blue colour of the text */
}
</style>
</head>
<body>
<div><b>This line is in bold face font</b></div>
<p><b>This line is in bold face with the color of the text - blue </b></p>
<p> Good Bye</p>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 16 CSS

3.4.9 At Rules
The @import rule is used to import one style sheet into another. The syntax for using @import
is
@import url("mystyles.css")

3.5 Style Sheet and HTML


There are three levels of cascading style sheets -
 Inline style sheet

 Document level style sheet

 External level style sheet

3.5.1 Inline Style Sheet


The inline cascading style sheet is a kind of style sheet in which the styles can be applied to
HTML tags. This tag can be applied using following rule -
Tag
{
property: value
}

For example :
<p style="font-family: Arial;color:red" >
Here for the tag p two properties are used such as font-family and color and those are
associated with the values such as Arial and red respectively.
Note that if we want to use more than one property then we have to use separator such as
semicolon. In the following HTML document we have used cascading style sheet-
HTML Document [InlineStyle.html]
<!DOCTYPE html >
<html>
<head>
<title>Inline Cascading Style Sheet</title>
</head>
<body>
<p>This is simple text</p>
<p style="font-size: 30pt ;font-family:Script">This text is different </p>
<p style="font-size: 40pt ;color:#ff0000">This text is colored.</p>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 17 CSS

Script Explanation
1) In this document, in the body section the style sheets are created.
2) In this section first of all we have displayed a simple sentence This is simple text. There is no
style for this sentence.
3) In the next line, we have applied style in which font-size is set to the size of 30 point and
font-family is set by the font name "Script" .
4) Then colored text will be displayed by color:#ff0000". The first two digits ff denote the red
color, there is no green and blue color as the values next to ff are 00. Hence the text will be
displayed in red.
This can be very well illustrated in output.
Output

3.5.2 Document Level Style Sheet


 This type style sheet appears only in the head section and in the body section newly defined
Selector tags are used with the actual contents.
 For example : In the following HTML script we have defined h1, h2, h3 and p selectors. For
each of these selectors different property and values are set. Such setting will help us to
represent our web page in some decorative form.
 The most important thing while writing document level style sheet is that we should mention the
style type="text/css" in the head section. By this the browser will come to know that the
program is making use of cascading style sheet.

HTML Document [DocLevelCSS.html]


<!DOCTYPE html>
<html >

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 18 CSS

<head>
<title>Document Level style sheet</title>
<style type="text/css">
h1
{
font-family:Arial;
color:green
}
h2
{
font-family:Arial;
color:red;
left:20px
}
h3
{
font-family:arial;
color:blue;
}
p
{
font-size:14pt;
font-family:verdana
}
</style>
</head>
<body>
<h1>
<center>
This page is created using Document Level Style Sheet
</center>
</h1>
<h2>
This line is aligned left and red colored.
</h2>
<p>
The embedded style sheet is the most commonly used style sheet.
This paragraph is written in Verdana font with font size of 14.
</p>
<h3>
This is a blue <a href="colorname.html">colored</a> line.
</h3>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 19 CSS

Output

Script Explanation
1) In above program, we have defined all the selectors in the head sections only. And these
HTML elements are then used along with the web page contents.
2) The setting defined in the selectors will affect the web page contents. For example we have
defined the selector h2 as
h2 Selector

{
font-family:Arial;
color:red;
Property left:20px
Value
}
and then in the body section we have written -
<h2> This line is aligned left and red colored.</h2>
3) Now as h2 defines font to be "Arial" with color as "red" having left alignment of 20 pixels,
the sentence "This line is aligned left and red colored." will be displayed in Arial font, which
is red colored and aligned from left by 20 pixels. Surely we can see this effect on our web
browser.

3.5.3 External Stylesheet


 Sometimes we need to apply particular style to more than one web documents in such cases
external style sheets can be used.
 The central idea in this type of style sheet is that the desired style is stored in one .css file. And
the name of that file has to be mentioned in our web pages.
 Then the styles defined in .css file will be applied to all these web pages.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 20 CSS

 Here is a sample program in which external style sheet is used.


Step 1 : Create an HTML document

HTML Document[ExtCSS.html]
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" type="text/css" href="ex1.css" />
</head>
<body>
<h1 class="special"> <center> This page is created using External Style
Sheet</center> </h1>
<h2>
This line is aligned left and red colored.
</h2>
<p>
The External style sheet is the compact representation of Cascading Style Sheets.
This paragraph is written in Monotype Corsiva font with font size of 14.
</p>
<h3>
This is a blue <a href="colorname.html">colored</a> line.
</h3>
</body>
</html>
Step 2 : Create a css file which contains the styles that can be applied to different HTML elements
present in the above HTML document.
The cascading style sheet ex1.css can be
<!- - The file name ex1.css and can be opened in notepad.-->
h1
{
font-family:Arial
}
h2
{
font-family:times new roman;
color:red;
left:20px
}
h3
{
font-family:arial;
color:blue;
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 21 CSS

p
{
font-size:14pt;
font-family:Monotype Corsiva
}

Script Explanation
When we want to link the external style sheet then we have to use <link> tag which is to be
written in the head section.
 link tells the browser some file must be linked to the page.

 rel=stylesheet tells the browser that this hyperlink is a style sheet.

 href=" " denotes the path name of style sheet file.


 type="text/css" tells the browser that what it is reading is text which is affected by the
cascading style sheet.

3.6 Style Rule Cascading and Inheritance

3.6.1 Style Rule Cascading


 When there are two or more values for the same property then conflict occurs. There are various
levels of style sheets such as embedded CSS and external CSS. Out of which embedded CSS
have more precedence over the external CSS.
 There are some sorting order rules that are used to decide the precedence. These are based on
two things, importance (important or normal) of the property and origin (author origin, user
origin and user agent origin). Let us first understand the terms important and origins.
 The keyword !important can be applied to specify that particular property is important. For
example :
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 22 CSS

p.myclass {font-family:Arial !important ;font-style:bold;}


specifies that the font being Arial is one property but font-style being bold is a important
property.
 When the specification is marked by !important then it actually specifies the weight. The weight
can be either important or normal.
 The origin can be author origin, user origin and user agent origin. These terms can be defined as
follows -
o Author is a person who writes the XHTML document and associated style sheets.
o User is a person who interacts with user agent and use the web document along with the
associated style sheets.
o User agent is a program that interprets the web document written in scripting language
and applies the style sheet according to the specification. For example, HTML is an user
agent.
 The sorting order can be determined by applying following rules with highest precedence to
lowest -
1. Important declaration having user origin.
2. Important declaration having author origin.
3. Normal declaration having author origin.
4. Normal declaration having user origin.
5. Any declaration (either important or normal) with user agent (i.e. browser) origin.
 Following rules are also be used to decide the sorting order of the elements from highest
precedence to lowest -
1. id selectors have the highest precedence.
2. class and pseudo class selectors
3. Contextual selectors
4. Universal selectors
 If the conflict still occurs then it can be resolved writing the properties in the specification. The
rules that are defined later in the document tree have the highest precedence than those defined
earlier.
 Style rule cascading can be defined as the process which is used to resolve the conflicts in the
style specification. Fig. 3.6.1 shows the steps in CSS cascade.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 23 CSS

Fig. 3.6.1 Steps in CSS cascade

3.6.2 Inheritance
 In CSS, if a property of an element has no associated declarations then using inheritance
technique the value for this property can be obtained.
 In an HTML document, the tags have parent-child relationships. For example, <title> tag is
always inside the <head> tag, so the <head> tag is the parent of the <title> tag. Similarly <p>
tag is defined inside the <body> tag. Then <body> becomes parent of <p> tag.
 In cascading style sheets, inheritance is based on tree structure of the document itself.

 An element inherits the value for its properties by checking the parent element. If the parent has
the value for the property demanded by the child then this property value can be inherited. If the
parent down not have this value, then its parent (i.e. grandparent) is checked. If this parent has
no such property value then its parent is checked. This process is continued until a root element
is obtained.
 Thus the search will be made in upward direction from the parent of the element to the root of
the tree or to the <html> tag of the document.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 24 CSS

Inheritance can be defined as a concept in which child always inherits the properties of parent
tag along with its own properties.
Following is an HML document in which inheritance is demonstrated.

HTML Document
<!DOCTYPE html>
<html>
<head>
<title>Inheritance Demo</title>
<style type="text/css">
p
{
font-family:Arial;
color:blue;
background-color:yellow;
}
strong
{
font-size:24px;
}
</style>
</head>
<body>
<center>
<p>This is a blue text <strong>with</strong> yellow background</p>
</center>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 25 CSS

Script Explanation :
In above, script <p> tag has some properties as Arial font, blue font color and yellow
background. The <strong> tag has only one property can that is font-size which is assigned by the
value 24px. But in the body section, <strong> tag is the child of <p> tag. And note that <strong>
inherits the properties of <p> tag. Hence the text defined under<strong> tag is also blue colored
with yellow background.
Now just modify by the above script as follows and observe the sample output.

HTML Document [inheritance1.html]


<!DOCTYPE html>
<html>
<head>
<title>Inheritance Demo</title>
<style type="text/css">
li
{
font-style:italic
}
p
{
font-family:Arial;
color:blue;
background-color:yellow
}
strong
{
font-size:24px
}
</style>
</head>

<body> Added <li> tag as grand parent for


<center> <strong> tag.
<li>
<p>This is a blue text <strong>with</strong> yellow background</p>
</li>
</center>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 26 CSS

Output

Note that the above style sheet contains the nested tags -
<li>
…..<p>
………….<strong>
………….</strong>
…..</p>
</li>
The <li> tag contains the italic property. Hence the text inside the <strong> tag becomes italic.
That means <strong> tag has inherited the italic property from its grandchild.

3.7 Text Properties


The font properties can be setting different types of fonts, styles and sizes.

3.7.1 Font Families


The font-family denotes different types of fonts such as Arial, Times New Roman, Script,
monospace and so on. Following are some examples of generic fonts

Generic Font Name Example

sans-serif Arial, Helvetica, Futura

cursive Zapf-chancery

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 27 CSS

fantasy Critter, Cottonwood

monospace Courier, Prestige

serif Times New Roman,Garamond


Let us see usage of font-family property in HTML document.

HTML Document[FontFamily.html]
<!DOCTYPE html>
<html>
<head>
<title>Font Family Demo</title>
<style type="text/css">
h1
Output
{
font-family:Arial;
}
h2
{
font-family:script;
}
h3
{
font-family:‘Times New Roman’;
}
h4
{
font-family:fantasy;
}
h5
{
font-family:Garamond;
}
</style>
</head>
<body>
<h1>This text is in Arial </h1>
<h2>This text is in script </h2>
<h3>This text is in Times New Roman</h3>
<h4> This text is in fantasy</h4>
<h5> This text is in Garamond</h5>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 28 CSS

</body>
</html>
If the font name has more than one word then the name should be enclosed by the
single quotes. Although quotes are not mandatory, it is a good practice to use quotes for
specifying the font name.

3.7.2 Font Sizes


This property is used to specify the size of the font. One can specify the font size in points (pts),
pixels (px) or in percentage (%). We can also specify the font size using the relative values such as
small, medium, large. Use of font size in such a way is relative. And the disadvantage of using
such relative sizes is that one cannot have the strict control over the font-size. Different browsers
may have different font size values.
In the following HTML document we will use the font-size property.

HTML Document[FontSize.html]
<!DOCTYPE html>
<html>
<head>
Output
<title>Font-Size Demo</title>
<style type="text/css">
h1
{
font-size:10pt;
}
h2
{
font-size:20px;
}
h3
{
font-size:xx-large;
}
h4
{
font-size:250%;
}

</style>
</head>
<body>
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 29 CSS

<h1>Programming the Web</h1>


<h2>Programming the Web</h2>
<h3>Programming the Web</h3>
<h4>Programming the Web</h4>
</body>
</html>

3.7.3 Font Variants


The font variation can be achieved by making setting the font in upper case or in lower case.
We use font-variant property for this purpose.

Value Meaning

normal The font can be displayed in normal form.

small-caps The font can be displayed in small capital letters.

HTML Document[FontVariant.html]
<!DOCTYPE html>
<html>
<head>
<title>Font-Variant Demo</title>
<style type="text/css">
h1
Output
{
font-variant:small-caps;
}

</style>
</head>
<body>
<h1>Programming the Web</h1>
</body>
</html>

3.7.4 Font Styles


Various font styles are -
 normal

 italic

 oblique
The illustration is as given below -

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 30 CSS

HTML Document[FontSt.html]
<!DOCTYPE html>
<html
<head>
<title>Font-Style Demo</title>
<style type="text/css">
h3.normal { font-style:normal;}
h3.italic { font-style:italic;}
h3.oblique { font-style:oblique;}
</style>
</head>
<body>
<h3 class="normal">Programming the Web</h3>
<h3 class="italic">Programming the Web</h3>
<h3 class="oblique">Programming the Web</h3>
</body>
</html>
Output

3.7.5 Font Weights

Various font styles are -


 Normal (by default)

 Bold

 Bolder

 Lighter
The illustration is as given below -

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 31 CSS

HTML Document[FontWt.html]
<!DOCTYPE html>
<html>
<head>
<title>Font-Weight Demo</title>
<style type="text/css">
p.normal { font-weight:normal;}
p.bold { font-weight:bold;}
p.bolder { font-weight:bolder;}
p.lighter { font-weight:lighter;}
</style>
</head>
<body>
<p class="normal">Programming the Web</p>
<p class="bold">Programming the Web</p>
<p class="lighter">Programming the Web</p>
<p class="bolder">Programming the Web</p>
</body>
</html>
Output

3.7.6 Font Shorthands


We can specify more than one font properties in a list
For example

HTML Document[Fontshrthnd.html]
<!DOCTYPE html>
<html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 32 CSS

<head>
<title>Font Properties</title>
<style type="text/css">
p.myfont {font-family:Courier New;
font-style:italic;
font-weight:bold;
font-size:28pt;
}
</style>
</head>
<body>
<p class="myfont">I Love my Country!!!</p>
</body>
</html>
Output

3.7.7 Text Decoration


Using text decoration property we can include special features in the text. Various properties of
text decoration are
 underline

 overline

 line-through

HTML Document[TxtDecor.html]
<!DOCTYPE html>
<html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 33 CSS

<head>
<title>Text Decoration</title>
<style type="text/css">
p.linethrough {text-decoration:line-through;}
p.underline {text-decoration:underline;}
p.overline {text-decoration:overline;}
p.normal {text-decoration:normal;}

</style>
</head>
<body>
<p class="linethrough"> This text is having linethrough </p>
<p class="overline"> This text is having overline </p>
<p class="underline"> This text is having underline </p>
<p class="normal"> This text is a normal text </p>

</body>
</html>
Output

3.7.8 Alignment of Text


Using cascading style sheets we can align the text. This alignment can be done using following
properties such as -

Property Value Meaning

text-align left Aligning the text to the left.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 34 CSS

text-align right Aligning the text to the right

text-align center Alignment of text at the centre.

text-indent value in inches Desired indentation of the text can be applied.

Following is script which uses various text alignment properties.

HTML Document[TextAlignCSS.html]
<!DOCTYPE html>
<html>
<head>
<title>Text Alignment Demo</title>
<style type="text/css">
h1
{
font-family:Arial;
font-size:15px;
text-align:left;
}
h2
{
font-family:Arial;
font-size:15px;
text-align:right;
}
h3
{
font-family:Arial;
font-size:15px;
text-align:center;
}
</style>
</head>

<body>
<h1>This line is aligned at left</h1>
<h2>This line is aligned at right</h2>
<h3>This line is aligned at center</h3>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 35 CSS

Output

University Question

1. Explain any eight CSS text properties. AU : Dec.11, Marks 8

3.8 Box Model


The box comes in picture when we put the contents within some rectangle. The box model
represents the contents, inner edge, outer edge, margins and padding. It is as shown in Fig. 3.8.1.

Fig. 3.8.1 The box model

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 36 CSS

Let us understand each of these terms along with suitable illustrations

3.8.1 Borders
There is a property called border-style which controls the element’s content border.

HTML Document[BorderStyle.html]
<!DOCTYPE html >
<html >
<head>
<title>A Border Style Demo</title>
<style type="text/css">
h4.none {border-style:none}
h4.dotted {border-style:dotted}
h4.dashed {border-style:dashed}
h4.solid {border-style:solid}
h4.double {border-style:double}
h4.groove {border-style:groove}
h4.ridge {border-style:ridge}
h4.inset {border-style:inset}
h4.outset {border-style:outset}
h4.hidden {border-style:hidden}
</style>
</head>
<body>
<h4 class="none">This text has no border</h4>
<h4 class="dotted">This text has a dotted border.</h4>
<h4 class="dashed">This text has dashed border.</h4>
<h4 class="hidden">This text has hidden border.</h4>
<h4 class="double">This text has double border.</h4>
<h4 class="solid">This text has solid border.</h4>
<h4 class="groove">This text has groove border.</h4>
<h4 class="ridge">This text has ridge border.</h4>
<h4 class="inset">This text has inset border.</h4>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 37 CSS

Output

There is another property and that is border-width which defined the width of the
border. The width can be specified in terms of pixels. The border-width property is
illustrated in the following example.

HTML Document[BorderWidth.html]
<!DOCTYPE html >
<html >
<head>
<title>A Border Width Demo</title>
<style type="text/css">
h4.thick
{
border-style:solid;
border-width:3px;
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 38 CSS

h4.thicker Output
{
border-style:solid;
border-width:5px;
}
h4.thickest
{
border-style:solid;
border-width:7px;
}
</style>
</head>
<body>
<h4 class="thick">Thick.</h4>
<h4 class="thicker">Thicker.</h4>
<h4 class="thickest">Thickest.</h4>
</body>
</html>
We can make the borders colourful using border-color property. Following script displays the
colored borders.

HTML Document[BorderColor.html]
<!DOCTYPE html>
<html>
<head>
<title>Colored Border Demo</title>
<style type="text/css">
h4.thickred
{
border-style:solid;
border-width:3px;
border-color:red;
}
h4.thickergreen
{
border-style:solid;
border-width:5px;
border-color:green;
}
h4.thickestblue
{
border-style:solid;

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 39 CSS

border-width:7px;
border-color:blue;
}
</style>
</head>
<body>
<h4 class="thickred">Red Border.</h4>
<h4 class="thickergreen">Green Border.</h4>
<h4 class="thickestblue">Blue Border.</h4>
</body>
</html>

Output

We can also specify the individual side of the box by some particular style. For example we can
display a box with the solid border on the top and right, dashed border on the bottom and dotted
border on the left. Thus any possible combinations with all four sides can be made using the
individual border style property.
Hence we can use -
 border-top-style:solid;

 border-right-style:solid;

 border-bottom-style:dashed;

 border-left-style:dotted;
OR
 border-style:solid solid dashed dotted

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 40 CSS

HTML Document[EachBorder.html]
<!DOCTYPE html>
<html>
<head>
<title>Setting Indivudual borderBorder Demo</title>
<style type="text/css">
h4.method1
{
border-top-style:solid;
border-right-style:solid;
border-bottom-style:dashed;
border-left-style:dotted;
}
h4.method2
{
border-style:solid solid dashed dotted;
border-color:green;
}
</style>
</head>
<body>
<h4 class="method1">Box by One Method</h4>
<br/><br/>
<h4 class="method2">Box by another Method</h4>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 41 CSS

3.8.2 Margins and Padding


Margin means the space between the content and its neighbouring content. There can be top
margin, bottom margin, left margin and right margin. Hence various properties of margins are
margin-top, margin-bottom, margin-left and margin-right. The values of these properties can be
given in px and in.

HTML Document[MarginDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Margin Demo</title>
<style type="text/css">
p.method1
{
border-style:solid;
margin-top:80px;
margin-bottom:60px;
margin-left:30px;
margin-right:70px;
}
</style>
</head>
<body>
<h3>Neighbouring Text</h3>
<p class="method1">Text</p>
<em>
<pre>Note:Just change the margin values of the above Text
and notice the effect on the browser
</pre>
</em>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 42 CSS

Output

Just change the values of the properties such as margin-top, margin-bottom, margin-left and
margin-right of the above given XHTML document and observe the change in the web browser.
Thus by experimenting the above script in this way, you can understand the actual meaning of the
margin.
Padding means the space between the contents and its border. Various properties of padding
are padding-left, padding-right, padding-top and padding bottom. These values can also be given in
px or in in.

HTML Document[PaddingDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Padding Demo</title>
<style type="text/css">
p.method1
{
border-style:solid;
padding-top:70px;
padding-bottom:50px;
padding-left:120px;
padding-right:60px;
}
</style>
</head>
<body>
<p class="method1">My Text</p>
<em>
<pre>Note:Just change the padding values of the above Text
and notice the effect on the browser
</pre>
</em>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 43 CSS

</body>
</html>

Output

Just change the values of the properties such as padding-top, padding-bottom, padding-left and
padding-right of the above given XHTML document and observe the change in the web browser.
Thus by experimenting the above script in this way, you can understand the actual meaning of the
padding.

Review Questions

1. Explain the box modeling of CSS

3.9 Color

3.9.1 Color Groups


There are three groups of colors. Those are as given below -
1. This is the smallest group of colors. In this group there are 16 colors. These are named colors.
The colors in this group are enlisted as follows.
Sr. No. Color Name Hexadecimal Value
1 black 000000
2 red FF0000
3 lime 00FF00

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 44 CSS

4 blue 0000FF
5 yellow FFFF00
6 fuchsia FF00FF
7 aqua 00FFFF
8 white FFFFFF
9 silver C0C0C0
10 gray 808080
11 maroon 800000
12 purple 800080
13 green 008000
14 olive 808000
15 navy 000080
16 teal 008080

These colors get displayed as it is on the web browsers. And all the web browsers support
these colors.
2. There is a set of 216 colors which is called web palette. The elements of such colors are red,
green and blue. The values of these elements can be 00, 33, 66, 99, CC and FF.
3. These are 16 millions colors. These are 24-bit colors.

3.9.2 Color Properties


Using color property we can set the foreground color and using background-color the
background color can be set. The use of these properties is shown in XHTML document.

HTML Document [colorProperties.html]


<!DOCTYPE html>
<html>
<head>
<title>Color Properties</title>
<style type="text/css">
h1
{
font-family:Arial;
color:green;
background-color:yellow;
}
</style>
</head>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 45 CSS

<body>
<center>
<h1>This is a green text with yellow background</h1>
</center>
</body>
</html>

Output

3.10 Background Image


Using background-image property an image can be set as background.

HTML Document[BackImg.html]
<!DOCTYPE html>
<html>
<head>
<title>Background Image</title>
<style type="text/css">
body {background-image:url(victoriafalls.jpg);
background-repeat:no-repeat; }
p
{
font-family:Arial;
font-size:20px;
}
</style>
</head>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 46 CSS

<body>
<center>
<h2>Wonder of the World</h2>
</center>
<p>
The Vicorial waterfall is one of the greatest waterfalls in the world.
It lies on the Zimbezi river which is between the border of Zambia and Zimbabwe.
The Victoria fall can be seen from 25 to 40 miles away.
The roaring of the water can be heard from a long distance.
The native people call it as “mosi-oa-tunya”, that means “smoke that thunders”.
Victoria falls was discovered by David Livingstone in 1855.
The falls were named in honor of Queen Victoria.
</p>
</body>
</html>
Output

It is expected that the foreground text over the image should be visible. That means the color of
the background image must not be the same as the color of the text written over it.
 Background-repeat property
The background-image property sets the background image with repetition. If we want to
control the repetition of the image then we must set the background-repeat property. The

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 47 CSS

values of this property could be no-repeat, repeat-x, repeat-y or repeat(default). The repeat-x
means the background image gets repeated over the x-axis(horizontally) and repeat-y means
the background image gets repeated over the y-axis(vertically).
 Background-position property
Various values for back-ground position property could be top, bottom, left and right

Ex. 3.10.1 : Write a CSS rule that places a background image halfway down the page, tilting it
horizontally. The image should remain in place when the use scrolls up or down.
Sol. :<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p
{
font-size:40px;
color:magenta;

}
body
{

background-image:url(baby.jpg);
background-repeat:repeat-x;
background-attachment:fixed;
}
</style>
</head>
<body>
<p>
Twinkle, twinkle, little star, How I wonder what you are.Up above the world so high, Like a
diamond in the sky.Twinkle, twinkle, little star, How I wonder what you are!
When the blazing sun is gone, When there's nothing he shines upon,Then you show your little
light, Twinkle, twinkle, through the night.
Twinkle, twinkle, little star, How I wonder what you are!
In the dark blue sky so deep Through my curtains often peep For you never close your eyes
Til the morning sun does rise
Twinkle, twinkle, little star How I wonder what you are Twinkle, twinkle, little star How I
wonder what you are
</p>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 48 CSS

Ex. 3.10.2 : Create a web page to create a fixed background image.


AU : May-09, Marks 2
Sol. :
<html>
<head>
<style type="text/css">
body
{
background-image:url("Myimg.jpg");
background-repeat:no-repeat
}
</style>
</head>
No repeat creates fixed background image
<body>
<center>
<h1>Life is beautiful!!!</h1>
</center>
</body>
</html>

Output

Ex. 3.10.3 : Write a CSS which adds background images and indentation.
AU : May-13, Marks 8
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 49 CSS

Sol. :
<html>
<head>
<style type="text/css">
body
{
background-image:url("Rose.jpg");
background-repeat:no-repeat
}
p {text-indent:50px;}
</style>
</head>
<body>
<center>
<p>Roses are beautiful.</p>
</center>
</body>
</html>

3.11 Normal Flow Box Layout


 Normal flow is the default scheme used for positioning. It applies to any element of the web
document.
 In this scheme, the two boxes are used -
1. Block box 2. Inline box.
 The block boxes flow vertically starting at the top of their containing block with each placed
directly below the preceding one. Inline boxes flow horizontally from left to right.

3.11.1 Basic Box Layout


 In any XHTML document, the <html> is the root element. Corresponding to this element a
browser generates a box called initial containing block. If browser’s horizontal and vertical
scroll bars are not active then the client area and the initial containing block become one and
the same.
 It is assumed that the web document is placed on an imaginary area called canvas. The browser
client area acts as a viewport to view the portion of the web document.
 All the relative CSS boxes will be added to the initial containing block. For instance the box
corresponding to the body element will be placed inside the initial containing block. Thus if B
element is inside the element A then the box corresponding to B will be placed inside the box
corresponding to A which in turn will be inside the initial containing block box. Thus the

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 50 CSS

normal flow processing of the blocks occurs from outer block to inner. This behaviour is known
as normal flow processing of boxes.

Fig. 3.11.1 Normal flow processing

 If the browser window is changed then the width of the block box of the body element gets
changed and accordingly the width of the other block elements gets changed. The height of the
block box varies according to the contents of the elements.

3.11.2 The Display Property


 The CSS defines the following HTML elements as the block elements - body, div, dt, dd,
fieldset, form, frame, frameset, hr, html, h1, h2, h3, h4, h5, h6, ol, p, pre and ul.
 Examples of display property are -
p {display:block}
em{display:inline}
pre{display:block}
table{display:table}
 Following script illustrates the use of display property.

XHTML document[DisplayDemo.html]

<!DOCTYPE html >


<html>
<head>
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 51 CSS

<title>Display property</title>
<style type="text/css">
p
{
background-color:yellow;
display:block;
border:solid
}
em
{
background-color:white;
display:inline;
border:dotted
}
</style>
</head>
<body>
<p>
This is a test for the normal flow processing.
</p>
<p>
The display<em>property is illustrated</em> here
</p>
</body>
</html>
Output

This is a nested box as


element em is inside the
element p

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 52 CSS

3.11.3 Margin Collapse


When two consecutive block boxes are displayed on the browser window then the separation
between these block boxes is defined by a special rule called margin collapse. According to this
rule, the bottom margin of the upper box and the top margin of the lower box are collapsed in a
single margin.

Fig. 3.11.2 Margin collapse

3.11.4 Inline Box


The HTML elements span and strong are treated as the inline elements. Hence the boxes
corresponding to these elements are called inline boxes. Using the display property one can define
the inline box. The inline elements are those elements that do not form new blocks of content; the
content is distributed in lines. The inline boxes may contain some text or some images.

XHTML Document[inlineblock.html]
<!DOCTYPE html >
<html>
<head>
<title>Inline block box</title>
<style type="text/css">
div
{
background-color:yellow;
border:solid
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 53 CSS

span
The inline block
{
box corresponds to
background-color:white;
the element span
display:inline;
border:dotted
}
</style>
</head>
<body>
<div>
This is a test for the normal flow processing.
There are two types of blocks defined in this flow processing.
The block box and inline block box.
Out of which the inline <span>block box is illustrated</span> here.
This is nested inline block box.
Beyond the normal flow processing, positioning of the elements can also be controlled. </div>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 54 CSS

Review Questions

1. What is normal flow processing of boxes ?


2. Write an XHTML document that illustrates the display property.
3. What do you understand by the term margin collapse ?
4. What is inline element ?

3.12 Beyond Normal Flow


Using CSS a web designer can have a full control over positioning of the elements. For that
purpose a position property is used. CSS allows to control the position of the element using three
methods -

Let us discuss each of them with illustrative examples.

3.12.1 Absolute Positioning


Following is an illustration positioning the element using absolute positioning.

XHTML document [Position_Demo1.html]


<!DOCTYPE html >
<html >
<head>
<title></title>
<style type="text/css">
.text_pos
{
position:absolute;
left:150px;
top:-10px;
font-family:script;
font-size:50px;
width:100px;
}
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 55 CSS

</style>
</head>
<body>
<p>Taj Mahal is one of the wonders of the World. It is located in

Agra,India.Taj Mahal is built by Shah Jahan in memory of his wife

Mumtaz Mahal.
</p>
<p>It is considered to be the excellent example of Mughal

Architecture.</p>
<p class="text_pos">History of Taj Mahal</p>
</body>
</html>
Output

Note that we have used a class named “text_pos” for positioning the text “History of Taj
Mahal”. In this class we have used left and top values for denoting the space from left and top
within the browser window. The absolute positioning defines a new co-ordinate system for
positioning of child elements. This co-ordinate system has its origin at the top, left corner of the
element. The position is measured from the upper left corner of the browser window. The element
can be absolutely positioned inside another positioned element.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 56 CSS

The width property is for uniformly embedding the text inside another element. If the width is
not specified, the element will extend to immediately inside the right outer edge of the parent
element. The height, if not specified, will be just large enough for the contents of the element. For
understanding the absolute positioning just change the left, top and width values from above script
and notice the changes in the browser window.

3.12.2 Relative Positioning


If we assign the value to the position attribute as relative then the corresponding element gets
placed at the relative position to the previous contents. For instance if there is a paragraph which is
starting from leftmost and topmost position in the browser’s window and if we want to place the
element <h1> with top:70px then <h1> will be displayed 70 pixels from paragraph. Thus relative
positions get decided with respect to the previous contents.
Following is an example in which relative positioning is used.

XHTML Document[Position_Demo2.html]
<!DOCTYPE html >
<html >
<head>
<title>Relative and Absolute positioning</title>
<style type="text/css">
.text_pos1
{
position:relative;
top:10px;
font-family:script;
font-size:30px;
width:400px;
}
.text_pos2
{
position:absolute;
top:10px;
font-family:Arial;
font-size:30px;
width:400px;
}

</style>
</head>
<body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 57 CSS

<p>Taj Mahal is one of the wonders of the World. It is located in Agra,India.Taj Mahal is built by
Shah Jahan in memory of his wife Mumtaz Mahal.
</p>
<p>It is considered to be the excellent example of Mughal Architecture.</p>
<p class="text_pos1">This is relative position</p>
<p class="text_pos2">This is absolute position</p>
</body></html>

Script Explanation
In above script, we have defined two classes text_pos1 and text_pos2. Both the classes have
the same positional values i.e. left and top. Both are having same font-size and width parameter.
Only font-family is changed to differ the look of both the elements. And the text_pos1 has the
position property set to relative position and text_pos2 has the position property which is set to
absolute position. Hence text_pos1 (relative positioning) will be placed at the relative position
from the previous text which is denoted by <p> tag. And absolute positioning will be the default
positioning which does not consider the position of previous text. This difference between relative
and absolute positioning can be well understood by following output.
Output

3.12.3 Float Position


The float position is used to shift an image to one side and wrap the text around it.
In the following example, the image is shifted to the right and the text is wrap around it. We
have used float:right for this pupose. If one wants to shift the image to the left he can simply
declare the style as float:left.

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 58 CSS

XHTML Document[FloatPosDemo.html]
<!DOCTYPE html >
<html >
<head>
<title>Float Positioning</title>
<style type="text/css">
img.Rightfloat
{
float:right;
margin: 4px;
}
</style>
</head>
<body>
<img src="TajMahal.jpg" class=" Rightfloat"/>
<p>Taj Mahal is one of the wonders of the World. It is located in
Agra,India.Taj Mahal is built by Shah Jahan in memory of his wife
Mumtaz Mahal.
</p>
<p>It is considered to be the excellent example of Mughal
Architecture.</p>
</body>
</html>

Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 59 CSS

Review Questions

1. What is CSS positioning? Explain it with illustrative examples.


2. List and explain the various positioning schemes in detail.

3.13 CSS 3.0


 The CSS3 is a latest version of CSS.

 It is completely backward compatible with older version of CSS.

 It support for selectors, box model, Background and borders, Text effects, animations, Multiple
column layout, 3D transformations and so on.
Let us discuss some remarkable features introduced in CSS3.

3.13.1 CSS Border


CSS3 allows to create following types border
1. border-radius 2. box-shadow 3. border-image
Let us discuss them along with the necessary illustrations.

1. The border-radius
The border-radius property allows the developer to create round corners in the design. If we
set a single value to border-radius then that means all the round corners will be of same value. For
example - Following line represents that all the round corners are of 10px radius.
border-radius: 10px;
Following script represents this property
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 3px solid red;
padding: 10px 60px; All four corners are of
background: yellow; radius of 30pixel.
width: 300px;
border-radius: 30px;
}
</style>
</head>
<body>
<div>This design has round corner</div>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 60 CSS

</body>
</html>
Output

2. The border shadow


The border-shadow property represents the shadows around the border. For example-
border-shadow : 10x 20x 5x black

Horizontal shadow Verticle Shadow blur distance Color of shadow

Following script represents this property


<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: yellow;
box-shadow: 10px 20px 5px blue;
}
</style>
</head>
<body>
<div> </div>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 61 CSS

Output

3. The border-image
The border-image property is for setting the image as a border. Following example illustrates
the idea
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: pink;
border: 20px solid transparent;
border-image-source: url('flower.png'); //image as a border
// The inward offsets of each side of image-border is specified by image-slice
border-image-slice: 20;
border-image-repeat: repeat; //repeat the image border
}
</style>
</head>
<body>
<div>
This design has a image border
</div>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 62 CSS

Output

Explanation
The image file can be provided to the border-image-source style using the url. The border-
image-slice specifies the inward offset of each side of the border image. It can be denoted by a
value or percentage. The syntax for border-image-slice is given by following example.
border-image-slice: 20% 30% 30% 20%; /* top right bottom left*/
If a single value is provided then that means all the four corners are sliced using the same
number.
By the border-image-repeat property the slice gets repeated from the center of the side to fill
the space.

3.13.2 CSS3 Text Effects


In this section we will discuss various text effects mainly used in CSS3.

1. Text Shadow Effect


The CSS3 allows to incorporate many advanced text effects in the web design. Out of which the
text shadow effect is very commonly used.
The text-shadow property can be as given below -
text-shadow: horizontal_shadow vertical_shadow blur_distance color_of_shadow
Let us now understand how to apply and experience this text style.
<!DOCTYPE html>
<html>
<head>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 63 CSS

<style>
h2 {
text-shadow: -5px 15px 3px gray;
}
</style>
</head>
<body>

<h2>Catch me If you can...</h2>


</body>
</html>
Output

2. Text Wrap Effect


Another useful effect is text wrap effect. By this effect the text in a paragraph gets wrapped on
the next line. This effect can be achieved by breaking the word -
word-wrap: break-word

Following is a simple CSS script in which the text wrap effect is used.
<!DOCTYPE html>
<html>
<head>
<style>
div.wrapdemo
{
width: 130px;
border: 1px solid red;
word-wrap: break-word;
}
</style>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 64 CSS

</head>
<body>

<div class="wrapdemo"> There was once a Merchant who had three daughters, the youngest of
whom was so beautiful that everybody called her Beauty. This made the two eldest very jealous; and,
as they were spiteful and bad-tempered by
nature, instead of loving their younger sister they felt nothing but envyandhatredtowardsher.</div>
</body>
</html>
Output

Note that the long sentence in a paragraph


gets wrapped and the remaining is displayed
on the next line.

Two Marks Questions with Answers

Q.1 What is CSS file ?


Ans. : The cascading style is many times defined in a separate file. This file is called CSS file.
In CSS file one or more style rules are given.
Q.2 Give the syntax of CSS rule. AU : Dec.-11, May-12

Ans. :
<style type="text/css">
h1

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 65 CSS

{
font-family:Arial;
color:green
}
</style>
Q.3 What are style sheets ?

Ans. : The style sheets are the collection of styles that can be either embedded within the
HTML documents or can be externally applied. The Cascading style sheet is a markup language
used to apply the styles to HTML elements.
Q.4 What is selector string ? Specify any three forms of selectors.
Ans. : The ruleset in CSS consists of selector string which is basically an HTML element.
These selectors can be defined with the help of properties and values.
Q.5 How do you provide uniform access to structured documents in diverse applications ?
AU : Dec.-08
Ans. : Style sheets allow the user to decide the style of presentation. This presentation can be
defined in a separate file. And simply by including this file in various web documents the
designated style can be applied to the corresponding tag. For example - If we define
h1
{
font_size : 20 pt
color : red
}
Then every line defined by h1 tag will be of size 20 pt and red in color.
Q.6 Mention the need for cascading style sheet. AU : May-11
Ans. : The cascading style sheet allows separation between the information contained in a
document and its presentation. Hence any change in presentation can be made without disturbing
the information of the document. The cascading style sheet allows the developer to give the
consistent appearance to all elements of the web page.
Q.7 What do you mean by the term ruleset ?
Ans. : The styles are defined in separate file. This file is called CSS file. The collection of rules
in a CSS file is called ruleset.
Q.8 Enlist various categories of properties used in CSS
Ans. : The various categories of properties in CSS are -
1) Fonts 2) List 3) Alignment of Text 4) Color
5) Margins 6) Background 7) Borders.
Q.9 What is the use of universal selector ?

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 66 CSS

Ans. : Using the universal selector the values can be defined for all the elements in the
document. It is denoted by *.
Q.10 What is generic class selector ?
Ans. : The generic class applied to any tag in the HTML document. And thus the values
defined within that generic selector can be applied to the corresponding tag. The class selector
must be preceded by the dot operator.
Q.11 Enlist the three commonly used pseudo classes.
Ans. : The three commonly used pseudo classes are -
1. focus 2. hover 3. hyperlink
Q.12 Define the hover element.
Ans. : The hover is associated with anchor element and the selector for this element is specified
by a:hover. When the mouse is moved over the element then the pseudo class get activated.
Q.13 What are the advantages of external style sheet ?
Ans. : When we use external style sheet then the style is defined in one file and actual contents
of the web page are defined in another file. Hence if we want to change the style of presentation
of web page then we can simply modify the file in which the style is defined.
Q.14 What is the difference between the external style sheet and embedded style sheet ?
Ans. : The external style sheet is a kind of style sheet in which the styles are defined in a
separate .css file and this file is mentioned at the beginning of the HTML document. When we
need to apply the particular style to more than one web documents then the external style sheet is
used. The embedded style sheet is a method in which the style is specified (or embedded ) within
the HTML document itself. It is not defined in separate file. Due to embedded style sheet unique
style can be applied to all the elements.
Q.15 What is the significance of Box Model in CSS ?
Ans. : The box model in CSS represents the contents, inner edge, outer edge, margins and
padding.
Q.16 What do you mean by margin and padding ?
Ans. : Margin means the space between the content and its neighbouring contents. Padding
means the space between the contents and its border.
Q.17 What is the use of float position ?
Ans. : The float position is used to shift an image to one side and wrap the text around it.

Q.18 What is CSS padding ? AU : Dec.-09

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 67 CSS

Ans. : CSS padding is a property that allows to have space between the border and actual
content. This space can be at the top, bottom, left and right. For example - Following is a CSS
script that creates padding around the sentence.
<html>
<head>
<style type="text/css">
h3
{
background-color:green;
}
h3.padding
{
padding-top:50px;
padding-bottom:50px;
padding-right:50px;
padding-left:50px;
}
</style>
</head>
<body> This text coil
<h3>This is a simple text without padding</h3> have padding at
<h3 class="padding">This text have padding around it</h3> top bottom left
</body> and right
</html>
Q.19 If you do not want repeated background images then how will you apply the style ?

Ans. : For not repeated background images the following style can be set :
body
{
background-image:url("Myimg.jpg");
background-repeat:no-repeat
}
Q.20 What do you mean by the term inline element ?

Ans. : The inline elements are those elements that do not form new blocks of content. The
content is distributed in lines.
Q.21 List two forms of style rules with an example. AU : Dec.-12

Ans. : 1. Universal Selector


This selector is denoted by * (asterisk). This selector can be applied to all the elements in the
document.
For example -
<style type="text/css">

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 68 CSS

*{
color:green;
}
</style>

2. Class Selector
Using class selector we can assign different styles to the same element. These different styles
appear on different occurrences of that element.
For example :
<style type="text/css">
h1.RedText
{
font-family:Monotype Corsiva;
color:red;
font-size: 14pt;
}
Using the dot Operator particular class is defined
h1.BlueText
{
font-family:Arial;
color:blue;
font-size: 10pt;
}
</style>
Q.22 List the ways of positioning an element within a browser window. AU : Dec.-12

Ans. : There are three ways of positioning the element within the browser window. These are -
1. Absolute positioning 2. Relative positioning 3. Float positioning
Q.23 Give example for inline style sheet. AU : May-13
Ans. : Using the style tag we can embed the css style within the web document. Such type of
style sheet is called inline style sheet. For example -
<html>
<head>
<style type="text/css">
h1
{
color:green
}
</style>
</head>
<body>
<h1> This page contains an inline style sheet</h1>
</body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 69 CSS

</html>
Q.24 Define cascading.
Ans. : Cascading is the collection of rules that the browsers use to determine how to use the
style information.
Q.25 What are different variations of CSS ?
Ans. : 1) CSS 1 2) CSS 2 3) CSS 2.1 4) CSS 3 5) CSS 4
Q.26 What are the features of CSS3 ?
Ans. : Various features of CSS3 are -
1. It allows simple arithmetic calculations using calc() function.
2. There are many powerful selectors available using which the style sheet can be fancy.
3. There is introduction of new pseudo classes such as only-child, empty, root, first-child, after,
before.
4. It supports 2D/3D transformations.
5. It has a support for multiple backgrounds. The background-size property is also introduced
in CSS3. That means designer can specify the size of background image using either length
or percentage.
Q.27 Write appropriate inline CSS to show a section of the HTML document with a font size
20. AU : May-16
Ans. : The inline CSS can be written with the tag style.
<!DOCTYPE html>
<html>
<head>
<title>Display Section with Specific Font Size</title>
</head>
<body>
<div style="font-size:20px;">
India is my country.All Indians are my brothers and sisters.I love my country, and I am proud
of its rich and varied heritage.I shall always strive to be worthy of it.I shall respect my parents,
teachers and all elders and treat everyone with courtesy.To my country and my people, I pledge
my devotion.In their well being and prosperity alone lies my happiness.
</div>
</body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 70 CSS

Q.28 List out the limitations of CSS AU : May-18

Ans. :
1) CSS work differently on different browser.
2) One can not read files using CSS.
3) It is unable to interact with CSS.
4) The CSS can not invoke a web page.


TM
Technical Publications - An up thrust for knowledge
Unit II

1 4 Client Side Scripting

Syllabus
The JavaScript Language-History and Versions Introduction JavaScript in Perspective - Syntax -
Variables and Data Types - Statements - Operators - Literals-Functions-Objects-Arrays-Built-in
Objects-JavaScript Debuggers.

Contents
4.1 Introduction to JavaScript Language ............................... May-14, ..................................... Marks 8
4.2 Writing First JavaScript
4.3 Identifier, Keywords and Comments
4.4 Data Types
4.5 Variable
4.6 Operators
4.7 Literals
4.8 Input and Output
4.9 Control Structures ............................................................ Dec.-08, May- 10, 11, ............... Marks 8
4.10 Functions.......................................................................... Dec.-07, 08, May-11,12,13, ..... Marks 16
4.11 Arrays............................................................................... May- 08,12, Dec.-13, ................. Marks 8
4.12 Standard Objects ............................................................. Dec.-09, 11, 13, ........................ Marks 16
4.13 Form Processing in JavaScript .......................................... Dec.-09, May-08, 14, ................. Marks 8
4.14 JavaScript Debuggers....................................................... May-12, ..................................... Marks 8
4.15 Examples .......................................................................... May-08, 09, Dec.-08, 09, ......... Marks 16
Two Marks Questions with Answers

(4 - 1)
Web Technology 4-2 Client Side Scripting

4.1 Introduction to JavaScript Language AU : May-14, Marks 8

4.1.1 History and Versions


The JavaScript is a programming language which is implemented by Netscape Communications
in 1995.
Various client side versions of JavaScript are enlisted in the following table
Browser Year JavaScript Version

Netscape Navigator 2.0 1995 JavaScript 1.0

Microsoft Internet Explorer 3.0 1996 JavaScript 1.0 (JScript 1.0)

Netscape Navigator 3.0 1996 JavaScript 1.1

Netscape Navigator 4.0 1997 JavaScript 1.2

Microsoft Internet Explorer 4.0 1997 JavaScript 1.2 (JScript 3.0)

Netscape Navigator 4.5 1998 JavaScript 1.3

Microsoft Internet Explorer 5.0 1999 JavaScript 1.3 (JScript 5.0)

4.1.2 Features of JavaScript


Following are some features of JavaScript
1. Browser Support : For running the JavaScript in the browser there is no need to use some
plug-in. Almost all the popular browsers support JavaScripting.
2. Structure Programming Syntax: The Javascript supports much commonly the structured
language type syntax. Similar to C-style the programming blocks can be written.
3. It automatically inserts the semicolon at the end of the statement, hence there is no need to
write semicolon at the end of the statement in JavaScript.
4. Dynamic Typing : It supports dynamic typing, that means the data type is bound to the
value and not to the variable. For example one can assign integer value to a variable say ‘a’
and later on can assign some strg the ing value to the same variable in JavaScript.
5. Run Time Evaluation : Using the eval function the expression can be evaluated at run time.
6. Support for Object : JavaScript is object oriented scripting language. However handling of
objects in JavaScript is somewhat different that the conventional object oriented
programming languages. JavaScript has a small number of in-built objects.
7. Regular Expression : JavaScript supports use of regular expressions using which the text-
pattern matching can be done. This feature can be used to validate the data on the web page
before submitting it to the server.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-3 Client Side Scripting

8. Function Programming : In JavaScript functions are used. One function can accept
another function as a parameter. Even, one function can be assigned to a variable just like
some data type. The function can be run without giving the name.

4.1.3 Difference between JavaScript and Java

Sr. No. Java JavaScript

1. Java is a programming language. JavaScript is a scripting language.

2. Java is an object oriented Javascript is not a object oriented


programming language. programming language. Its object
model is far different than a typical
object oriented programming language
such as C++ or Java.

3. Java is strongly typed language and In JavaScript variables need not be


the type checking is done at declared before their use. Checking the
compile time. compatibility of type can be done
dynamically.

4. Objects in Java are static. That In JavaScript the objects are dynamic.
means the number of data members That means we can change the total
and method are fixed at compile data members and method of an object
time. during execution.

University Question

1. Elaborate the language history of JavaScript and its versions. AU : May-14, Marks 8

4.2 Writing First JavaScript


The JavaScript can be directly embedded within the HTML document or it can be stored as
external file.

Directly embedded JavaScript


The syntax of directly embedding the JavaScript in the HTML is
<script type=“text/javascript”>



</script>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-4 Client Side Scripting

Ex. 4.2.1 : Write a JavaScript to display Welcome message in JavaScript


Sol. :
<!DOCTYPE html >
<html >
<head>
<title> My First Javascript </title>
</head>
<body>
<center>
<script type="text/javascript">
/*This is the First JavaScript*/
document.write(" Welcome to First Page of Javascript");
</script>
</center>
</body>
</html>
Output

Script Explanation :
In above script
(1) we have embedded the javaScript within
<script type="text/javascript">

</script>
(2) a comment statement using /* and */. Note that this type of comment will be recognized only
within the <script> tag. Because, JavaScript supports this kind of comment statement and
not the XHTML document.
(3) Then we have written document.write statement, using which we can display the desired
message on the web browser.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-5 Client Side Scripting

Indirectly Embedding JavaScript


If we want to embed the JavaScript indirectly, that means if the script is written in some another
file and we want to embed that script in the HTML document then we must write the script tag as
follows -
<script type=“text/javascript” src=“MyPage.js”>

Javascript is which is to be embedded is in
the file MyPage.js



</script>
We will follow the following steps to use the external JavaScript file.
Step 1 : Create an XHTML document as follows -

XHTML Document[FirstPg.html]
<!DOCTYPE html >
<html>
<head>
<title> My First Javascript </title>
</head>
<body>
<center>
<script type="text/javascript" src="my_script.js">
</script>
</center> This is an external
</body> javascript file,it can
be specified with the
</html>
attribute src
Step 2 :

JavaScript[my_script.js]
/*This is the First JavaScript*/
document.write(" Welcome to First Page of Javascript");

Step 3 : Open the HTML document in Internet Explorer and same above mentioned output
can be obtained.

Advantages of indirectly embedding of JavaScript


1. Script can be hidden from the browser user.
2. The layout and presentation of web document can be separated out from the user interaction
through the JavaScript.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-6 Client Side Scripting

Disadvantages of indirectly embedding of JavaScript


1. If small amount of JavaScript code has to be embedded in XHTML document then making a
separate JavaScript file is meaningless.
2. If the JavaScript code has to be embedded at several places in XHTML document then it is
complicated to make separate JavaScript file and each time invoking the code for it from the
XHTML document.

4.3 Identifier, Keywords and Comments

1. Identifiers
Identifiers are the names given to the variables. These variables hold the data value. Following
are some conventions used in JavaScript for handling the identifiers -
1. Identifiers must begin with either letter or underscore or dollar sign. It is then followed by
any number of letters, underscores, dollars or digits.
2. There is no limit on the length of identifiers.
3. The letters in the identifiers are case-sensitive. That means the identifier INDEX, Index,
index, inDex are considered to be distinct.
4. Programmer defined variable names must not have upper case letters.

2. Reserved words
Reserved words are the special words associated with some meaning. Various reserve words
that are used in JavaScript are enlisted as below –
break Continue delete for in return throw var with

case default else function instanceof switch try void

catch do finally if new this typeof while

3. Comments
JavaScript supports following comments
1. The // i.e a single line comment can be used in JavaScript.
2. The /* and */ can be used as a multi-line comment.
3. The XHTML <!--> and <--> is also allowed in JavaScript

4. Semicolon
While writing the JavaScript the web programmer must give semicolon at the end of the
statements.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-7 Client Side Scripting

4.4 Data Types


JavaScript defines two entities primitives and objects. The primitives are for storing the values
whereas the object is for storing the reference to the actual value.
There are following primitive types used in JavaScript
1. Number 2. String 3. Boolean
4. Undefined 5. Null
There are three type of predefined objects in JavaScript
1. Number 2. String 3. Boolean
These objects are called wrapper objects. These wrapper objects provide properties and
methods which can be used by primitive types.

Fig. 4.4.1 (a) Representation of primitive type

Fig. 4.4.1 (b) Representation of object

4.5 Variable
In JavaScript we can declare the variable using the reserved word var. The value of this variable
can be any thing; it can be numeric or it can be string or it can be a Boolean value.

JavaScript[VarDemo.html]
<!DOCTYPE html >
<html >
<head>
<title> Variables in Javascript </title>
</head>
<body>
<script type="text/javascript">
var a,b,c;
var string;
Variable declaration is done using var.
a=2;
Note that there is no data type required
b=3; for handling variables.
c=a+b;

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-8 Client Side Scripting

string ="The result = ";


document.write("Performing addition of 2 and 3. "+"<br/>");
document.write(string);
document.write(c);
</script>
</body>
</html>
Output

Note that using var we can define the variable which is of type numbers( 2 , 3 or 5) as well as
the string “The result”.

4.6 Operators
Various operators used by JavaScript are as shown in following table -
Type Operator Meaning Example

Arithmetic + Addition or unary plus c = a+b

– Subtraction or unary minus d = –a

TM
Technical Publications - An up thrust for knowledge
Web Technology 4-9 Client Side Scripting

* Multiplication c=a*b

/ Division c=a/b

% Mod c=a%b

Relational < Less than a<4

> Greater than b>10

<= Less than equal to b<=10

>= Greater than equal to a>=5

== Equal to x==100

!= Not equal to m!=8

Logical && And operator 0&&1

|| Or operator 0 ||1

Assignment = Is assigned to a=5

Increment ++ Increment by one ++i or i++

Decrement -- Decrement by one – – k or k– –

The conditional operator is ? The syntax of conditional operator is


Condition?expression1:expression 2
Where expression1 denotes the true condition and expression2 denotes false condition.

For example :
a>b?true:false
This means that if a is greater than b then the expression will return the value true otherwise it
will return false.

4.6.1 String Concatenation Operator


Two string can be concatenated using the + operator. A variable can be concatenated with the
string using + operator also.

JavaScript[StrOper.html]
<!DOCTYPE html >
<html >
<head>
<title>String Concatenation Demo</title>
</head>
<body>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 10 Client Side Scripting

<center>
<script type="text/javascript">
var first_string;
first_string="Programming";
document.write("<h3>"+first_string+" the web"+"</h3>");
</script>
</center>
</body>
</html>
Output

4.7 Literals
There are two types of literals used in JavaScript and those are numeric literals and string
literals. The numeric literals are called numbers. These numbers can include integer values,
floating point or double precision values. For example -
10
10.3
10.0
10.
10E3
10.2E4
10.e2
10e-3
are all valid numeric literals.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 11 Client Side Scripting

The string literals are the sequence of characters. It can be written in double quotes “ ” or in
single quotes ‘ ‘. For example
‘Rain Rain come soon ‘

4.8 Input and Output

4.8.1 The document.write


 For displaying the message on the web browser the basic method being used is
document.write. To print the desired message on the web browser we write the message in
double quotes inside the document.write method.
 For example
document.write(“Great India”);
 We can pass the variable instead of a string as a parameter to the document.write.

For example
var my_msg=”Great India”;
document.write(my_msg);
Note that the variable my_msg should not be passed in double quotes to document.write
otherwise the result the string “my_msg” will be printed on the browser instead of the string
“Great India” .
 We can combine some HTML tags with the variable names in document.write so that the
formatted display can be possible on the web browser.
For example – if we want to print the message “Great India” on the web browser in bold font
then we can write following statements-
var my_msg=“Great_India”;
document.write(“<strong>”+my_msg+“</strong>”);

4.8.2 Popup Box


 One of the important features of JavaScript is its interactivity with the user.

 There are three types of popup boxes used in JavaScript by which user can interact with the
browser.

alert box : In this type of


popup box some message will
be displayed.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 12 Client Side Scripting

confirm box: In this type of


popup box in which the
message about confirmation
will be displayed. Hence it
should have two buttons Ok
and Cancel.

Prompt box is a type of popup


box which displays a text
window in which the user can
enter something. Hence it has
two buttons Ok and Cancel.

JavaScript[PopupBox.html]
<!DOCTYPE html>
<html >
<head>
<title>Introduction to pop up box</title>
</head>
<body>
<p>Experiment with the popup boxes by clicking the buttons(OK and Cancel) on them</p>

<script type="text/javascript">
if(confirm("do you agree?"))
alert("You have agreed");
else
input_text=prompt("Enter some string here..."," ");
/*the value entered in prompt box is returned
and stored in the variable text */
alert("Hi "+input_text);
</script>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 13 Client Side Scripting

Output

If we click on OK button then an alert box will appear.

On load, the confirm box appears and if we click on Cancel button then the prompt box will
appear. We can type some string within it.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 14 Client Side Scripting

Click OK button and we will get the alert box as follows -

Thus alert, confirm and prompt boxes cause the browser to wait for user response. The user
responds by clicking the button on these popup boxes.

Script Explanation
On loading this script using web browser first of all a confirm box will be displayed. If we click
on OK button an alert box will appear. Otherwise a prompt box will be displayed. Again if we
click on the OK button of prompt box again an alert box will appear which will display the string
which you have entered on prompt box. If you run the above script you will get all these effects.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 15 Client Side Scripting

4.9 Control Structures AU : Dec.-08, May- 10, 11, Marks 8

Various control structures used in JavaScript are


Statement syntax Example
if-else if(condition) if(a>b)
statement document.write(“ a is greater than b”);
else else
statement document.write(“b is greater than a”);
while while(condition) while(i<5)
{ {
statements i=i+1;
} document.write(“value of i”+i)
}
do..while do do
{ {
}while(condition); i=i+1;
document.write(“value of i”+i)
}while(i<5);
for for(initialization;test for(i=0;i<5;i++)
condition;stepcount) {
{ document.write(i);
statements }
}
switch…case switch(expression) switch(choice)
{ {
case 1: statements case 1: c=a+b;
break; break;
case 2: statements case 2:c=a-b;
break; break;
… }
default:
statements
}
break : break; for(i=10;i>=0;i--)
Similar to C or C++, the {
break statement is used to if(i==5)
break the loop. break;
}

continue: continue; for(i=10;i>=0;i--)


The continue statement is {
used in a loop in order to if(i==5)
continue(skip). The keyword {
continue is used to make x=i;
use of continue statement in continue;
a loop.
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 16 Client Side Scripting

Control structure is essential part of JavaScript. The Control Structures in JavaScript are just
similar to that of C or C++. Various control structures are -
1. if statement 2. While 3. Do-while 4. for
5. switch case 6. break 7. Continue
Let us discuss various examples that make use of control structures.

Ex. 4.9.1 : Develop a javascript to generate ‘ARMSTRONG NUMBERS’ between the range
1 to 100. [Eg : 153 is an Armstrong number, since sum of the cube of the digits is equal to the
number i.e. [13+53+33=153]
Sol. :
<html>
<body>
<table border="1" allign="center">
<th>Armstrong Numbers</th>
<script type="text/javascript">
var num,i,temp,sum;
var n=0;
i=1;
do
{
num=i;
sum=0;
while(num>0)
{
n=num%10;
n=parseInt(n);
num=num/10;
num=parseInt(num);
sum=sum+(n*n*n);
}
if(sum==i)
{
document.write("<tr><td>"+i+"</td></tr>");
}
i++;
}while(i<=1000);
</script>
</table>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 17 Client Side Scripting

Ex. 4.9.2 : Write a javascript that displays the as per following:


(Calculate the squares and cubes of the numbers from 0 to 10)
Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

Sol. :
<html>
<head>
<title>Sqaure and Cube value table</title>
</head>
<body>
<table border=1 align="center">
<th>Number</th><th>Square</th><th>Cube</th>
<script type="text/javascript">
for (i=1; i<=10; i++)
{
document.write("<tr><td>"+i+"</td><td>"+(i*i)+"</td><td>"+(i*i*i)+"</td></tr>");
}
</script>
</table>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 18 Client Side Scripting

Ex. 4.9.3 : Write a script that reads an integer and displays whether it is a prime number or not.
Sol. :
<html>
<head>
<title>PRIME NUMBER DEMO</title>
</head>
<body>
<script type="text/javascript">
var num=prompt("Type number here.","");
var b;
var flag=1;
for(i=2;i<num;i++)
{
b=num%i;
if(b==0)
{
flag=0;

break;
}
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 19 Client Side Scripting

if(flag==0)
alert(num+" is not a prime number");
else
alert(num+" is a prime number");
</script>
</body>
</html>
Output

Ex. 4.9.4 : Write a JAVAScript to print characters of a string at odd positions.


(for example for the string India, I, d and a should get printed).
Sol. :
<html>
<body>
<script>
var str="India";
var k=str.length;

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 20 Client Side Scripting

for(i=0;i<=k;i=i+2)
{
n=str.charAt(i);
document.write(n);
document.write(“ ”);
}
</script>
</body>
</html>
Output

Ex. 4.9.5 : Develop a JavaScript page to demonstrate an If condition by which the time on your
browser is less than 10; you will get a “Good morning” greeting.
AU : Dec.-08, Marks 2
Sol. : Goodmorning.html
<html>
<head>
<script type="text/javascript">
function GreetMsg()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
if(h<10)
alert("Good Morning!!!(Time "+h+":"+m+":"+s+")");
else
alert("Have a Good Day!!!(Time "+h+":"+m+":"+s+")");
}
</script>
</head>
<body onload="GreetMsg()">
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 21 Client Side Scripting

Output

Ex. 4.9.6 : Write a JavaScript to find and print the largest and smallest values among 10 elements
of an array.
AU : May- 10, Marks 8
Sol. : largestsmallest.html
<html>
<head>
<script type="text/javascript">
function fun()
{
a=new Array(10);
a[0]=20;
a[1]=10;
a[2]=-1;
a[3]=50;
a[4]=70;
a[5]=120;
a[6]=40;
a[7]=60;
a[8]=90;
a[9]=100;
document.write("<br/>The elements of array are...<br/>");
max_val=a[0];
for(i=0;i<10;i++)
document.write(" "+a[i]);
min_val=a[0];
max_val=a[0];
for(i=0;i<10;i++)

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 22 Client Side Scripting

if(a[i]<min_val)
min_val=a[i];
if(a[i]>max_val)
max_val=a[i];
}
document.write("<br/>The minimum value is "+min_val);
document.write("<br/>The maximum value is "+max_val);
}
</script>
<title>Finding largest and smallest Element</title>
</head>
<body onload=fun()>
</body>
</html>
Output

Ex. 4.9.7 : Write a JavaScript to find the product of first 15 even numbers.
Sol. :
<html>
<body>
<script type="text/javascript">
prod=1;
for(i=1;i<15;i++)
{
if(i%2)
{
prod=prod*i;
}
}
document.write("Product of odd numbers between 1 to 15 is "+prod);
</script>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 23 Client Side Scripting

University Question

1. State and explain the types of statements in JavaScript. AU : May-11, Marks 8

4.10 Functions AU : Dec.-07, 08, May-11,12,13, Marks 8

 We can write the functions in the JavaScript for bringing the modularity in the script.

 Separate functions can be created for each separate task. This ultimately helps in finding the bug
from the program efficiently.
 We can define the function anywhere in the script either in head or body section or in both. But
it is a standard practice to define the function in the head section and call that function from the
body section.
 The keyword function is used while defining the function.
 The syntax for defining the function is
function name_of _function (arg1,arg2,…argn)
{

Statements
}
Here is a simple illustration in which we have written a function my_fun()
JavaScript[FunDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function my_fun()
{
document.write("This statement is within the function"); Definition of function
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
document.write("This statement is before a function call");
document.write("<br>");
my_fun();
call to the function
</script>
</center>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 24 Client Side Scripting

Output

Script Explanation
The above code is pretty simple. We have defined one function named my_fun in the head
section of the HTML document and called it from the body section. The corresponding write
statements are used to display the messages on the browser window.

4.10.1 Returning Value from the Function


 We can return some value from the function using a keyword return.

 This return value is either stored in variable or directly displayed on the browser window.

 Following is a simple illustration in which the value is returned from the function and is directly
displayed on the browser window using document.write.

JavaScript[FunRetDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function my_fun()
{
str="I am function returned value";
return str;
}
</script>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 25 Client Side Scripting

</head>
<body>
<center>
<script type="text/javascript">
document.write("This statement is before a function call");
document.write("<br>");
document.write("<h3>"+my_fun()+"<h3>");
</script>
</center>
</body>
</html>
Output

4.10.2 Passing the Parameters to the Function


 Similarly we can pass some arguments to the function.

 The syntax is
function function_name(aregument1, argument2…,argumentn)
{
//body of function
}
 In the following program, we have passed two arguments to the function and returning some
value from the function.

JavaScript[FunPassRet.html]
<!DOCTYPE html >
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 26 Client Side Scripting

function my_fun(str1,str2)//two atrguments str1 and str2 are passed


{
str="I am function returned value."+" "+str1+" "+str2 ;
return str; //returning one string value from function
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
document.write("This statement is before a function call");
document.write("<br>");
document.write("<h3>"+my_fun("Hello!!","How are to you?")+"<h3>");
</script>
</center>
</body>
</html>
Output

4.10.3 Passing an Array to the Function


 Similar to C or C++ we can pass an entire array as a parameter to the function.

 This method of array passing is called as call by reference.

 When an array is passed to the function the array name is simply passed.

 In the following JavaScript we have initialized an array in the body part and to display those
contents of an array we have called a display() function. And to this function an array is passed
as an argument. Let see the JavaScript.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 27 Client Side Scripting

JavaScript[FunPassArr.html]

<!DOCTYPE html>
<html>
<head>
<title>Passing an Array to the function</title>
Function definition with
<script type="text/javascript"> array as an argument
function display(a)
{
document.write("The contents of the array are..."+"<br>");
i=0;
for(i in a)
{
document.write(a[i]+"<br>");
i++;
}
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
var ar=new Array(10);
for(i=0;i<=9;i++)
{
ar[i]=i;
}
display(ar); Function call
</script>
</center>
</body>
</html>

In above given script we have called a display function by passing an array as a parameter to it.
Hence we will get following output.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 28 Client Side Scripting

Output

Ex. 4.10.1 : Write a JavaScript to sort the elements of an array in ascending order
Sol. :

<!DOCTYPE html>
<html>
<head>
<title>Sorting the Numbers</title>
<script type="text/javascript">
function display(a)
{
i=0;
for(i in a)
{
document.write(a[i]+"<br>");
i++;
}
}
function sort(a)
{
for(i=0;i<a.length-1;i++)
{
for(j=i+1;j<a.length;j++)

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 29 Client Side Scripting

{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
var ar=new Array(10,30,20,50,40);
document.write("Before sorting the elements..."+"<br>");
display(ar);
sort(ar);
document.write("After sorting the elements..."+"<br>");
display(ar);
</script>
</center>
</body>
</html>

Script Explanation
1. In the above program we have stored some values in the array in the body part.
2. Then in order to display the contents of an array we have called display function.
3. Then we have called one more function called sort in which the elements of an array are
sorted.
4. Note that in the sort function we have used length property which returns total number of
elements in an array.
5. The simple bubble sort method is used to sort the array in an ascending order.
6. Again the display function is called in order to display the sorted array.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 30 Client Side Scripting

Output

Ex. 4.10.2 : Write an HTML and JavaScript program which accepts N as input and displays first
N Fibonacci numbers as list.
Sol. :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function fun(str)
{
var num=Number(str);
var i,j,k,count;
document.write("<h3>"+" The Fibonacci series is as follows..."+"</h3>");
i=0;
j=1;
document.write(j);
for(count=0;count<=num;count++)
{
k=i+j;
i=j;

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 31 Client Side Scripting

j=k;
document.write(","+k);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var input_str=prompt("Enter some number","");
fun(input_str);
</script>
</body>
</html>

Ex. 4.10.3 : Write a javascript that uses a loop, that searches a word in sentence held in an array,
returning the index of the word.
Sol. :
<!DOCTYPE html>
<html >
<head>
<script type="text/javascript">
function Search(form1)
{
var Sentence= form1.input.value;
var pattern=prompt(“Enter the word to be searched for: ”,"");
alert(pattern);
temp=Sentence.split(“ ”);
for(i=0;i<temp.length;i++)
{
if(temp[i]==pattern)
{
alert(“The word is at position: ”+(i+1));
}
}
}
</script>
</head>
<body>
<form name="form1">
<b> Enter the sentence </b>
<input type="text" name="input"><br/>
<input type="button" value="Click Me" onclick="Search(form1)">
</form>
</body>
</html>
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 32 Client Side Scripting

Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 33 Client Side Scripting

Ex. 4.10.4 : Write a JavaScript to check input string is palindrome or not.

Sol. :

<html>
<head>
<title>PALINDROME CHECK</title>
<script type="text/javascript">
function palindrome(str)
{
var len = str.length;

for ( var i = 0; i < Math.floor(len/2); i++ )


{
if (str[i] !== str[len - 1 - i])
{
return false;
}
}
return true;
}
</script>
</head>
<body>
<script type="text/javascript">
str=prompt("Enter some string","");
if(palindrome(str))
document.write(str+" is Palindrome");
else
document.write(str+"Not Palindrome");
</script>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 34 Client Side Scripting

Output

Ex. 4.10.5 : Develop and demonstrate a HTML file that includes JavaScript that uses a function
for the following problems :
(a) Parameter : A string Output : The position of the string of the left-most vowel
(b) Parameter : A number Output : The number with digits in the reverse order.
Sol. : (a) [RegExpDemo4.html]
<!DOCTYPE html>
<html >
<head>
<title>Pattern Matching using Regular Expression </title>
<script type="text/javascript">
function TestString(str)
{
document.write("The given string is ");
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 35 Client Side Scripting

document.write("<em>"+str+"</em>"+"<br/>");
var i=str.match(/[aeiouAEIOU][a-zA-Z]*/);
return i;
}
</script>
</head>
<body>
<h3>
<script type="text/javascript">
var input_str=prompt("Enter some string here","");
p=TestString(input_str);
document.write("The leftmost vowel is found at index "+p.index);
</script>
</h3>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 36 Client Side Scripting

b) [RevNum.html]

<!DOCTYPE html>
<html >
<head>
<script type="text/javascript">
function fun(str)
{
var num=Number(str);
var n=0;
document.write("<b>"+"The reversed number is "+"</b>");
while(num>0)
{
n=num%10;
n=parseInt(n);
num=num/10;
num=parseInt(num);
document.write(n);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var input_str=prompt("Enter some number","");
fun(input_str);
</script>
</body>
</html>
Output

Click OK button and you will get the reversed number as follows -

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 37 Client Side Scripting

Ex. 4.10.6 : Write a JavaScript function to find the product of two arguments and return the
result.
AU : Dec.-08, Marks 5
Sol. :
<!DOCTYPE html>
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function my_fun(num1,num2)
{
return num1*num2;
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
document.write("The product of 10 and 20 is ");
document.write("<br>");
document.write("<h3>"+my_fun(10,20)+"</h3>");
</script>
</center>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 38 Client Side Scripting

Ex. 4.10.7 : Write a JavaScript function named drawstripes that will draw a number of colored
strips by generating an HTML table in which each row has ( possibly) different color. Your
function must have 3 parameters :
 Width, the width of each strip

 Height, the height of each strip

 Colors an array in which each element is the name of color. Each color name is a valid HTML
color (can be used as the value of BGCOLOR attribute or CSS color property)
AU : Dec.-07, CSE, Marks 16
Sol. : [stripeDemo.html]
<html>
<head>
<title></title>
<script>
var colors = new Array('#ff0000','#00ff00','#0000ff','#ff00ff');
function drawstrips(id)
{
if(document.getElementById)
{
var table = document.getElementById(id);//get the table
var rows = table.getElementsByTagName("tr"); //get the row of table
var wd,ht;
for(i = 0; i < rows.length; i++)
{
wd=prompt("Enter the width of the strip"+i,"");
ht=prompt("Enter the height of the strip"+i,"");
w=Number(wd);
h=Number(ht);
display(rows[i],i,w,h);

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 39 Client Side Scripting

}
}
}
function display(row,i,w,h)
{
row.style.backgroundColor = colors[i%colors.length]; //using CSS style
row.style.width = w;
row.style.height = h;
}
</script></head>
<body onLoad="drawstrips('MyTable')"> Varying color, width
<table id="MyTable" cellspacing="10" cellpadding="10"> and height of each
<tr><td>Strip 1</td></tr>
<tr><td>Strip 2</td></tr>
<tr><td>Strip 3</td></tr>
</table>
</body>
Note : For the sake of understanding following output is given for the above application]

Ex. 4.10.8 : Write a JavaScript to find the sum of first n even numbers and display the result. Get
the value of n from the user.
AU : May-13, Marks 8
Sol. :
<html>
<head>
<script type="text/javascript">
function EvenNumSum(str)
{

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 40 Client Side Scripting

var n=Number(str);
sum=0;
for(i=1;i<n;i++)
{
if(i%2==0)
sum=sum+i;
}
document.write("<br>"+" Sum of first "+n+" even numbers is "+sum+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var n=prompt("Enter the value of n","");
EvenNumSum(n);
</script>
</body>
</html>

4.10.4 Global Functions of JavaScript


Global functions are the top-level functions in JavaScript that are independent of any specific
object. These functions use the built in objects of the JavaScript. Following are some global
functions -

1. encodeURI(URI)
This function is used to encode the URI.This function encodes special characters,
except: , / ? : @ & = + $ #.

For example

globalfun1.html
<html>
<body>
<script type="text/javascript">
var uri="my example.jsp?name=< >ggg"
document.write(encodeURI(uri)+ "<br />");
</script>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 41 Client Side Scripting

Output

2. decodeURI
This function decodes the encoded URI.

For example

globalfun2.html
<html>
<body>
<script type="text/javascript">
var uri="my example.jsp?name=< >ggg"
document.write(encodeURI(uri)+ "<br />");
document.write(decodeURI(uri)+ "<br />");
</script>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 42 Client Side Scripting

3. parseInt
This function parses a string and returns the integer value.
The syntax is -
parseInt(string,radix)

String is parsed to It represents the numerical system


obtain integer such as octal, decimal or
value hexadecimal. It is optional
parameter.

Example

globalfun3.html
<html>
<body>
<script type="text/javascript">
document.write(parseInt("100"));
</script>
</body>
</html>
The output of above code will be 100.
Similar to the parseInt function the parseFloat function is used to obtain the real value from
the string.

4. eval
The eval function is used to evaluate the expression.
The syntax is
eval(string);

Example

globlafun4.html
<html>
<body>
<script type="text/javascript">
document.write(eval("2+3*5"));
</script>
</body>
</html>
The output of above code will be 17.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 43 Client Side Scripting

University Questions

1. Explain how functions can be written in JavaScript with an example. AU : May-11, Marks 8
2. Explain how local and global functions can be written using JavaScript. AU : May-12, Marks 8

4.11 Arrays AU : May- 08,12, Dec.-13, Marks 8

 Arrays is a collection of similar type of elements which can be referred by a common name.

 Any element in an array is referred by an array name followed by “[“ followed by position of
the element followed by ].
 The particular position of element in an array is called array index or subscript.

For example –

Array index

0 1 2 3 4

10 20 30 40 50

Array value
Fig. 4.11.1 Arrays

 Normally the first element in an array is stored at 0th location, however we can start storing the
element from any position.

4.11.1 Array Declaration

 In JavaScript the array can be created using Array object.

 Suppose, we want to create an array of 10 elements then we can write,

var ar = new Array(10);

 Using new operator we can allocate the memory dynamically for the arrays.

 In the brackets the size of an array is mentioned and the var ar denotes the name of the array.
Thus by the above sentence an array ar will be created in which we can store 10 elements at the
most. Sometimes the above statement can be written like this
var ar;

ar=new Array(10);

4.11.2 Array Initialization


Let us see how to store some elements in an array.
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 44 Client Side Scripting

 JavaScript Program [ArrayDemo.html]


<!DOCTYPE html>
<html>
<head>
<title>Array Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
a=new Array(5);//creation of array
for(i=0;i<5;i++)
{
a[i]=i;
document.write(a[i]+"<br>");//displaying array
}
document.write("Another way of initialization"+"<br>");
b=new Array(11,22,33,44,55);//creation of array
for(i=0;i<5;i++)
{
document.write(b[i]+"<br>");//displaying array
}
document.write("Yet another way of initialization"+"<br>");
var c=[100,200,300,400,500];//creation of array
for(i=0;i<5;i++)
{
document.write(c[i]+"<br>");//displaying array
}
</script>
</strong>
</body>
</html>

As you can notice that, in above JavaScript an array can be initialized in three different ways
which is shown by boldface. Hence an output of above script will be

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 45 Client Side Scripting

Output

There is one control structure in JavaScript which is closely associated with array elements and
such a control structure is for…in. Let us see a simple JavaScript which makes use of for-in
control structure to display elements of an array.
JavaScript [for_inDemo.html]
<!DOCTYPE>
<html>
<head>
<title>for-in Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
Days=new Array();
Days[0]="Sunday";
Days[1]="Monday";
Days[2]="Tuesday";

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 46 Client Side Scripting

Days[3]="Wednesday";
Days[4]="Thursday";
Days[5]="Friday";
Days[6]="Saturday";
for(i in Days)
{
document.write(Days[i]+"<br>");
}
</script>
</strong>
</body>
</html>
Output

Ex. 4.11.1 : Write a javascript that reads ten numbers and displays the count of negative
numbers, the count of positive numbers and the count of zero from the list.
Sol. :
<html>
<body>
<script type="text/javascript">
ar=new Array();
ar[0]=10;
ar[1]=0;
ar[2]=-9;
ar[3]=0;
Reading ten numbers
ar[4]=20;
ar[5]=30;
ar[6]=3;
ar[7]=88;
i=0;
for(i in ar)
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 47 Client Side Scripting

{
document.write(ar[i]+"<br/>");
Displaying the ten numbers
i++;
}
positive_count=0;
negative_count=0;
zero_count=0;
i=0;
for(i in ar)
{
if(ar[i]==0)
Computing the count for zero,
zero_count++; positive and negative numbers
else if(ar[i]>0)
positive_count++;
else
negative_count++;
i++;
}
document.write("<br>"+" Total Number of positive elements are
document.write(" Total Number of negative elements are
document.write(" Total Number of zero elements are "+zero_count+"<br/>");
</script>
</body>
</html>

4.11.3 Two Dimensional Array


Actually JavaScript does not support the multidimensional arrays. Hence for defining the 2D
array we make use of single dimensional array, how? Here it is -

JavaScript[TwoDArray.html]
<!DOCTYPE html>
<html>
<head>
<title>Two Dimensional Array</title>
</head>
<body>
<center>
<h3> Demonstration of 2D array</h3>
<script type="text/javascript">
a=new Array();//creation of rows of array
for(i=0;i<5;i++)
a[i]=new Array();//creating columns of array
for(i=0;i<5;i++)
{

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 48 Client Side Scripting

for(j=0;j<5;j++)
{
a[i][j]=i+j;
document.write(a[i][j] +" ");
}
document.write("<br>");
}
</script>
</center>
</body>
</html>
Output

There is another way by which the two dimensional array can be initialized. This method is
represented in the following Script

JavaScript[TwoDArray1.html]
<!DOCTYPE html>
<html>
<head>
<title>Two Dimensional Array</title>
</head>
<body>
<center>
<h3> Demonstration of 2D array</h3>
<script type="text/javascript">
var a=[ [1,2,3],
[4,5,6],
[7,8,9]
]; //creation of array
for(i=0;i<3;i++)

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 49 Client Side Scripting

{
for(j=0;j<3;j++)
{
document.write(a[i][j] +" ");
}
document.write("<br>");
}
</script>
</center>
</body>
</html>
Output

Ex. 4.11.2 : Use a one-dimensional array and write a script to solve following problem . Read in
20 numbers, each of which is between 1 and 100. As each number is read, print it only if it is not a
duplicate of a number that has already been read.
AU : May- 08, Marks 8
Sol. : duplicate.html
<html>
<head>
<script type="text/javascript">
function change()
{
a=new Array(20);
for(i=0;i<=19;i++)
{
var input_str=prompt("Enter the any number between 1 to 100","");
var val=Number(input_str);
a[i]=val;
}
for(i=0;i<=18;i++)
{
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 50 Client Side Scripting

for(j=i+1;j<=19;j++)
{
if(a[i]>a[j])//before checking duplicate elements
{
temp=a[i]; //arrange them in sorted order
a[i]=a[j];
a[j]=temp;
}
}
}
document.write("The elements (without considering duplicate elements)are...");
for(i=0;i<=18;i++)
{
flag=0;
for(j=i+1;j<=19;j++)
{
if(a[i]==a[j])//checking if two adjacent elements are duplicate
{
a[j]=-1;//-1 is assigned to duplicate elements
flag=1;//flag indicates a[i] and a[j] are duplicate
}
}
if(flag==1)//flag=1 represents that a[i] element
a[i]=-1;//needs to be marked as duplicate
}
for(i=0;i<=19;i++)
{
if(a[i]>0) //-1 means duplicate elements
document.write(a[i]+",");//elements that are not -1 are unique elements
}
}
</script>
<title>Eliminating Duplicate Elements</title>
</head>
<body onload=change()>
</body>
</html>

University Questions

1. Explain the way in which javaScript handles arrays with example. AU : May-12, Marks 8
2. Explain the JavaScript array handling and array methods. AU : Dec.-13, Marks 8

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 51 Client Side Scripting

4.12 Standard Objects AU : Dec.-09, 11, 13, Marks 16

 In JavaScript object is a collection of properties. These properties are nothing but the members
of the classes from Java or C++. For instance - in JavaScript the object Date() is used which
happens to the member of the class in Java.
 The property can be of two types either a data type or a function type. The data properties are
sometimes called as properties and method properties are called as methods or functions.
 The data properties are further classified into two types - primitive values and reference to other
objects.
 Primitives are simplest data types for example Number, String, Boolean are some primitives
used to define type the simple data.
 The objects in the JavaScript are accessed using the variables. These variables act like a
references to the object. The property of the object can be accessed with the help of object name
using the dot operator. For example : If there is an object named Person then its property salary
can be accessed as Person.salary
 Object is a root object in JavaScript. All other objects are formed from this Object using
prototype inheritance. All the other objects inherit the methods of this Object. In JavaScript
the object appears internally and externally. It is there in the form of property-value pair. The
properties are the names and values are data values or functions.

4.12.1 Math Objects


 For performing the mathematical computations there are some useful methods available from
math object.
 For example if we want to find out minimum of two numbers then we can write -
document.write(math.min(4.5,7.8));
The above statement will result in 4.5. Thus using various useful methods we can perform
many mathematical computations.
 Here are some commonly used methods from math object.
Method Meaning

sqrt(num) This method finds the square root of num.

abs(num) This method returns absolute value of num.

ceil(num) This method returns the ceil value of num. For example ceil(10.3) will return 11.

floor(num) This method returns the floor value of num. For example floor(10.3) will return 10.

log(num) This method returns the natural logarithmic value of num. For example log(7.9) will
return 2.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 52 Client Side Scripting

pow(a,b) This method will compute the ab. For example pow(2,5) will return 32.

min(a,b) Returns the minimum value of a and b.

max(a,b) Returns the maximum value of a and b.

sin(num) Returns the sine of num.

cos(num) Returns the cosine of num.

tan(num) Returns the tangent of num.

exp(num) Returns the exponential value i.e. enum .

JavaScript Program[MathDemo.html]
<!DOCTYPE html>
<html >
<head>
<title>Math Demo</title>
</head>
<body>
<center>
<h3>Square root of 100 is </h3>
<script type="text/javascript">
var num=100;
document.write("<h3>"+Math.sqrt(num)+"</h3>");
</script>
</center>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 53 Client Side Scripting

4.12.2 Number Objects


Various properties of number object are -
Property Meaning
MAX_VALUE Largest possible number gets displayed.
MIN_VALUE Smallest possible number gets displayed.
NaN When not a number then NaN is displayed.
PI The value of PI gets displayed.
POSITIVE_INFINITY The positive infinity gets displayed.
NEGATIVE_INFINITY The negative infinity gets displayed.
Using Number.property_name we can display the property value. Following JavaScript uses
the property of negative infinity.
JavaScript[NumberDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Number Object Demo</title>
</head>
<body>
<center>
<script type="text/javascript">
document.write(Number.NEGATIVE_INFINITY);
</script>
</center>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 54 Client Side Scripting

4.12.3 Date Objects


 This object is used for obtaining the date and time.

 This date and time value is based on computer’s local time (system’s time) or it can be based on
GMT(Greenwich Mean Time).
 Nowadays this GMT is also known as UTC i.e. Universal Co-ordinated Time. This is basically
a world time standard.
 Following are the commonly used methods of Date object.
Method Meaning

getTime() It returns the number of milliseconds. This value is the difference


between the current time and the time value from 1st January 1970.

getDate() Returns the current date based on computers local time.

getUTCDate() Returns the current date obtained from UTC.

getDay() Returns the current day. The day number is from 0 to 6 i.e. from
Sunday to Saturday.

getUTCDay() Returns the current day based on UTC. The day number is from 0
to 6 i.e. from Sunday to Saturday.

getHours() Returns the hour value ranging from 0 to 23, based on local time.

getUTCHours() Returns the hour value ranging from 0 to 23, based on UTC timing
zone.

getMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on


local time.

getUTCMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on


UTC timing zone.

getMinutes() Returns the minute value ranging from 0 to 59, based on local time.

getUTCMinutes() Returns the minute value ranging from 0 to 59, based on UTC
timing zone.

getSeconds() Returns the second value ranging from 0 to 59, based on local time.

getUTCSeconds() Returns the second value ranging from 0 to 59, based on UTC
timing zone.

setDate( value ) This function helps to set the desired date using local timing or
UTC timing zone.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 55 Client Side Scripting

setHour(hr,minute,second,ms) This function helps to set the desired time using local or UTC
timing zone. The parameters that can be passed to this function are
hour,minute,seconds and milliseconds. Only hour parameter is
compulsory and rest all are the optional parameters.

In the following web document we are making use of Date() object and some useful methods of
it.

JavaScript[DateDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Date Demo</title>
</head>
<body>
<script type="text/javascript">
var my_date=new Date();
document.write("The date is: "+my_date.toString()+"<br>");
document.write("Today's date is "+my_date.getDate()+"<br>");
document.write("This is the month of "+my_date.getMonth()+"<br>");
document.write("The current year is "+my_date.getFullYear()+"<br>");
document.write("Now, Hour = "+my_date.getHours()+"<br>");
document.write("Minutes = "+my_date.getMinutes()+"<br>");
document.write("Seconds = "+my_date.getSeconds()+"<br>");
</script>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 56 Client Side Scripting

Script Explanation:
1. In the above script we have created an instance my_date of the object Date().
2. Then using my_date.toString() method we can display the current date along with the time.
3. Then using the functions like getDate(), getMonth(), getFullYear() we are displaying the
date, month and year separately.
4. Similarly using the functions getHours(), getMinutes() and getSeconds() we can display the
current hour, minute and seconds separately.

4.12.4 Boolean Objects


 This object is the simplest kind of object which is used especially when we want to represent
true and false values.
 Here is a simple javascript in which the Boolean type variable is used -

Javascript Program
<html>
<body>
<script type="text/javascript">
var temp=new Boolean(false);
document.write("<b>"+"The boolean value is: ");
document.write(temp.toString());
</script>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 57 Client Side Scripting

4.12.5 String Objects


 String is a collection of characters.

 In JavaScript using string object many useful string related functionalities can be exposed off.

 Some commonly used methods of string object are concatenating two strings, converting the
string to upper case or lower case, finding the substring of a given string and so on.
 Here is a listing of some methods of string.
Method Meaning

concat(str) This method concatenates the two strings. For example s1.concat(s2) will result
in concatenation of string s1 with s2.

charAt(index_val) This method will return the character specified by value index_val.

substring(begin,end) This method returns the substring specified by begin and end character.

toLowerCase() This function is used to convert all the uppercase letters to lower case.

toUpperCase() This function is used to convert all the lowercase letters to upper case.

valueOf() This method returns the value of the string.

There is one important property of string object and that is length. For example
var my_str=”Hello”;
var len; Length of the string “Hello” will be
len=my_str.length; stored in the variable len

Here is sample program in which some methods of string object are used.

JavaScript[StringDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>String Properties and Methods Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
var s1="Hello ";
var s2="Parth!";
document.write("First string is: "+s1+"<br>");
document.write("Second string is: "+s2+"<br>");
document.write("Concatenating two strings: "+s1.concat(s2)+"<br>");
document.write("Finding length of Second string : "+s2.length+"<br>");
document.write("The character at 0th position of First string is : "+s1.charAt(0)+"<br>");

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 58 Client Side Scripting

document.write("The First string can be converted to upper case as : "+s1.toUpperCase());


</script>
</strong>
</body>
</html>
Output

Ex. 4.12.1 : Write a script that inputs a line of text, tokenizes it with String method split and
displays the tokens in reverse order.
Sol. :
<html>
<body>
<script type="text/javascript">
var str=new String("I like writing in javascript");
var a=new Array();
a=str.split(' ');
document.write("<strong>The original string is</strong>"+"<br/>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<br/>");
document.write("<strong>The reversed string is</strong>"+"<br/>");
for(i=a.length-1;i>=0;i--)
document.write(a[i]+" ");
</script>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 59 Client Side Scripting

4.12.6 Object Creation and Modification


 The web designer can create an object and can set its properties as per his requirements.

 The object can be created using new expression.

 Initially the object with no properties can be set using following statements
Myobj=new Object();
 Then using dot operator we can set the properties for that object.

 The object can then be modified by assigning the values to this object.

JavaScript[ObjectDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Object Creation Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
var Myobj;
var n,i;
//creating an object
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 60 Client Side Scripting

Myobj=new Object();
//setting the propertis for newly created object
Myobj.id=10;
Myobj.name="Anuradha";
document.write("The ID is "+Myobj.id+"<br/>");
document.write("The Name is "+Myobj.name);
</script>
</strong>
</body>
</html>
Output

Alternative method of creating an object and modifying the properties is as given below -
var Myobj={name:"Anuradha",id:10};
Then using document.write statement we can display the property values as follows -
document.write("The ID is "+Myobj.id+"<br/>");
document.write("The Name is "+Myobj.name);
The property of created object can be deleted using an expression delete. Normally the property
of an object is deleted in order to free the allocated memory so that this memory can be reused by
other process.

University Questions

1. Discuss javascript array object in detail. AU : Dec.-11, Marks 8


2. Explain the javascript object Math. AU : Dec.-13, Marks 8
3. What are the methods associated with array object in JavaScript ? Explain each one with
example. AU : Dec.-09, Marks 16

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 61 Client Side Scripting

4.13 Form Processing in JavaScript AU : Dec.-09, May-08, 14, Marks 8

 Various control objects can be placed on the form. These control objects are also called as
widgets.
 Various widgets used in JavaScript are -Text box, Push button, Radio button, Check box and so
on.
We have discussed how to place various widgets on HTML page in section 2.10. JavaScript can
be associated with the form elements for validation purpose. Let us now discuss the form
validation with the help of examples

Ex. 4.13.1 : Write a javaScript to display a welcome message using alert whenever a button of a
html form is pressed. AU : Dec.-09, Marks 8
Sol. :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function my_fun()
{
alert("WELCOME");
}
</script>
</head>
<body>
<center>
<form>
<input type="button" name="Button1" value="Click" onClick="my_fun()";/>
</form>
</center>
</body>
</html>

Ex. 4.13.2 : Write a Javascript that inputs a telephone number as a string in the form of
(555) 5555555. The script should use string method split to extract the area code as a token, the
first 3 digits of the phone number as a token, the last 4 digits of the phone number as a token.
Display the area code in one text field and seven digit phone number in another text field.
AU : May-08, CSE, Marks 8
Sol. : HTML Document[phNo.html]
<html>
<head>
<title>Phone Number Demo</title>
<script type="text/javascript">
function TestString()
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 62 Client Side Scripting

{
var str=document.form1.input.value;
var i=str.match(/"("\d{3}")"\" "\d{3}"-"\d{4}/);
var temp1=str.split("(");
var temp2=temp1[1].split(")")
document.form1.area.value=temp2[0];
var temp3=temp2[1].split(" ");
var temp4=temp3[1].split("-")
document.form1.phnum.value=temp4[0]+temp4[1];
}
</script>
</head>
<body>
<form name="form1">
<b>Enter phone number:</b><input type="text" name="input" value=""><br/><br/>
<b>Area Code:</b><input type="text" name="area" value=""><br/><br/>
<b>Phone Number:</b> <input type="text" name="phnum" value=""><br/><br/>
<input type="button" value="Click"onclick=TestString(input)>
</body>
</html>
Output

Ex. 4.13.3 : Write a JavaScript for password verification.


Sol. :
<!DOCTYPE html>
<html>
<head>
<title>Demo of onlclick Tag Attibute</title>
<script type="text/javascript">
function my_fun()
{

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 63 Client Side Scripting

var mypwd=document.getElementById("pwd");
var my_re_pwd=document.getElementById("re_pwd");
if(mypwd.value=="")
{
alert("You have not entered the password");
mypwd.focus();
return false;
}
if(mypwd.value!=my_re_pwd.value)
{
alert("Password is not verified, Re-enter both the passwords");
mypwd.focus();
mypwd.select();
return false;
}
else
{
alert("Congratulations!!!");
return true;
}
}
</script>
</head>
<body>
<center>
<form id="form1">
<label> Enter your password
<input type="password" value="" id="pwd" />
</label>
<br/><br/>
<label> Re-Enter the password
<input type="password" value="" id="re_pwd" onblur="my_fun();"/>
</label><br/>
<input type="submit" value="Submit" name="submit" onsubmit="my_fun();"/>
<input type="reset" value="Reset" name="reset"/><br/>
</form>
</center>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 64 Client Side Scripting

Output(Run1)

Output(Run2)

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 65 Client Side Scripting

Output(Run3)

Ex. 4.13.4 : Write JavaScript to validate a for consisting of Name, Age, Address, EmailID, hobby
(check box), Gender(radio box), country(Drop down menu).
Sol. : ApplicationForm.html
<html>
<head>
<title>The Student Registration Form</title>
<script type=text/javascript>
function validate()
{

var i;
var name_str=document.my_form.name;
var phoneID=document.my_form.ph_txt;
var ph_str=document.my_form.ph_txt.value;
var str=document.my_form.Email_txt.value;
if((name_str.value==null)||(name_str.value==""))
{
alert("Enter some name") Validating Name
return false
}
if(document.my_form.Age_txt.value=="")// validating age
{
alert("Enter Some Age")
return false
}
if((document.my_form.Age_txt.value<"5")&&(document.my_form.Age_txt.value>"21"))
{

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 66 Client Side Scripting

alert("Invalid Age")
return false
}

if(ph_str.length<1 ||ph_str.length>11)
{
alert("Invalid length of Phone Number")
return false Validating Phone Number
}
for (i = 0; i < ph_str.length; i++)
{
var ch = ph_str.charAt(i);
if (((ch < "0") || (ch > "9"))){
alert("Invalid Phone Number")

phoneID.focus()
return false
}
}

var index_at=str.indexOf("@")
var len=str.length
var index_dot=str.indexOf(".")
var emailID=document.my_form.Email_txt
if ((emailID.value==null)||(emailID.value==""))
{ Validating Email ID
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (str.indexOf("@")==-1)
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(".")==-1 || str.indexOf(".")==0
|| str.indexOf(".")==index_at)
{
alert("Invalid E-mail ID")
return false Validating Email ID
}

if (str.indexOf("@",(index_at+1))!=-1)
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1)

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 67 Client Side Scripting

{
alert("Invalid E-mail ID")
return false
}
if (!document.my_form.group1[0].checked && !document.my_form.group1[0].checked)
{
alert("Please Select Sex");
return false;
}
if (!document.my_form.group1[0].checked && !document.my_form.group1[0].checked)
{
alert("Please Select Sex");
return false;
}
return true

}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name=my_form onsubmit=validate()>
<strong>Name: </strong>
<input type=text name=name><br/>

<strong>Age: </strong>
<input type=text name=Age_txt><br/>

<strong>Phone No:</strong>
<input type=text name=ph_txt><br/>
<strong>Email: </strong>
<input type=text name=Email_txt><br/><br/>
<strong>Sex: </strong>
<input type="radio" name="group1" value="Male">Male
<input type="radio" name="group1" value="Female">Female<br/><br/><br/>
<strong>Hoby: </strong>
<input type="checkbox" name ="option1" value="Singing">Singing<br/>
<input type="checkbox" name ="option1" value="Reading">Reading<br/>
<input type="checkbox" name ="option1" value="T.V.">Watching T.V<br/>
<br/><br/>
<strong>Country:</strong>
<select name="My_Menu">
<option value="India">India</option>
<option value="China">China</option>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 68 Client Side Scripting

<option value="Shrilanka">Shrilanka</option>
</select>
<center>
<input type=submit value=Submit></br>
</center>

</body>
</html>
Output

Ex. 4.13.5 : Design a HTML form for validation the users with fields user name and password and
ok button which should receive the input from the user and responses as authorized or invalid
user name or invalid password. AU : May-14, Marks 8
Sol. :
<head>
<title>HTML FORM</title>
<script type=text/javascript>
function validate()
{
var user=document.form1.username;
var pass=document.form1.password;
if((user.value==null)||(user.value==""))
{
alert("Enter some user name");
}
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 69 Client Side Scripting

if((pass.value==null)||(pass.value==""))
{
alert("Enter some password");

}
if(user.value=="admin")
{
alert("Valid user name");

}
if(pass.value=="password")
{
alert("Valid password");
}
else
alert("Invalid username/password");
}
</script>
</head>
<body>
<form id="form1" name="form1" onsubmit=validate()>
<table width="510" border="0" align="center">
<tr> <td>Username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr> <td>Password</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="button" value="OK" /></td>
</tr>
</table>
</form>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 70 Client Side Scripting

4.14 JavaScript Debuggers AU : May-12, Marks 8

 JavaScript is a scripting language which is very much similar to a programming language. It


supports the arrays, functions and control statements. Hence debugging the javascript is just
similar to debugging any programming language.
 The standard traditional method of debugging the JavaScript is by use of alert() to display the
values of corresponding variables. But it is a complex method of debugging as within the loop if
we write the alert statement then each time the popup window will appear to display the
corresponding messages.
 However we can make use of some other API methods for debugging the javascript.

 Another way is to use the log() function console API.

 Example Program : Following is a simple script that illustrates how to debug the values of the
variable using the log() function of console.
<!DOCTYPE html>
<html>
<head>
<title>Continue Statement</title>
</head>
<body>
<script type="text/javascript">
for(i=10;i>=0;i--)
{ Here x==5 is true hence it will return
if(i==5) true along with the message.
{
x=i;
console.log('x is equal to 5', x == 5);
continue;
}
console.log('i= '+i,i == 5);
document.write(i);
document.write("<br>");
}
document.write("The number "+x+" is missing in above list" );
</script>
</body>
</html>
Just open the above code in Google Chrome. Press F12, click on the Console to get the
debugging done using the log function. Here is the snapshot for the same.
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 71 Client Side Scripting

Output

University Question

1. Discuss about javascript debugging. AU : May-12, Marks 8

4.15 Examples AU : May-08, 09, Dec.-08, 09, Marks 16

Ex. 4.15.1 : Design web page to create a clock with a timing event.
AU : June- 09, Marks 4
Sol. : clock.html
<html>
<head>
<script type="text/javascript">
function Display()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
h=ConvertTwelve(h);
m=SingleDigit(m);

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 72 Client Side Scripting

s=SingleDigit(s);
document.getElementById("mytext").value=h+":"+m+":"+s;
t=setTimeout('Display()',500);
}
function ConvertTwelve(h)
{
if(h>=12)
h=h-12;
return h;
}
function SingleDigit(i)
{
if (i<10)
{
i="0" + i;//writing 0 before single digit number
}
return i;
}
</script>
</head>
<body onload="Display">
<input type="text" value="" size="5" id="mytext"/>
</body>
</html>
Output

Ex. 4.15.2 : Write HTML program for the registration of new customer to the online banking
system (Customer Data collected using a form, after submitting account number and type of
account and username, password is displayed as output) AU : May-08, CSE, Marks 8

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 73 Client Side Scripting

Sol. : HTML Document[bank.html]


<html>
<head>
<title>Online Banking System</title>
<script type="text/javascript">
function fun()
{
alert("Name: "+form1.userName.value);
alert("Password: "+form1.pwd.value);
alert("Account Type: "+form1.MyMenu.value);
alert("Account Number: "+form1.AccNo.value);
}
</script>
</head>
<body bgcolor="khaki">
<form name="form1" onsubmit="fun()">
<table>
<tr><td><b>Name:</b></td><td><input type="text" name="userName"></tr>
<tr><td><b>Password:</b></td><td><input type="password" name="pwd"></tr>
<tr><td><b>Account Type:</b></td>
<td><select name="MyMenu">
<option value="Savings Account">Savings Account</option>
<option value="Current Account">Current Account</option>
</select>
</td>
</tr>
<tr><td><b>Account Number:</b></td><td><input type="text" name="AccNo"></tr>
</table>
<br/><br/>
<center>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</center>
</form>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 74 Client Side Scripting

Output

Ex. 4.15.3 : Develop a HTML page which accepts


- Any mathematical expression
- Evaluate the expression
- Displays the result of the evaluation. AU : Dec.-08, CSE, Marks 16
Sol. : HTML Document[eval.html]
<html>
<head>
<title>Expression Evaluation</title>
<script type="text/javascript">
function Compute()
{
document.form1.ans.value=eval(document.form1.my_exp.value);
}
</script>
</head>
<body>
<form name="form1">
<b>Enter Expression here:</b><br/><input type="text" name="my_exp">

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 75 Client Side Scripting

<br/><br/>
&nbsp&nbsp&nbsp&nbsp<input type="button" value="Evaluate" onclick=Compute()>
<br/><br/>
<b>Answer is: </b><br/><input type="text" name="ans">
</form>
</body>
</html>
Output

Ex. 4.15.4 : Develop a simple online shopping application using JavaScript.


(Assume your own data) AU : Dec.-09, CSE, Marks 16
Sol. :
Step 1 : We will first write a simple JavaScript which will allow user to enter the personal
details and items to be purchased.
HTML Document[shopping.html]
<!DOCTYPE html PUBLIC "-//W#C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="JavaScript">
var cost;
function fun()
{
cost=0;
if(document.myform.Item1.checked){cost=cost+20.15;}
if(document.myform.Item2.checked){cost=cost+10.10;}
if(document.myform.Item3.checked){cost=cost+26;}

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 76 Client Side Scripting

if(document.myform.Item4.checked){cost=cost+29;}
document.myform.total.value="$"+cost;
}
</script>
</head>
<body bgcolor="pink">
<form name="myform" action="http://localhost/cgi-bin/purchaseInfo.cgi" enctype="text/plain"
method="post">
<center><h2>Online shopping Application</h2></center>
<strong>Personal Details:</strong>
<table>
<tr><td>name:</td><td> <input type="text" name="customer"/></td></tr>
<tr><td>City:</td><td> <input type="text" name="city"/></td></tr>
<tr><td>Phone:</td><td> <input type="text" name="phone"/></td></tr>
<tr><td>Email_Id:</td><td> <input type="text" name="email"/></td></tr>
</table>
<hr/>
<strong>Description:</strong>
<p>Following are some items with their prices.</p>
<p>Choose the required items by checking the chekboxes.</p>
</div>
<hr/>
<strong>Items to be chosen:</strong>
<br/>
<input type="checkbox" name="Item1" value="Item1_chosen" onclick="fun()"> Item One($20.15)
<p><input type="checkbox" name="Item2" value="Item2_chosen" onclick="fun()"> Item
Two($10.10)
<p><input type="checkbox" name="Item3" value="Item3_chosen" onclick="fun()"> Item Three($26)
<p><input type="checkbox" name="Item4" value="Item4_chosen" onclick="fun()"> Item Four($29)
<input type="text" name="total" value="0"/>
<br/><br/>
<center>
<input type="submit" value="Place the Order" />
<input type="reset" value="Clear" />
</center>
</form>
</body>
</html>
Step 2 : When user click the Place the order button the submitted input can be collected in a
cgi file. The sample cgi file can be written as follows -
CGI Document[purchaseInfo.cgi]
#!/program files/perl/bin/perl
use CGI qw(:standard);
print header;
print start_html(-BGCOLOR =>"Khaki");
print h2("Thank you for spending your valuable time with us!!!<br/>");
my($name)=param("customer");
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 77 Client Side Scripting

print"<b>Order submitted is...</b>$name";


print end_html;
Step 3 : The output can be viewed as follows -

Click the ‘Place the order’ button and following output can be seen

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 78 Client Side Scripting

Ex. 4.15.5 : Write a Javascript to validate radio button, operator field and check box.
Sol. :
JavaScript Program
<html>
<head>
<script LANGUAGE="JavaScript">

function ValidateForm(form)
{

if ((form.gender[0].checked == false ) && ( form.gender[1].checked == false ))


{ alert ( "Please choose your Gender: Male or Female" );
return false;
}
if ((form.status[0].checked == false ) && ( form.status[1].checked == false ))
{ alert ( "Please choose your choice: AC or non AC" );
return false;
}
if ( form.course.selectedIndex == 0 )
{ alert ( "Please select Some Course." );
return false;
}
return true;
}
</script>
</head>
<body>
<br>
<form>
Your Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<br/>
Choice: <input type="checkbox" name="status">AC
<input type="checkbox" name="status"> Non AC
<br/>
Course:
<select name="course">
<option value="">Select an Option:</option>
<option value="Computer">Computer</option>
<option value="Mechanical">Mechanical</option>
<option value="E&Tc">E&Tc</option>
</select>
<br/><br/>

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 79 Client Side Scripting

<input type="button" name="SubmitButton" value="Submit"


onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>
</body>
</html>

Two Marks Questions with Answers

Q.1 What is the benefit of using JavaScript code in an HTML document ? AU : Dec.-07, CSE
Ans. : Following are some significant benefits of using JavaScript code in an HTML document
1. The client side data validation can be possible using JavaScript.
2. We can access the HTML elements. That means we can have control over HTML, BODY,
TITLE tags.
3. Since JavaScript is based on the programming constructs we can control the logic of a
simple scripting language. For example if a mouse pointer is moving over a text then change
its colour.
4. JavaScript can determine the visitor’s browser and can load the page accordingly.
Q.2 What is the need for client side scripting ? AU : May-09, CSE
Ans. : Following are the issues that get handled using client side scripting -
1. Simple scripting language like HTML or XML represents the data on the web page in
simplest manner.
2. The scripting languages like JavaScript and DHTML are useful for enhancing the
interactivity of the user with the web browser.
3. Mathematical evaluation is also possible using the client side scripting.
4. Using client side scripting languages the web page which gets designed for the user provides
a graphical user interface using which the user can input his data in an elegant manner. This
data can then be submitted to database or any server side scripting language in order to
process it further.
5. The input validation can also be possible using client side scripting language like JavaScript.
6. Using cascading stylesheets with the client scripts the look and feel of the web page can be
enhanced.
Q.3 List out the objects used in JavaScript with its purpose. AU : May-09, CSE, May-12
Ans. : Various objects that can be used in JavaScript are -
1. Math Object - This object provides useful methods that are required for mathematical
computations.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 80 Client Side Scripting

For example : For computing square root of some number sqrt(num) method is used.
For finding out minimum value of a and b min(a,b) method is used.
2. Number Object - This object is used has various numeric properties.
For example : Largest possible number gets displayed using MAX_VALUE, for displaying
the pi value PI property is used.
3. Date Object - This object is used for obtaining date and time. For example using getTime()
function the number of milliseconds can be obtained.
4. Boolean Object - This is the simplest object used to obtain true or false values.
5. String Object - This object provides many useful string related functionalities.
For example : For finding out the substring of a given string substring(begin,end) method
can be used.
Q.4 Comment on the statement. “Each object of a class has its own instance of static
member variable.” AU : Dec.-08
Ans. : When we create an object for a class then each object has its own distinct copies of
variables. Such variables are called instance variables. For example if declare a class MyCar as
follows
class MyCar
{
private String color;
private String model;
private double price;
}
This class has instance variables color, model and price. Now, each object of class MyCar
will have its own values for these variables. These values will be static in nature. These objects
can be stored at different memory locations. Thus every instance of the class(object) shares a
class variables. Hence it is said that every object of a class has its own instance of static member
variable.
Q.5 What is JavaScript statement ? Give an example. AU : Dec.-11
Ans. : The assignment statement in JavaScript is very much similar to C. For example
Sum+=10
Sum=sum+10
Can be written in JavaScript.
Q.6 Give any three uses of JavaScript.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 81 Client Side Scripting

Ans. :
1) The JavaScript can be used to create some web applications such as Calculator, Calender,
Paint like applications.
2) JavaScript can be used to detect the visitor’s browser.
3) JavaScript can be used to validate the data.
Q.7 What kind of comments are supported by the JavaScript ?
Ans. : JavaScript supports following comments -
The // is used to specify the single line comment.
The /* and */ can be used to specify the multi-line comments.
The XHTML <!- -> and <- -> is used in JavaScript.
Q.8 Explain how the string literals are used in JavaScript ?
Ans. : The string is a collection of characters. The string literal is used within the single quote or
double quotes.
Q.9 What is the use of the word ‘var’ in the JavaScript ?
Ans. The word var is used to define the variables of numeric or string type.

Q.10 What do you mean by Coercion ?


Ans. : JavaScript supports the automatic type conversion. The coercion is a type conversion
method. This is implicit type of conversion.
Q.11 What is the use of parseInt() and parseFloat() methods ?

Ans. :
The parseInt() and parseFloat() methods are used to separate out the integer and float values
respectively from the string. For example parseInt(“12abc”) will return 12 from the string.
Q.12 What is the use of pop up boxes in JavaScript ?
Ans. : There are three types of popup boxes used in JavaScript. Using these popup boxes the
user can interact with the web application.
Q.13 What is the use of toString method with respect to arrays ?
Ans. : The toString method converts the array to string.

Q.14 What are the advantages of indirectly embedding the JavaScript in the Web document ?
Ans. : Following are the advantages of indirectly embedding the JavaScript in the web
document -
1. Script can be hidden from the browser.
2. The layout and presentation of web document can be separated out from the user interaction
through the JavaScript.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 82 Client Side Scripting

Q.15 What are the properties and methods object window for screen output ?
Ans. : Following are some properties and methods of object window -
1. The property write of object window is used to display something on the screen.
2. The methods alert, prompt and confirm are useful for handling screen output and keyboard
input.
Q.16 Explain array creation in JavaScript with example. AU : May-11
Ans. : In JavaScript the array can be created using Array object. Suppose, we want to create an
array of 10 elements then we can write,
var ar = new Array(10);
Using new operator we can allocate the memory dynamically for the arrays. In the brackets
the size of an array is mentioned and the var ar denotes the name of the array. Thus by the above
sentence an array ar will be created in which we can store 10 elements at the most. Sometimes
the above statement can be written like this
var ar;
ar=new Array(10);
Q.17 What are global functions in JavaScript ?
Ans. : The global functions are the top level functions in JavaScript that are independent of any
specific object. These functions are built in objects of JavaScript. Examples of global functions
are –
Name of the Function Purpose

encodeURI This function is used to encode URI

decodeURI This function is used to decode the encoded URI

parseInt This function parses the string and returns the integer
value.

eval The eval function is used to evaluate the expression.

Q.18 What is the meaning of widgets ?

Ans. : Various graphical controls such as text box, check box,radio buttons, push buttons and so
on can be placed on the form for user interactivity. These control objects are called the widgets.
Q.19 State the types of java script statements with examples. AU : Dec.-13
Ans. : Various types of javascript statements are -
1. Simple assignment statements
2. Conditional statements
3. Object manipulation statements
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 83 Client Side Scripting

4. Comment statements
5. Exception handling statements
Q.20 Write a Java Script to print “Good Day” using IF-ELSE condition. AU : May-14

Ans. :
<html>
<head>
<script>
function MyMessage()
{
var today=new Date();
var h=today.getHours();
if(h<12)//After 12 O'clock Say Good Bye
//Before 12 O'clock say Good Day
document.write("Good Day");
else
document.write("Good Bye");
}
</script>
</head>
<body onload="MyMessage()">
</body>
</html>
Q.21 List any four methods of date object. AU : Dec.-16

Ans.

Method Meaning

getTime() It returns the number of milliseconds. This value is the difference between the
current time and the time value from 1st January 1970.

getDate() Returns the current date based on computers local time.

getDay() Returns the current day. The day number is from 0 to 6 i.e. from sunday to
saturday.

getHours() Returns the hour value ranging from 0 to 23, based on local time.

getSeconds() Returns the second value ranging from 0 to 59, based on local time.

TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 84 Client Side Scripting

Q.22 How exceptions are handled in JavaScript ? AU : May 17


Ans. : The exceptions are handled in Javascript using try… catch block.s
For example –
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}
else
{
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
Q.23 What are object literal in JavaScript. AU : Dec.-18
Ans. : The object literal in javascript is a name-value pair wrapped in curly braces.
For example -
Var myobj = {
name : “AAA”,
rollno : 2,
marks : 82
};



TM
Technical Publications - An up thrust for knowledge
Unit III

1 5 Document Object Modeling

Syllabus
Host Objects : Browsers and the DOM-Introduction to the Document Object Model DOM History
and Levels-Intrinsic Event Handling-Modifying Element Style-The Document Tree-DOM Event
Handling-Accommodating Noncompliant Browsers Properties of window.

Contents
5.1 Introduction to the Document Object Model
5.2 DOM History and Levels
5.3 The Document Tree ................................................. May-11,12 Dec.-13, ............. Marks 8
5.4 Modifying Element Style .......................................... Dec.-12, 15,......................... Marks 16
5.5 Intrinsic Event Handling .......................................... Dec-09,12, May-10,11, ........ Marks 8
5.6 DOM2 Event Model ................................................. May-08,12,16,
................................................................................. Dec.-08, 11,12,13,............... Marks 16
5.7 Accommodating Noncompliant Browsers
5.8 Properties of Window .............................................. May-10, ................................ Marks 2
Two Marks Questions with Answers

(5 - 1)
Web Technology 5-2 Document Object Modeling

5.1 Introduction to the Document Object Model


 The Document Object Modeling(DOM) is for defining the standard for accessing and
manipulating HTML,XML and other scripting languages.
 It is the W3C recommendation for handling the structured documents.

 Normally the structured information is provided in XML, HTML and many other documents.

 Hence DOM provides the standard set of programming interfaces for working with XML and
XHTML and JavaScript.
What is DOM?

Document Object Model (DOM) is a set of platform independent and language neutral Application
Programming Interface (API) which describes how to access and manipulate the information stored in
XML,HTML and JavaScript documents.

5.2 DOM History and Levels


 Various levels of DOM are enlisted in the following table -

Level Description

DOM 0 This model is supported by the early browsers. This level could support JavaScript. This
version was implemented in Netscape 3.0 and Internet Explorer 3.0 browsers.

DOM 1 This version was issued in 1998 which was focused on XHTML and XML.

DOM 2 This version was issued in 2000 that could specify the style sheet. It also supports the event
model and traversal within the documents.

DOM 3 This is the current release of DOM specification published in 2004. This version could deal
with XML with DTD and schema, document validations, document views and formatting.

5.3 The Document Tree AU : May-11,12 Dec.-13, Marks 8

 Basically DOM is an Application Programming Interface (API) that defines the interface
between HTML document and application program. That means, suppose application program
is written in Java and this Java program wants to access the elements of HTML web document
then it is possible by using a set of Application Programming Interfaces (API) which belongs to
the DOM.
 The DOM contains the set of interfaces for the document tree node type. These interfaces are
similar to the Java or C++ interfaces. They have objects, properties and methods which are
useful for respected node type of the web document.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5-3 Document Object Modeling

 The documents in DOM are represented using a tree like structure in which every element is
represented as a node. Hence the tree structure is also referred as DOM tree.
 For example : Consider following XHTML document.
<html>
<head>
<title>This is My Web Page </title>
</head>
<body>
<h1>Hello Friends </h1>
<h2>How are you?</h2>
</h3>See you</h3>
</body>
</html>
 The DOM tree will be

Fig. 5.3.1 DOM structure for simple web document

 We can describe some basic terminologies used in DOM tree as follows -


1. Every element in the DOM tree is called node.
2. The topmost single node in the DOM tree is called the root.
3. Every child node must have a parent node.
4. The bottommost nodes that have no children are called leaf nodes.
5. The nodes that have the common parent are called siblings.

University Questions

1. Explain about document tree in detail. AU : May-11,12 Marks


2. List and explain the various types of document nodes . AU : Dec.-13, Marks 8

TM
Technical Publications - An up thrust for knowledge
Web Technology 5-4 Document Object Modeling

5.4 Modifying Element Style AU : Dec.-12, 15,Marks 16

We can access or change the contents of document by using various methods. Some commonly
used properties and methods of DOM are as follows :

Methods
Method Meaning
getElementById This method is used to obtain the specific element which is specified by
some id within the script.
createElement This method is used to create an element node.
createTextNode Useful for creating a text node.
createAttribute Useful for creating attribute.
appendChild For adding a new child to specified node, this method is used.
removeChild For removing a child node of a specific node, this method is used.
getAttribute This method is useful for returning the specified attribute value.
setAttribute This method is useful for setting or changing the specified attribute to the
specified value.

Properties
Property Meaning
attributes This property is used to get the attribute nodes of the node.
parentNode This DOM property is useful for obtaining the parent node of the specific
node.
childNodes This DOM property is useful for obtaining the child nodes of the specific
node.
innerHTML It is useful for getting the text value of a node.

5.4.1 Accessing Elements using DOM


 There are several ways by which we can access the elements of the web document.
 To understand these methods of accessing we will consider one simple web document as
follows.
<html >
<head>
<title>This is My Web Page </title>
</head>
<body>
<form name=“form1”>
<input type=”text” name=“myinput”/>
</form>

TM
Technical Publications - An up thrust for knowledge
Web Technology 5-5 Document Object Modeling

</body>
</html>

Method 1
 Every XHTML document element is associated with some address. This address is called DOM
address.
 The document has the collection of forms and elements. Hence we can refer the text box
element as
var Dom_Obj=document.forms[0].elements[0];
 But this is not the suitable method of addressing the elements. Because if we change the above
script as

<form name=“form1”>
<input type=“button” name= “mybutton”/>
<input type=”text” name=“myinput”/>
</form>

then index reference gets changed. Hence another approach of accessing the elements is
developed.

Method 2
 We can access the desired element from the web document using JavaScript method
getElementById. The element access can be made as follows -
var Dom_Obj=document.getElementById(“myinput”);
 But if the element is in particular group, that means if there are certain elements on the form
such as radio buttons or check boxes then they normally appear in the groups. Hence to access
these elements we make use of its index. Consider the following code sample
<form id=”Food”>
<input type=“checkbox” name=“vegetables” value=”Spinach” />Spinach
<input type=“checkbox” name=“vegetables” value=”FenuGreek” />FenuGreek
<input type=“checkbox” name=“vegetables” value=”Cabbage” />Cabbage
</form>

 For getting the values of these checkboxes we can write following code.
var Dom_obj=document.getElementById(“Food”);
for(i = 0 ; i < Dom_Obj.vegetables.length ; i++)
document.write(Dom_Obj.vegetables[i]+“<br/>”);

TM
Technical Publications - An up thrust for knowledge
Web Technology 5-6 Document Object Modeling

5.4.2 Modifying Elements using DOM

Appending an element Using DOM


We can add new node in the HTML document using the DOM method appendChild method
Following example illustrates the idea
<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">The first sentence in HTML document.</p>
<p id="p2">The second sentence in HTML document.</p>
</div>

<script>
var pnode = document.createElement("p");
var node = document.createTextNode("This is newly added sentence in HTML document.");
pnode.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(pnode);
</script>
</body>
</html>

Inserting an element Using DOM


We can insert a node in between the nodes by using appendChild and insertBefore method. For
example
TM
Technical Publications - An up thrust for knowledge
Web Technology 5-7 Document Object Modeling

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">First Sentence</p>
<p id="p2">Second Sentence</p>
</div>

<script>
var pnode = document.createElement("p");
var node = document.createTextNode("Newly Added Sentence!!!");
pnode.appendChild(node);
var element = document.getElementById("div1");
var nextnode = document.getElementById("p2");
element.insertBefore(pnode,nextnode);
</script>

</body>
</html>
Output

Removing an element Using DOM


We can remove or delete particular from HTML document using DOM’s removeChild
method.
Here is illustration
<!DOCTYPE html>
<html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 5-8 Document Object Modeling

<body>

<div id="div1">
<p id="p1">First Sentence</p>
<p id="p2">Second Sentence</p>
<p id="p3">Third Sentence</p>
</div>

<script>
var parentnode = document.getElementById("div1");
var node = document.getElementById("p2");
parentnode.removeChild(node);
</script>
</body>
</html>
Output

Ex. 5.4.1 : Write a JavaScript to display sum of two elements. Make use of appropriate DOM
method.
Sol. :
<!Doctype html>
<html>
<head>
<script type="text/javascript">
function getSum()
{
var number1=document.getElementById("number1").value;
var number2=document.getElementById("number2").value;
var num1=Number(number1);

TM
Technical Publications - An up thrust for knowledge
Web Technology 5-9 Document Object Modeling

var num2=Number(number2);
alert(num1+num2);
}
</script>
</head>
<body>
<form>
Enter Num1:<input type="text" id="number1" /><br/> <br/>
Enter Num2:<input type="text" id="number2" /><br/>
<input type="button" value="SUM" onclick="getSum()"/>
</form>
</body>
</html>
Output

Ex. 5.4.2 : Write a JavaScript to welcome the user by his/her name when he enters his/her name
in textbox. Make use of appropriate DOM method.
Sol. :
<!Doctype html>
<html>
<head>
<script type="text/javascript">
function display()
{
var name=document.getElementsByName("user");

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 10 Document Object Modeling

alert("Welcome "+name[0].value);
}
</script>
</head>
<body>
<form>
Enter Name:<input type="text" name="user" /><br/> <br/>
<input type="button" value="Greet" onclick="display()"/>
</form>
</body>
</html>
Output

University Questions

1. With a simple example illustrate how the elements of the HTML document tree structure can
be accessed using Javascript. AU : Dec.-12, Marks 16
2. Explain DOM model. AU : Dec.-15, Marks 8

5.5 Intrinsic Event Handling AU : Dec-09,12, May-10,11, Marks 8

 Definition of Event : Event is an activity that represents a change in the environment. For
example mouse clicks, pressing a particular key of keyboard represent the events. Such events
are called intrinsic events.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 11 Document Object Modeling

 Definition of Event Handler : Event handler is a script that gets executed in response to these
events. Thus event handler enables the web document to respond the user activities through the
browser window.
 JavaScript support this special type of programming in which events may occur and these events
get responded by executing the event handlers. This type of programming is called event-driven
programming.
 Events are specified in lowercase letters and these are case-sensitive.

 Event Registration : The process of connecting event handler to an event is called event
registration. The event handler registration can be done using two methods -
o Assigning the tag attributes
o Assigning the handler address to object properties.

Internet Programming
On occurrence of events the tag attribute must be assigned with some user defined
functionalities. This will help to execute certain action on occurrence of particular event.
Commonly used events and tag attributes are enlisted in the following table -
Events Intrinsic event Meaning Associated tags
attribute
Losing the focus. <button>
<input>
blur onblur <a>
<textarea>
<select>
On occurrence of <input>
change onchange some change. <textarea>
<select>
When user clicks <a>
click onclick
the mouse button. <input>
When user double <a>
dblclick ondblclick clicks the mouse <input>
button. <button>
When user acquires <a>
the input focus. <input>
focus onfocus <select>
<textarea>

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 12 Document Object Modeling

When user releases Form elements such as


keyup onkeyup the key from the input,button,text,textarea and
keyboard. so on.
When user presses Form elements such as
keydown onkeydown the key down input,button,text,textarea and
so on.
When user presses Form elements such as
keypress onkeypress the key. input,button,text,textarea and
so on.
When user clicks Form elements such as
mousedown onmousedown the left mouse input,button,text,textarea and
button. so on.
When user releases Form elements such as
mouseup onmouseup the left mouse input,button,text,textarea and
button. so on.
When user moves Form elements such as
mousemove onmousemove the mouse. input,button,text,textarea and
so on.
When the user form elements such as
moves the mouse input,button,text,textarea and
mouseout onmouseout
away from some so on.
element.
When the user Form elements such as
moves the mouse input,button,text,textarea and
mouseover onmouseover
away over some so on.
element.
After getting the <body>
load onload
document loaded.
When the reset <form>
reset onreset
button is clicked.
When the submit <form>
submit onsubmit
button is clicked.
On selection. <input>
select onselect
<textarea>
When user exits the <body>
unload onunload
document.

The use of these tag attributes for handling the events is illustrated by following code
sample

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 13 Document Object Modeling

That means when the user clicks the button then as an event handler a user defined function
My_fun() gets called. Basically in this function user writes the instructions that need to be
executed on the button click event.

Ex.5.5.1 : Discuss the properties of mouse events associated with DOM2 with an example.
AU : Dec-12, Marks 8
Sol. : Various types of mouse events associated with DOM2 are click, mousedown, mouseup,
mouseout and mouseover.
Events Intrinsic event Meaning Associated tags
attribute
When user clicks the Form elements such as
mousedown onmousedown left mouse button. input,button,text,textarea and so
on.
When user releases the Form elements such as
mouseup onmouseup left mouse button. input,button,text,textarea and so
on.
When user moves the Form elements such as
mousemove onmousemove mouse. input,button,text,textarea and so
on.
When the user moves form elements such as
mouseout onmouseout the mouse away from input,button,text,textarea and so
some element on.
When the user moves Form elements such as
mouseover onmouseover the mouse away over input,button,text,textarea and so
some element on.
When user clicks the <a>
click onclick
mouse button. <input>
When user double <a>
dblclick ondblclick clicks the mouse <input>
button. <button>

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 14 Document Object Modeling

Following is an example in which image can be dragged and dropped anywhere in the HTML
document. Accordingly the co-ordinates will be displayed.
<html>
<head>
<title> Drag and Drop Demo</title>
<script type = "text/javascript">
var X_offset, Y_offset, Item;
function Catch_function(e)

{
Registering the mouse event with
Item = e.currentTarget; the help of addEventListener
var posX = parseInt(Item.style.left); function.
var posY = parseInt(Item.style.top);
X_offset = e.clientX - posX;
Y_offset = e.clientY - posY;
document.addEventListener("mousemove", Move_function, true);
document.addEventListener("mouseup", Drop_function, true);
e.stopPropagation();
e.preventDefault();

}
function Move_function(e)
{
Item.style.left = (e.clientX - X_offset) + "px";
Item.style.top = (e.clientY - Y_offset) + "px";
e.stopPropagation();
}
function Drop_function(e)
{
document.removeEventListener("mouseup", Drop_function, true);
document.removeEventListener("mousemove", Move_function, true);
e.stopPropagation();
}
</script>
</head>
<body>
<h3>
Click on image below-drag it, move it and then drop anywhere!!!
<br /><br />
<img src="lamp1.jpg"
style = "position: absolute;

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 15 Document Object Modeling

top: 100px;
left: 100px;
border:2px solid;"
onmousedown = "Catch_function(event);" />
</h3>
</body>
</html>
Output

5.5.1 Handling Events from the Body Elements


To understand how events works in JavaScript let us put some Form components on the
JavaScript. The onload event gets activated as soon as the web page gets loaded in the browser’s
window. Following script along with its output illustrate the onload tag attribute.

JavaScript[OnloadDemo.html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo of onload Tag Attibute</title>
<script type="text/javascript">
function my_fun()
{
//This message will be displayed on page loading

alert("Welcome");
} When web document gets
</script> loaded on the browser window
</head> then my_fun() will be called
<body onload="my_fun()">

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 16 Document Object Modeling

</body>
</html>
Output

University Questions

1. Explain the process of event registration.


2. Explain DOM event handling in detail. AU : May-11, Marks 8
3. Describe the event object properties. AU : May-10, Marks 8
4. Explain any four intrinsic event attributes.
5. Write a javascript to demonstrate the onload event. AU : Dec.-09, Marks 6

5.6 DOM2 Event Model AU : May-08,12,16, Dec.-08, 11,12,13, Marks 16

The DOM2 event model provides the generic event system in which the events can be
registered. The event flow can be represented in a hierarchical manner. Using DOM2 event model
information of each event can be obtained.
The DOM2 provides the method for capturing the events so that one can perform specific
action in response to the. It also provides an Event and MouseEvent objects. These are basically
the interfaces which contain information specific to a given event. This information can then be
used by your event processing code.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 17 Document Object Modeling

Following table enlists the Event Interface and types of various Events that can be triggered

Event interface Various events

Event blur,change,abort,error,focus,load,reset,resize,select,scroll,unload,submit

MouseEvent mousedown, mouseup, mouseover, mousemove, mouseout, click

In DOM0 the connection between event and event handler is simple. But in DOM2 the event
model is complicated one.

5.6.1 Event Propagation


 Event propagation means travelling of an event. To understand the event propagation consider
one scenario -
Suppose there is an element inside other element. And both these elements have onchange
event handlers. Then the question occurs here is that which event will be handled first whether
the event in the outer element or the event in inner element? Unfortunately there are two
opinions about it - the first opinion is the event in the outer element should be handled first and
then the event in the inner element should get handled(event capturing) (Refer Fig. 5.6.1).

Fig. 5.6.1 Event capturing

According to other opinion, first directly the event which is present in the inner element
should be handled and then the event in the outer element must be handled (event bubbling).
(Refer Fig. 5.6.2).
The DOM0 supports this kind of event handling.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 18 Document Object Modeling

Fig. 5.6.2 Event bubbling

 Event object is created at a node in the document tree. This node is called the target node.
 To solve the controversy of event handling whether it is using capturing or using bubbling, the
W3C suggested the DOM2 event model in which both the approaches are considered.
 According to DOM2 event model the event handling is a three-phase process

Phase 1
This phase is called the capturing phase in which the event starts at root node in the
document tree and propagates towards the target node. In this direction if any event handler is
found(not the target node event handler) then first of all it is checked whether they are
enabled or not. If there is any enabled event then it is executed by the capturing phase(may or
may not be enabled event). Thus event then reaches to the target node.

Phase 2
In this phase the handlers registered to the target node get executed.

Phase 3
This phase is called the bubbling phase in which the event starts at the target node and
moves up to the document tree node. In this phase the event bubbles up the document tree to
the root node. On this trip if any event handler registered for event gets executed by the
bubbling phase(may or may not be enabled event).
 There are some events that can be bubbled or captured. All the mouse events can be bubbled but
load and unload events do not get bubbled.
 The stopPropagation method of event object is useful for stopping the propagation of an event.

 Events cause certain action on occurrence of particular action. Using preventDefault method
the default action can be prevented on occurrence of an event.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 19 Document Object Modeling

5.6.2 Event Handler Registration


 The event handler registration in DOM0 is called the traditional method of event registration. In
DOM0 there are two methods by which the event registration is done -

Method 1 :
 In this method the event handler code can be assigned to the attribute of an element. For
example -
element.onclick=my_fun;
That means when user clicks on the element the event handler function my_fun() will be
called. Note that we must not use parenthesis while specifying the function my_fun.

Method 2 :
 In this method name of the event handler is assigned to the property associated with the event.
For example
<input type=“button” value=“Enter” onclick=“my_fun();” />
Thus the onclick becomes the property of the button element to which the event handler
code is assigned. Hence on clicking the button, the code for my_fun() will get invoked as the
event handler.
 Drawback : The drawback of using DOM0 event model for registering the event is that we
cannot assign two different handlers for the same event. Sometimes we want two different
functionalities to get executed for the same type of event. For instance we may want to check
the spelling on button click or we may want to edit the code on button click. This can not be
achieved in DOM0 event registration model.
 To overcome the drawback of traditional event registration model W3C has introduced the new
model called DOM2 event registration model. That means at a time we can have more than
one event handler functions that can be associated with the same event.
 In this model a method addEventListener is called to which the name of the event and event
listener is passed as a parameter.
 The addEventListener is defined in EventTarget interface.
addEventListener(“name_of_event”,handler_function,true or false);
The first parameter is the name of the event which must be given in quotes as it is considered to
be the string literal. The second parameter is the event handler function which is basically the user
defined function for specifying the actions to be taken when the event gets fired. The third
parameter is either true or false. If the value is true then that means the particular event is enabled
for using it in capturing phase. If the value is false then that means the particular event is enabled
for using it in bubbling phase.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 20 Document Object Modeling

 For example -
document.my_button.addEventListener(“click”,my_fun,false);
When user clicks the button element whose id is my_button the event handler code my_fun
gets invoked. The third parameter false indicates that the event is enabled for the bubbling phase.
Thus addEventListener is useful in registering the event.
 For removing or deleting the event registration the method removeEventListener is used. This
method takes the same parameters as the addEventListener. Hence
removeEventListener(“name_of_event”,handler_function,true or false);
 The this keyword is used to refer the owner of a function. In event registration function if we
use the this keyword then it refers to the element the event is handled by
For example -
document.my_button.addEventListener(“click”,my_fun,false);
 The event handler function my_fun will be
function my_fun()
{
this.style.background=“pink”;
}
That means if we click the button my_button then the background color gets changed to pink.
 There is a event property of global window object which provides the event details.
For example

Placing the text box on the


<input type=“text” value=“ ”id=“my_txt” /> form


Txt_obj=getElementById(“my_txt”); Registering the event when
Txt_obj.addEventListener(“change”,my_fun,false); user types something in the
…. text box

function my_fun(event)
{ The contents that are typed
var My_name=event.currentTarget; by the user in the text box
alert(My_name.value); gets displayed using alert
}
 Using the currentTarget property of the event object the target node of the event can be
accessed.
 The clientX and clientY given the x and y co-ordinates at the time of event.

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 21 Document Object Modeling

5.6.3 Examples
In this section we will make use of DOM2 event model for registering the event. Note that we
have used two different functions for the same event.
Note that this feature is not supported by Internet Explorer. Hence we must see the output on
some another web browser. I have used Mozilla Firefox web browser.

Ex. 5.6.1 : Write a Javascript for validating name and date.


Sol. : JavaScript [EventReg.html]
<!DOCTYPE html>
<html>
<head>
<title>Demo of Event Registration</title>
<script type="text/javascript">
function chkDt(event) Accessing the text box
{ created for entering the
var inputstr =event.currentTarget; name using the
var str=inputstr.value; event.currentTarget
if(str.match(/\d{1,2}:\d{1,2}:\d{4}/))
{
a=str.split(":");
var dd=Number(a[0]);
var mm=Number(a[1]);
var yy=Number(a[2]);
if(mm==1||mm==01)
{
if(dd>=30)
{
alert("Invalid date,Please re-enter it(February have 28 or 29 days)");
inputstr.focus();
inputstr.select();
}
else
alert("Valid Date");
}
else if(mm==0||mm==2||mm==4||mm==6||mm==7||mm==9||mm==11)
{
if(dd>31)
{
alert("Invalid date,Please re-enter it");
inputstr.focus();
inputstr.select();
}
else

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 22 Document Object Modeling

alert("Valid Date");
}
else if(mm==3||mm==5||mm==8||mm==10)
{
if(dd>30)
{
alert("Invalid date,Please re-enter it");
inputstr.focus();
inputstr.select();
}
else
alert("Valid Date");
}
}
else
{
alert("invalid Input format!!,Please try again");
inputstr.focus();
inputstr.select();
}

}
function chkName(event) Accessing the text box created
{ for entering the name using the
var inputstr =event.currentTarget; event.currentTarget
var str=inputstr.value;
if(str.match(/[a-zA-Z]+\s[a-zA-Z]\s[a-zA-Z]+/))
{
a=str.split(" ");
var First_name=a[0];
var Mid_initial=a[1];
var Last_name=a[2];
if(First_name.match(/^[a-zA-Z]{1,15}$/))
{
if(Mid_initial.match(/[a-zA-Z]$/))
{
if(Last_name.match(/^[a-zA-Z]{1,15}$/))
alert("Valid name, now enter date");
else
alert("InValid Last Name");
}
else
alert("InValid Middle name initial");
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 23 Document Object Modeling

else
alert("InValid First name");
}
else
alert("You have entered wrong input");
}
</script>
</head>
<body>
<form id="form1">
<label>Enter Name:
<input type="text" value="" id="Name_chk" />(firstname mid_initial lastname)
</label>
<br/><br/>
<label>Enter date:
<input type="text" value="" id="Dt_chk" />(dd-dd-dddd)
</label>
<br/>
</form>
<script type="text/javascript"> Getting the object
var name_node=document.getElementById("Name_chk"); for each element
var dt_node=document.getElementById("Dt_chk"); and then
dt_node.addEventListener("change",chkDt,false); registering the
name_node.addEventListener("change",chkName,false); event handlers
</script>
</body>
</html>
Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 24 Document Object Modeling

Thus document object model is useful in handling objects and events.

Ex. 5.6.2 : Create a script that repeatedly flashes an image on the screen. Do this by changing the
visibility of the image. Allow users to control the “blink speed”.
AU : May-08, Marks 8
Sol. : Blinking.html
<html>
<head>
<script type="text/javascript">
function GetSpeed()
{
var input_str=prompt("Enter the speed value here:","");
var i=Number(input_str);
blinkImage(i);
}
function blinkImage(i)
{

if(!document.getElementById('blink').style.visibility)
{
document.getElementById('blink').style.visibility="visible"
}
if(document.getElementById('blink').style.visibility=="visible")
{
document.getElementById('blink').style.visibility="hidden";
}
else
{
document.getElementById('blink').style.visibility="visible";
}

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 25 Document Object Modeling

j=i;
timer=setTimeout("blinkImage(j)",i);
}
function stoptimer()
{
clearTimeout(timer);
}
</script>
<title>Image Blinking Demo</title>
</head>
<body onload="GetSpeed()">
<img src="flower1.gif" id="blink" style="visibility:hidden" >
</body>
</html>

Ex. 5.6.3 : Develop a DHTML page to change the background color using mouse over event on
three squares containing different colors.
AU : Dec.-08, Marks 2
Sol. : backgroundcolor.html
<html>
<head>
<script type="text/javascript">
function changeColor(color)
{
document.getElementById('B').style.background=color;
}
</script>
</head>
<body id="B">
<p>Move mouse over the color strips</p>
<p> </p>
<table width="50%">
<tr>
<td bgcolor="red" onmouseover="changeColor('red')"
onmouseout="changeColor('transparent')">RED</td>
<td bgcolor="yellow" onmouseover="changeColor('yellow')"
onmouseout="changeColor('transparent')">YELLOW</td>
<td bgcolor="aqua" onmouseover="changeColor('aqua')"
onmouseout="changeColor('transparent')">AQUA</td>
</tr>
</table>
</body>
</html>

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 26 Document Object Modeling

Output

Ex. 5.6.4 : Write a DHTML to shake the window of a button click. Make use of two buttons one
button used to start the shaking and another button used to stop the shaking of window.
AU : Dec.-08, Marks 10
Sol. : shake button.html
<head>
<script language="JavaScript1.2">
function shake(n)
{
if(parent.moveBy)
{
for (i = 100; i > 0; i--)
{
for (j = n; j > 0; j--)
{
parent.moveBy(0,i);
parent.moveBy(i,0);
parent.moveBy(0,-i);
parent.moveBy(-i,0);
}
}
}
}
function Stop_Shake(obj)
{
parent.moveBy=0;
obj.style.left=0;
obj.style.top=0;
}
</script>
</head>
<body>
<center>
<form>
<input type="button" onClick="Stop_Shake(this)" value="Stop">
<input type="button" onClick="shake(100)" value="Shake">
TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 27 Document Object Modeling

</form>
</center>
</ form>

</body>

Ex.5.6.5 : Write a DHTML to change the background colour of a button , Mouse over three
colored table cells and the background color will change. AU : Dec.-08, Marks 10
Sol. : buttoncolor.html
<html>
<head>
<script type="text/javascript">
function changeColor(color)
{
document.getElementById('MyButton').style.background=color;
}
</script>
</head>
<body>
<p>Move mouse over the color strips</p>
<p> </p>
<table width="50%">
<tr>
<td bgcolor="red" onmouseover="changeColor('red')">RED</td>
<td bgcolor="yellow" onmouseover="changeColor('yellow')">YELLOW</td>
<td bgcolor="aqua" onmouseover="changeColor('aqua')">AQUA</td>
</tr>
</table>
<form>
<input id="MyButton" type="button" value="Changing Color of Button">
</form>
</body>
</html>

Output

TM
Technical Publications - An up thrust for knowledge
Web Technology 5 - 28 Document Object Modeling

Ex.5.6.6 : Write a JavaScript for displaying the context menu. The context menu is one that is
shown when user right clicks anywhere in the document.
Sol. :
test1.html
<div id="ContxtMenu"
style="width:150px;border:1px solid black;background
color:yellow;visibility:hidden;position:absolute;line-height:30px; padding-left: 10px">
<a href="http://www.google.com">Search Engine</a><br />
<a href="http://www.facebook.com">Social Networking</a><br />
<a href="http://www.gmail.com">Email Service</a><br / >
</div>

<script type="text/javascript">
var browserObj=document.getElementById && !document.all
var visibility=0

function Display(e)
{
el=document.getElementById("ContxtMenu")
visibility=1
if (browserObj)
{
el.style.left=pageXOffset+e.clientX+"px"
el.style.top=pageYOffset+e.clientY+"px"
el.style.visibility="visible"
e.preventDefault()
return false
}

function Hide()
{
if (typeof el!="undefined" && visibility)
{
el.style.visibility="hidden"
visibility=0
}
}
if (browserObj)
{
document.addEventListener("contextmenu", Display, true)
document.addEventListener("click", Hide, true)
}
</script>

TM
Technical Publications - An up thrust for knowledge

You might also like