Unit 1 & 2 Web Design - MGT
Unit 1 & 2 Web Design - MGT
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
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.
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
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.
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
(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
TM
Technical Publications - An up thrust for knowledge
Web Technology 1-6 Web Site Basics
<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
(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 -
<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 -
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.
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 10 Web Site Basics
This software sends the HTTP request to the server and then processes the HTTP response.
TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 11 Web Site Basics
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.
University Question
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
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
University Questions
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.
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.
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 1 - 19 Web Site Basics
Ans. :
2. The number of users of internet are The number of users of intranet are limited.
unlimited.
4. Internet contains large number of Internet can be accessed from the intranet but
intranets. with restrictions.
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
University Question
1. List the two differences between HTML and XHTML with respect to elements.
AU : Dec.-11, Marks 4
It contains rich text. The rich text means text with tags.
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.
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.
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.
XHTML document.
3. XHTML 1.0 Frameset : When want to make use of frames in the XHTML document.
University Question
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.
Following HTML document along with its output is itself self explanatory.
2.5.2 Paragraphs
Following are the tags that are used for creating paragraphs
Tag Meaning
<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.
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 10 HTML
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
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.
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
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 –
’ apostrophes '
© copyright ©
Another type of entity reference that is used frequently is 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  .
HTML Document[SpaceDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Space Demo</title>
</head>
<body>
<h3>
Method 1:
</h3>
<p>
Jony Jony Yes Papa  Eating
sugar no Papa Open Your
mouth 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>
</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
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 <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 -
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.
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 22 HTML
University Question
1. How are audio files played through HTML? Explain with an example.
AU : Dec.-09, Marks 2
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.
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
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.
…
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 26 HTML
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 28 HTML
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
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>
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>
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 33 HTML
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> </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"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center">2</td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center">3</td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
</table>
</body>
</html>
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 35 HTML
Output
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> </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
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
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
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
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 .
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
*
rows pixels It specifies the number and size
% of rows in a frameset.
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
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.
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
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
Attribute Description
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>
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.
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
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
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.
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. :
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 62 HTML
Output
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>
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.
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 67 HTML
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.
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.
TM
Technical Publications - An up thrust for knowledge
Web Technology 2 - 69 HTML
Ans. :
Special Character Entity Reference Meaning
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. :
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
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
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
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
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
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 -
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
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
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>
Here is the HTML document which makes use of such generic selector.
</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
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
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
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.
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
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}
</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
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")
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
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.
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 20 CSS
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.
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 23 CSS
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.
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.
cursive Zapf-chancery
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 27 CSS
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.
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
Value Meaning
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>
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
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
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
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 34 CSS
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 36 CSS
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
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
3.9 Color
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.
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
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
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>
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.
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.
XHTML document[DisplayDemo.html]
<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
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 52 CSS
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
</style>
</head>
<body>
<p>Taj Mahal is one of the wonders of the World. It is located in
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.
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
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
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.
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
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.
TM
Technical Publications - An up thrust for knowledge
Web Technology 3 - 63 CSS
<style>
h2 {
text-shadow: -5px 15px 3px gray;
}
</style>
</head>
<body>
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
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.
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
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
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
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
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. 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
TM
Technical Publications - An up thrust for knowledge
Web Technology 4-4 Client Side Scripting
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
…
…
</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.
TM
Technical Publications - An up thrust for knowledge
Web Technology 4-6 Client Side Scripting
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
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.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
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
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
== Equal to x==100
|| Or operator 0 ||1
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.
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 ‘
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>”);
There are three types of popup boxes used in JavaScript by which user can interact with the
browser.
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 12 Client Side Scripting
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
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
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
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
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
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
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.
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
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
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
Sol. :
<html>
<head>
<title>PALINDROME CHECK</title>
<script type="text/javascript">
function palindrome(str)
{
var len = str.length;
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
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>
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)
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
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.
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);
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>
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
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.
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.
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 54 Client Side Scripting
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
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.
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.
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
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.
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
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
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 61 Client Side Scripting
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
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> </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
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
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
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 74 Client Side Scripting
Output
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 75 Client Side Scripting
<br/><br/>
    <input type="button" value="Evaluate" onclick=Compute()>
<br/><br/>
<b>Answer is: </b><br/><input type="text" name="ans">
</form>
</body>
</html>
Output
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
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)
{
TM
Technical Publications - An up thrust for knowledge
Web Technology 4 - 79 Client Side Scripting
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.
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
parseInt This function parses the string and returns the integer
value.
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.
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
TM
Technical Publications - An up thrust for knowledge
Unit III
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
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.
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.
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
University Questions
TM
Technical Publications - An up thrust for knowledge
Web Technology 5-4 Document Object Modeling
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.
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
<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>
<!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
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
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
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
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
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 blur,change,abort,error,focus,load,reset,resize,select,scroll,unload,submit
In DOM0 the connection between event and event handler is simple. But in DOM2 the event
model is complicated one.
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
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
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
…
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.
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
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