0% found this document useful (0 votes)
151 views119 pages

MCAWT Unit1

Hey, are you trying to extract a zip or rar or archive file, but don’t know how it’s do that no problem we are here to solve your problem. before we go ahead make sure you have a zip or rar or archive file which you want to extract. if you don’ have then please download it.

Uploaded by

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

MCAWT Unit1

Hey, are you trying to extract a zip or rar or archive file, but don’t know how it’s do that no problem we are here to solve your problem. before we go ahead make sure you have a zip or rar or archive file which you want to extract. if you don’ have then please download it.

Uploaded by

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

WEB TECHNOLOGIES

1
UNIT- I
History of HTML , WWW and INTERNET:

The primary scripting language for developing web pages is Hyper Text Markup
Language(HTML). It is used to describe how a web page will appear in a browser’s
window. HTML allows us to write formatting instructions for web pages. Web browsers
interpret the formatting instructions for web pages and present the webpage on the
screen.

HTML provides simple mechanisms for formatting text, creating links and lists,
inserting images, embedding audio and video etc. It can also include Cascading Style
Sheets(CSS) to specify the style and layout of text and other components. Scripts
written in various languages such as JavaScript and VBScript may also be used to
change the appearance of web pages and make them interactive.

The first public version HTML specification was introduced in 1991 by Berners-
Lee. In November 1994,HTML version 2.0 was introduced by Internet Engineering Task
Force(IETF).In this version several features such as forms, tables and image maps
were added. The World Wide Web Consortium (W3C) published HTML3.2 in 1997.In
the same year W3C published HTML4.0.In 1999,W3C published HTML4.01.

World Wide Web:

Tim Berners-Lee, a British scientist at CERN, invented the World Wide Web
(WWW) in 1989. The web was originally conceived and developed to meet the demand
for automatic information-sharing between scientists in universities and institutes around
the world.

WWW is a system of interlinked hypertext documents accessed via the Internet.


The World Wide Web, or simply Web, is a way of accessing information over the
medium of the Internet. It is an information-sharing model that is built on top of the
Internet. The Web uses the HTTP protocol, only one of the languages spoken over the
Internet, to transmit data. Web services, which use HTTP to allow applications to
communicate in order to exchange business logic, use the Web to share information.
The Web also utilizes browsers, such as Internet Explorer or Firefox, to access Web
documents called Web pages that are linked to each other via hyperlinks. Web
documents also contain graphics, sounds, text and video.

The Web is one of the services that runs on the Internet. It is a collection of
textual documents and other resources, linked by hyperlinks and URLs, transmitted by
web browsers and web servers. The Web is just one of the ways that information can be
disseminated over the Internet, so the Web is just a portion of the Internet. In short, the
Web can be thought of as an application "running" on the Internet.

INTERNET : The Internet is a network of interconnected computer networks that use


the TCP/IP protocol suite to link several devices world wide.

Internet is a short form of the technical term internetwork, the result of


interconnecting computer networks with special gateways or routers. The Internet is

2
also often referred to as the Net. The Internet is a massive network of networks, a
networking infrastructure. It connects millions of computers together globally, forming a
network in which any computer can communicate with any other computer as long as
they are both connected to the Internet. Information that travels over the Internet does
so via a variety of languages known as protocols.

Web Page : A Web page is a document created using HTML. A web page is a
document or information resource that is suitable for the World Wide Web and can be
accessed through a web browser and displayed on a monitor or mobile device. This
information is usually in HTML or XHTML format, and may provide navigation to other
web pages via hypertext links. Web pages may be retrieved from a local computer or
from a remote web server. The web server may restrict access only to a private
network, e.g. a corporate intranet, or it may publish pages on the World Wide Web. Web
pages are requested and served from web servers using Hypertext Transfer Protocol
(HTTP).

Website : A website or simply site, is a collection of related web pages containing


images, videos or other digital assets. A website is hosted on at least one web server,
accessible via a network such as the Internet or a private local area network through an
Internet address known as a Uniform Resource Locator. All publicly accessible websites
collectively constitute the World Wide Web. Web sites can be static or dynamic.

Static Website: A static website is one that has web pages stored on the server in the
format that is sent to a client web browser. It is primarily coded in Hypertext Markup
Language, HTML.

Dynamic Website: A dynamic website is one that changes or customizes itself


frequently and automatically, based on certain criteria

• Web pages and sites can be stored on the hard drive of a local computer or a
Web server on the Internet. Ex: Apache, IIS
• A Web browser is a program that displays the Web pages it retrieves. Popular
browsers include Microsoft Internet Explorer, Netscape Navigator, Mozilla,
Google chrome etc..

What is Hypertext?

Hypertext provides the links between different documents and different document
types. In a hypertext document, links from one place in the document to another are
included with the text. By selecting a link, you are able to jump immediately to another
part of the document or even to a different document. In the WWW, links can go not
only from one document to another, but from one computer to another.

Retrieving Data from the Web :

We can retrieve data by using the address of the file. That address is called
Uniform Resource Locator (URL). The address box of the browser shows the
currently displayed document. We can type a URL into the address box can get the file
we wanted.

3
Structure of URLs:

Each host computer(WEB SERVER) has unique IP address, every data File or
document on the Internet also has a unique address called a URL (Uniform Resource
Locator).

The URL consists of three parts:

• The Protocol
• The Domain name (Webserver name)
• The Path.

Eg: http://www.linccweb.org/eresources.asp

Protocol domain name path

The Protocol is a set of rules or an agreement that specifies a common


language that computers on a network use for communication with other computers.

Ex: HTTP -:Hyper Text Transfer Protocol


FTP - File Transfer Protocol
SMTP - Simple Mail Transfer Protocol
TCP/IP – Transmission Control Protocol/Internet Protocol

HTTP:

• Hypertext Transfer Protocol (HTTP) is the communication protocol used by the Internet
to transfer hypertext documents.
• A protocol to transfer hypertext requests and information between servers and browsers
• Hypertext is text, displayed on a computer, with references (hyperlinks) to other text that
the reader can immediately follow, usually by a mouse HTTP is behind every request for
a web document or graph, every click of a hypertext link, and every submission of a
form.
• HTTP specifies how clients request data, and how servers respond to these requests.
• The client makes a request for a given page and the server is responsible for finding it
and returning it to the client.
• The browser connects and requests a page from the server.
• The server reads the page from the file system and sends it to the client and then
terminates the connection

4
FTP:

File Transfer Protocol (FTP) provides a method for transferring files over a network from
one computer to another. More generally, it provides for some simple file management
on the contents of a remote computer. It is an old protocol and is used less than it was
before the World Wide Web came along. Today, its primary use is uploading files to a
Web site. Sites that have a lot of downloading will often have an FTP server to handle
the traffic. If FTP is involved, the URL will have ftp: at the front.

The File Transfer Protocol is used to send files from one system to another under user
commands. Both text and binary files are accommodated and the protocol provides
features for controlling user access. When a user wishes to engage in File transfer, FTP
sets up a TCP connection to the target system for the exchange of control messages.
These allow used ID and password to be transmitted and allow the user to specify the
file and file action desired. Once file transfer is approved, a second TCP connection is
set up for data transfer. The file is transferred over the data connection, without the
overhead of headers, or control information at the application level. When the transfer is
complete, the control connection is used to signal the completion and to accept new file
transfer commands.

TCP/IP :

Transmission control protocol/Internet protocol is a set of rules (protocols) governing


communications among all computers on the Internet. TCP/IP was developed
in 1978 and driven by Bob Kahn and Vint Cerf. Transmission control protocol (TCP):
5
Controls disassembly of message into packets at the origin reassembles at the
destination Internet protocol (IP):Specifies the addressing details for each packet Each
packet is labeled with its origin and destination.

There are four total layers of TCP/IP protocol, listed below with a brief description.

Network Access Layer - This layer is concerned with building packets.

Internet Layer - This layer uses IP (Internet Protocol) to describe how packets are to be
delivered.

Transport Layer - This layer utilizes UDP (User Datagram Protocol)


and TCP(Transmission Control Protocol) to ensure the proper transmission of data.

Application Layer - This layer deals with application network processes. These
processes include FTP (File Transfer Protocol), HTTP (Hypertext Transfer Protocol),
and SMTP (Simple Mail Transfer Protocol).

SMTP

SMTP stands for Simple Mail Transfer Protocol. It was first proposed in 1982. It is a
standard protocol used for sending e-mail efficiently and reliably over the internet.

Key Points:
• SMTP is application level protocol. SMTP is connection oriented protocol. SMTP is
text based protocol.
• It handles exchange of messages between e-mail servers over TCP/IP network.
Apart from transferring e-mail, SMPT also provides notification regarding incoming
mail.
• When you send e-mail, your e-mail client sends it to your e-mail server which further
contacts the recipient mail server using SMTP client.
• These SMTP commands specify the sender’s and receiver’s e-mail address, along
with the message to be send.
• The exchange of commands between servers is carried out without intervention of
any user.

6
• In case, message cannot be delivered, an error report is sent to the sender which
makes SMTP a reliable protocol.

Style vs. Format:

Format allow you to change format of a given text using tags and its attributes.

The Style is a group of formatting commands which can be applied to any text.
Style refers to CSS styles. One paragraph can have both a "style" and a "format"
associated with it.

What is HTML?

• HTML is a language for describing web pages.HTML stands for Hyper Text
Markup Language.HTML is not a programming language, it is a markup
language .A markup language is a set of markup tags.The purpose of the tags is
to describe page content.

Features of HTML:

1) It is a very easy and simple language. It can be easily understood and modified.
2) It is very easy to make effective presentation with HTML because it has a lot
of formatting tags.
3) It is a markup language so it provides a flexible way to design web pages along with
the text.
4) It facilitates programmers to add link on the web pages (by html anchor tag) , so it
enhances the interest of browsing of the user.
5) It is platform-independent because it can be displayed on any platform like Windows,
Linux and Macintosh etc.
6) It facilitates the programmer to add Graphics, Videos, and Sound to the web pages
which makes it more attractive and interactive.

7
What is HTML Document?

• HTML documents describe WebPages. HTML documents contain HTML tags


and plain text. HTML documents are also called “WebPages”.

The purpose of a web browser like Internet Explorer or Firefox is to read


HTML documents and displays them as WebPages. the browser does not display the
HTML tags. But uses the tags to interpret (or) translate the content of the page.

Editing HTML:

• Text editor like notepad used to write HTML source code.


• Notepad is available in:
Start→programs→accessories→notepad
(or)
Start→run→notepad
• All HTML files have either the .html or .htm as file extensions

HTML Tags & Attributes:

Tag or element: An HTML tag is a format name surrounded by angle brackets.

< tag name >.

About HTML Tags

1. Tags are delimited by angled brackets.


2. They are not case sensitive.
3. Styles must be switched off by an end tag.
4. Some characters have to be replaced in the text by escape sequences.
5. White space, tabs and newlines are ignored by the browser.
6. If the browser does not understand a tag it will usually ignore it.

What are attributes?


Attributes are used to describe information for a particular element.
Syntax: <element attribute1=value attribute2=value ----- ->

HTML Elements

An element consists of three essential pieces: an opening tag, the content, and
a closing tag.
Eg:
<h1> This is first heading </h1>

8
<p>This is a paragraph.</p>

Explain the STRUCTURE of HTML Document ?

<html>
<head>
<title>--------------</title> <! - - This is Sample Document structure - ->
</head>
<body>
------------------- <! - - This is Sample HTML Document.-- ->
</body>
</html>
Explanation: The entire document is surrounded by <html> …. </html> which tell the
software that it is now processing html.
Document Head: <head>…..</head>
• Head section contains control information to be used by browser, server and body.
The <head> element can contain other HTML tags that contain metadata.
• Metadata provides information about the document such as title, description,
keywords etc. A typical HTML document might contain a <title> tag, one or
more <meta> tags, a <script> tag, and a <style> tag - all enclosed within
the <head> element.
• Most metadata are not displayed in the browser (although the title usually appears in
the browser's title bar) but it can be useful for the functionality of the page.

The Document Body :<body> ...</body>


This is where you will begin writing your content for web document. Documents are
structured as blocks of text. Formatting tags are used here to format these blocks.

9
HTML comments:
<! -- --> : Comments can be inserted into the HTML code to make it more readable and
understandable. Comments are ignored by the browser and are not displayed. They are
simply there for the programmer's benefit. Comments can be placed in either head or
body of your document.
Eg:
<html>
<head>
<! - - this is the single line comment - - >
<title> welcome </title>
</head>
<body>
<! - - This is document body --
- -This is multi line comment - - >
</body>
</html>

Explain body tag and its attributes?


Body tag :
The body is the second part of every HTML document. The text and html code that
goes between the <body> and </body> tags is rendered and displayed in the document
area of the browser’s window.

Attributes:
Attribute Description
Bgcolor=rgb(or)colorname background color of the webpage
Background=url background picture for the webpage
Text=RGB(or)colorname color of the text on the webpage
Link= RGB (or)colorname color of the unvisited links
Vlink= RGB (or)colorname color of the visited links
Alink= RGB (or)colorname color of the active links

Ex.
<body bgcolor=”pink” background=”Sunset.jpg” link=”#FF0000”
vlink=”#00FF00” alink=”#0000FF”>
Adding colors:
HTML colors are defined using a hexadecimal notation (HEX) for the combination
of Red, Green, and Blue color values (RGB).

10
R(red) G(Green) B(Blue)
00 00 00
33 33 33
66 66 66
99 99 99
CC CC CC
FF FF FF

To create RGB number from the above values,simply select one number from each
column. For example choose FF from the red column,00 from the green column,00
from the blue column to create RGB number FF0000,which has pure bright red.

Ex:
To specify the background color for your document ,include the bgcolor=”#….”attribute
in the opening body tag like this:
<body bgcolor=”#FF0000”>

HTML Paragraphs
Paragraphs are defined with the <p> tag.
Syntax :< p> Welcome to Guntur </p>
Attribute: align= left (default) | right | center
Eg:
<html>
<body>
<p align=”right”>This is a paragraph.</p>
<p align=”center”>This is a paragraph.</p>
<p>This is a paragraph.</p>
</body></html>

HTML Line Breaks:


Use the < br > tag if you want a line break (a new line) without starting a new
paragraph. The <br> tag is used to force line breaks within text. Normally, line breaks
are treated as a space by browsers. This <br> has no ending tag(ie,</br>).
Eg: <html> <body>
<p>This is<br>a Para<br><br>graph with line breaks</p>
</body></html>

HTML Headings:
Page headings are created with the <h1>, <h2>,<h3>,<h4>,<h5>,<h6> tags.
Syntax: <h i> sairam </h i> i.e i=1,2,3,4,5,6
11
Attribute: align=left(default) | right | center
<h1> defines the Largest size heading.
<h6> defines the smallest size heading.

Eg: HTML program to display different sizes of heading.


<html>
<head>
<title>Headings Demo</title>
</head>
<body>
<h1 align=”center”>This is heading 1</h1> size is 2em or 32px
<h2 align=”center”>This is heading 2</h2> size is 1.5em or 24px
<h3 align=”center”>This is heading 3</h3> size is 1.17em or 18.72px
<h4 align=”center”>This is heading 4</h4> size is 1em or 16px
<h5 align=”center”>This is heading 5</h5> size is 0.83em or 13.28px
<h6 align=”center”>This is heading 6</h6> size is 0.67em or 10.72px
</body>
</html>

HTML <hr> Tag (Horizontal Ruler)


The <hr> tag creates a horizontal line in an HTML page. The <hr> element can
be used to separate content in an HTML page.
ATTRIBUTES:
Attribute Description

Size=n Specifies the rule height

Width= n% Specifies the rule width

Align=left |right |center Specifies the alignment.

noshade Specifies the rule has no shading

Color=RGB(or)colorname Specifies the color to the line

Eg:
Illustrate the horizontal rulers in your page

<html>
<body bgcolor=green>
<hr> <br><br>
<hr align=right width=60% size=5>welcome</hr> <br>
<br> <br>
<hr width=70% size=7 color=”green”> </hr>
<br> <br>

12
<hr width=30% height=300 noshade></hr>
</body>
</html>

HTML Text Formatting Tags:


The page content in the body of the webpage can be presented in a neat way using
different text formatting tags. These tags are used to individual letters or words.
Tag Description

<b> Defines bold text

<u> Defines underline

<i> Defines italic text

<big> Defines big text

<small> Defines small text

<em> Defines emphasized text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<pre> writes text exactly as it is, including spaces.

<strike> strikes a line through the text

<marquee> Displays scrolling text in a marquee style

Escape sequences used in text formatting are

Name Escape Sequence Result


Copyright &copy; ©
Trademark &reg; ®
Non breaking space &nbsp; It provides one blank space
Less than &lt; <
Greater than &gt; >
Ampersand &amp; &
trademark &trade; ™

quotations &quot; “

13
Write a HTML program illustrating text formatting tags.

<html>
<head>
<title> Second Program </title>
</head>

<body>

<h3>Text Formatting Tags</h3>


<p>
<b>This text is bold</b> <br>
<u>This text underlined </u> <br>
<i> Welcome </i>
<strike> Striked text </strike>
<marquee> J.K.C.College </marquee>
<i>This text is italic</i> <br>
<em>This text is emphasized</em> <br>
<tt> Type writer Text </tt>
This is<sub> subscript</sub> and <sup>superscript</sup> <br>

<pre> this is predefined format

J.K.C. College “
* * * </pre>
<tt>This is type writer text </tt> <br>
</p>
<h3>Escape Sequences</h3>
<p>Less than &lt; <br> greater Than &gt;<br> Ampersand &amp;<br> Quotations
&quot;<br> Non breakable space &nbsp;<br>CopyRigh t &copy; </p>
</body>
</html>

<font> Tag:
The FONT tag is used to change the style of a specific text.This tag contains
various attributes like face,color and size.

ATTRIBUTES:
Attribute Description
size=n Size of your text, n takes values 1 to 7
color=rgb colorcode (or) colorname Indicates color of the text
face="name of font" Indicates type of font

14
Eg:
Illustrate font variations in your HTML code.
<html>
<head>
<title> Second Program </title>
</head>
<body bgcolor="#ffcc88">
<font face=”Arial” size=”1” color=”blue”>JKCCOLLEGE</font><br>
<font face=”Times New Roman” size=”2” color=”green”> JKCCOLLEGE </font>
<br>
<font face=”Verdana” size=”3” color=”violet”> JKCCOLLEGE </font><br>
<font face=”Symbol” size=”4” color=”red”> JKCCOLLEGE </font> <br>
<font face=”Calibri” size=”5” color=”yellow”> JKCCOLLEGE </font> <br>
<font face=”Algerian” size=”+1” color=”pink”> JKCCOLLEGE </font><br>
<font face=”impact” size=”-1” color=”cyan”> JKCCOLLEGE </font> <br>
</body>
</html>

To set the default font style, color etc we use the <basefont> tag.

<basefont face=”Arial” size=”2” color=”red”>

Embedding Images (or) <img> Tag :


An image is placed in HTML document using the standalone <img> tag. The attribute
src indicates the URL of the image file. If the image file located in the same directory of
the html document, only the name of the image file may be specified. The browser
inserts the image where <img> tag occur in the document.

<img src=URL alt=text border=n width=n height=n align=left|center|right>


Eg: <img src=”D:\abc.jpg” width=300 height=300 >
ATTRIBUTES:
Attribute Description

alt=”text” Specifies an alternate text for an image

src=URL Specifies the location of an image

Border=n Specifies the border for image

Width=n Specifies the width of the image

Height=n Specifies the height of the image

Align= left | right | center Specifies the align of the image

15
Two types of image files are commonly used:

---> .GIF - short for Graphics Interchange Format and pronounced jiff or giff (hard g);
---> .JPEG - short for Joint Photographic Experts Group and pronounced jay-peg.
GIF supports color and various resolutions. It also includes data compression,
making it especially effective for scanned photos.
JPEG is a lossy compression technique (data compression technique in which
unnecessary information is eliminated) for color images.

Eg1:

<html><body>
<img src="Tulips.jpg" alt="There is no image" width="100" height="100" border=2
align=right>
</body> </html>

Eg2:
<html> <head>
title>welcome</title>
</head>
<body background=”Desert.jpg”>
<p>this is our college </p>
</body></html>

Creating image maps in HTML using <map> and <area> tags :

We can create an image with clickable area which can be of specific shape, using
<map> and <area> tags. The image is inserted using the <img> tag. The only difference
from other images is that you must add a usemap attribute.

The usemap value starts with a hash tag # followed by the name of the image map, and
is used to create a relationship between the image and the image map.

name attribute value in <map> tag and usemap attribute value in <img> tag should be
same.
The <area> tag is used to create clickable area with shapes.
The <map> can have more than one <area> tag.

Syntax
<img usemap="#mapname" src="imagePath">

<map name="mapname">
<area shape="shapeName" coords="coordinatePoint" href="htmlPath">
<area shape="shapeName" coords="coordinatePoint" href="htmlPath">
</map>

coords and shape


shape - rect or rectangle, square,circle,poly or polygon.

16
For rect or square shape: The values is x1,y1 and x2,y2. Using these two points and
joining them a rectangular or square shape is formed.

circle value for shape attribute : For a circle shape, the value is x,y,r.
x and y is specifying the center of the circle, it will decide where to move the
circle. r is specifying the value for the radius.

poly value for shape attribute : For a poly or polygon shape, the value is a set
of x,y pairs for each point. This can be unlimited numbers of pairs of points.
Every points are connected and create the shapes.

Ex:
Try to click on the computer, phone, or the cup of coffee in the image.

Here is the HTML source code for the image map above:

<img src="workplace.jpg" alt="no image map" usemap="#workmap">

<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer“ href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone“ href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>

Anchor tag (or) Hyperlink (<a>):


The HTML anchor element is used to create a link to a resource (another web
page, a file, etc.) or to a specific place within a web page.
The anchor tag is written like this <a href=URL>--------------</a>

17
Anchor tag attributes:
Attribute description
HREF=URL URL you are linking to
NAME=”text” name a section of the page
TARGET = "_blank" | "_parent" | "_self" which window the document should be
| "_top" | window name displayed.

The HREF Attribute:


The href attribute is used to specify the address of documents or services at
other internet sites, address of document within the sane website or address of a
specific part of either the current page or another page.
External Linking: External links are useful to navigate another webpage or website from
the current webpage. Here the URL address is the webpage address.
<a href="abc.html">google</a>

Absolute vs. Relative URLs:

There is a link in our example: http://www.google.com . The is an example of


an absolute URL. Absolute URLs are those that include a complete (absolute)
description of the link destination. Absolute URLs include the protocol (http) and the
complete domain name and file path needed to reach the destination anchor.
The second is an example of a relative URL. Relative URLs link to a web page by
describing the position of the page relative to the position of the current page. When
writing internal links that point to other pages of the same website we have the option of
writing relative URLs rather than absolute URLs.
For example, if we are at this address: http://example.com/products/red-product/, and
we want to link to the blue product page, we can use either of the following anchor
elements:

<a href="/products/blue-product/">Go check out the blue product!</a>


<a href="../blue-product/">Go check out the blue product!</a>

The NAME Attribute (used for Internal linking):


The name attribute allows an anchor tag to be used to point to a specific place on
a web page. You might link from the bottom of a long page to the top of the page, or link
from an item in a Table of Contents to the corresponding item where it appears on the
page.
The syntax for using the name attribute is like this:

18
<a name="chap1"></a>
To link to that named anchor you'd code your link like this:
<a href="#chap1">Table of Contents</a>

The TARGET Attribute:


The target attribute allows you to determine where the link will open.
Value Description

Target=_blank Opens the linked document in a new window or tab

Target=_self Opens the linked document in the same frame as it was


clicked (this is default)

Target=_parent Opens the linked document in the parent frame

Target=_top Opens the linked document in the full body of the window

Target=window name Opens the linked document in a named frame


Eg
<html><body>
<p> This is a link to <a href="http://www.google.com/">Google</a>.</p>
<p> This is a link to our <a href="abc.html">HTML reference</a>.</p>
</body></html>
Internal Linking :
HTML has facilitates to include internal LINKS ALSO BY ASSIGNING A
LOCATION NAME TO ANY individual point in an HTML document. This location name
can be added to the page URL. For internal linking also , the anchor tag is used. To
create name the following tag is used.

The Anchor Tag and the Name Attribute

The name attribute is used to create a named anchor. When using named anchors we
can create links that can jump directly into a specific section on a page, instead of
letting the user scroll around to find what looking for.

Below is the syntax of a named anchor:

<a name="label">Text to be displayed</a>

The name attribute is used to create a named anchor. The name of the anchor
can be any text .

The line below defines a named anchor:


Ex.

19
<a name="chap1">Useful Tips Section</a>

3. Prepare a sample code to illustrate links between different sections of a


page. (Internal linking)

<html>
<head>
<title> Internal Linking </title>
</head>
<body>
<h1 align=center >MY BOOK </h1>
<p> My book contains the following chapters </p> <br>
<a href="#chap1">1. Introduction </a><br>
<a href="#chap2">2. Topic 1 </a><br>
<a href="#chap3">3. Topic 2 </a><br>

<a name = "chap1"></a>


<h3 align = "center"> Chapter 1</h3>
<p> The text here <br>
The text here <br>
The text here <br>
The text here </p>

<a name = "chap2"></a>


<h3 align = "center"> Chapter 2</h3>
<p> The text here <br>
The text here <br>
The text here <br>
The text here </p>

<a name = "chap3"></a>


<h3 align = "center"> Chapter 3</h3>
<p> The text here <br>
The text here <br>
The text here <br>
The text here <br> </p>
</body>
</html>

Explain different types of LISTS in HTML?:


A List is a collection of one or more items. Html supports 3 types of Lists for formatting
Text.
. They are
1. Ordered list.
2. Unordered list.
3. Definition list.

20
1.ORDERED LISTS:
In an ordered list the elements are prefixed by a number in the list. The beginning
and ending tags of the ordered list are <ol>and </ol>. The items in the list begins with
<li>tag. Ending tag for item </li> in the list is optional.
Tags:
Tag Description

<ol> Defines an ordered list

<li> Defines a list item

<OL> ATTRIBUTES:
Attribute Description
Type=A|a|I|i|1 Specifies the number(or letter)with which the list
should start A,a,I,i,1(default)
Start Specifies the number to start at

List Items <li>


The li element defines a list item. The element must be contained
within OL or UL.

The end tag </li> may be omitted.

Eg:<html><body>
<h4>Numbered list:</h4>
<ol start=5>
<li>Apples</li>
<li>Bananas</li>
<li>Oranges</li>
</ol>

2.UNORDERED LISTS:
If the order is not important we can use the unordered list. the unordered list of
items starts with <ul> and ends with </ul>. The items inside <ul>tag are created using
<li> tag and are displayed using bullets.

Tags:
Tag Description

21
<ul> Defines an unordered list

<li> Defines a list item

<UL> ATTIBUTE:
Attribute Description
"disc" Specifies the style of bullets preceding list items.
TYPE= "circle"
"square" • disc - a filled-in circle;
o circle - a circle outline;
▪ square - a square;

Eg : <html><body>
<h4>An Unordered List:</h4>
<ul type=square>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

3.Definition Lists:
A definition list is one where list items consists of two parts: a term and its
description. It is created using <dl>. The term part and the definition part of each item
are created using <dt> Definition term and <dd> Definition Description tags
respectively.
Tags:
Tag Description

<dl> Defines a definition list

<dt> Defines an item in a definition list

<dd> Defines a description of an item in a definition list

Eg:
<html><body>
<h4>A Definition List:</h4>
<dl>
<dt>HTML</dt>
<dd>Hyper Text Markup Language</dd>
<dt>WWW</dt>
<dd>World Wide Web</dd>
</dl>
</body>
</html>
22
NESTED LISTS:
Nested lists may be used to display sub elements of an item. Any of the three
types of lists may be nested in another.
Eg:<html><body>
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ol>
<li>Black tea</li>
<li>Green tea </li>
</ol>
</ul>
</body>
</html>

4) Create a simple HTML program to illustrate three types of lists.

<html>
<head>
<title> Types of Lists </title>
</head>
<body bgcolor="yellow">
<h1 align="center"> Lists </h1>
<br>
<h2 align="center"> Unordered Lists </h2>

<h3> B.Sc </h3>


<ul type = "circle" >
<li> Computers </li>
<li> Physics </li>
<li> Electronics </li>
</ul>
<br>
<h2 align="center"> Ordered Lists </h2>
<br>
<h3> Groups </h3>
<ol type="i">
<li> B.Sc </li>
<li> B.Com </li>
<li> B.A </li>
</ol>
<br>
<h2 align="center"> Definition Lists</h2>
<br>
<dl>
<dt> Our College </dt>
23
<dd> Provides the above specified groups with different
combinations.</dd>
</dl>
</body>
</html>

TABLES:
Tables are way to arrange content on webpage. Tables are made up of rows and
columns create individual cells that can contain either text or image. Tables serve two
functions. They help present complex data in readable format. We can use tables to
incorporate sophisticated design elements into WebPages.

TAG USE
<table> Marks a table with in an HTML document.
<tr> Marks a row with in a table.
<td> Marks a cell with in a row. The closing tag is optional
<th> Marks a heading cell with in a row. The closing tag is optional.

Note: <tr> Table Row, <td> Table data(or)cell data, <th> Table heading.

Adding captions to table:


A caption is explanatory or descriptive text that usually appears above the table. A
caption serves two purposes:
• To summarize table contents
• To provide at-a-glance information about table contents

<caption>: used within a table to identify the text of the table caption
<caption> tag Attributes: Align=top|bottom places the caption at the top or bottom of
the table.

<TABLE> tag ATTRIBUTES:


Attribute Description
Border=n size of border around the table
Cellpadding=n space between the edge of a cell and the contents
Cellspacing=n space between cells
Width=n px width of the table as a whole
Height=n px height of the table as a whole

24
Bgcolor=RGB(or)colorname color of the background
Background=URL picture to use as background
Bordercolor=RGB(or)colorname color of border around the table
Align=left|right alignment of table to surrounding text
Hspace=n horizontal space between table and surrounding text
Vspace=n vertical space between table and surrounding text
Rules=none|all|cols|rows|groups if there should be internal borders

<td> Attributes:
Attribute Description
Align=left|center|middle|right horizontal alignment of cell contents
Valign=top|middle|center|bottom|baseline vertical alignment of cell contents
Width=n width of cell
Height=n height of cell
Colspan=n number of columns to cover
Rowspan=n number of rows to cover
Bgcolor=RGB(or)colorname color of the background
Background=URL of image color of border around the table
Bordercolor=RGB(or)colorname color of border around the table

<tr> ATTRIBUTES:
Attribute Description
Align=left|center|right horizontal alignment of cell contents
Valign=top|middle|bottom|baseline vertical alignment of cell contents
Bgcolor= RGB(or)colorname color of the background
Background=URL of image color of border around the table
Bordercolor= RGB(or)colorname color of border around the table

Eg:
<html>
<body>
<table border="1" bgcolor=blue cellspacing=4 cellpadding=5 >
<caption>Monthly savings</caption>

<tr bgcolor=yellow>
<th>Month</th>

25
<th>Savings</th>
</tr>

<tr>
<td>January</td>
<td>$100</td> output
</tr>
Monthly savings
<tr> Month Savings
<td>February</td> January $100
<td>$50</td>
February $50
</tr>

</table>

</body>
</html>

7. Create nested table to store your curriculum

<html>
<head> <title> Curriculum </title> </head>
<body>
<h1> BIODATA </h1>
<pre >
Sai Mailid : [email protected]
Contact No : 93333333

</pre>
<hr align="left" width="60%" size="5"> <br>

<table border="2">
<caption align="left"><h3> Details:</h3></caption>

<tr> <th> Name</th> <td> Sai</td> </tr>


<tr> <th> Qualification</th> <td> M.Sc (Computers) </td> </tr>
<tr> <th align="center" colspan="2"><b><i> Acadamic Details:</b></i></td></tr>
<tr>

<td colspan="2" align="center">


<table border="1">
<tr> <th> Qualification</th> <th> School/College</th> <th> University</th> <th>
Percentage</th> /tr>

<tr> <td>10<sup>th</sup></td> <td>Nirmala</td> <td>S.S.C Board</td> <td> 8%</td>


</tr>

<tr> <td>Intermediate</td> <td> B.A. & K </td> <td> Board of Intermediate</td> <td>
72%</td> </tr>
26
<tr> <td>B.Sc(Computers)</td> <td> kc college </td><td>Andhra University </td> td>
74%</td> </tr>
</td>
</tr>
</table>

<tr> <th colspan=2><b><i> Personal Details:</b></i></th>


</tr> <td> Name</td> <td> Sai</td> </tr>
<tr rowspan=3> <td valign=center> Address</td> <td valign=middle> H.No. 1-2-
56<br> Guntur <br> Guntur(Dist) </td></tr>
<tr> <td> Maritial Status</td> <td> No</td> </tr>
<tr> <td > Contact Number</td> <td > 99999999</td> </tr>
<br>

</table>
<pre>
The above mentioned details are genuine. If there are any disputes occur in the said
details, i will take the responsibility.
Sai
</pre>

</body>
</html>
Tables using images :
We can place images in a table by using <img> tag in <td> tag.
<table width="500px" height="100%" border="1">
<tr><td><img src="filename.jpg" alt="description here" ></td>
<td> This text is in the table data cell on the right. </td>
</tr>
</table>

Multimedia Objects

Multimedia comes in many different formats. It can be almost anything you can
hear or see like text, pictures, music, sound, videos, records, films, animations, and
more.
On the Internet you can often find multimedia elements embedded in web pages,
and modern web browsers have support for a number of multimedia formats.

Multimedia Formats
Multimedia elements also have their own file formats for video with different
extensions like .swf, .wmv, and .mp4.
Multimedia elements also have their own file formats for audio with different
extensions like .mid, .wav, .wma, .mp3.
Object:
27
The <object> tag defines an embedded object within an HTML document. Use
this element to embed multimedia (like audio, video, Java applets, ActiveX, PDF, and
Flash) in your web pages.

Attributes:

Attribute Value Description


left
right
align Defines visual alignment of the object
top
bottom
border pixels Specifies border width around the object
data URL Specifies the URL for Object data.
height pixels Specifies the hight of the object.
hspace pixels Specifies the horizontal space around the object.
name object name Specifies a unique name for the object
type mime type Defines the MIME type of data specified in the data attribute.
vspace pixels Specifies the vertical space around the object.
width pixels Specifies the width of the object.
classid classid number Defines a class ID value as set in the Windows Registry or a URL.

Ex: audio:
<html><body>
<object height="100" width="100" data="horse.mp3"></object>
<p>If you cannot hear the sound, your computer or browser doesn't support the sound
format.</p>
<p>Or, you have your speakers turned off.</p>
</body></html>
Ex:vedio:
<html><body>
<object height="200" width="200" data="intro.swf"></object></body> </html>

FRAMES
The HTML frame is a powerful feature that enables a web page to be broken into
different unique sections that are related but can be operated independently without
depending on each other.

Advantages (Pros) of using Frames:


• One of the most beneficial feature of frames is it lets the user to have multiple pages
in the same browser.
28
• Using frames we can keep one part of the page static while changing the other
parts of the page.
• If we create a top frame we can use it as a header i.e, as that page is static it acts
like an include page.
• Frames can be used to reduce server load, as there is no need to reload all the
pages whenever a new page is visited.

Disadvantages (Cons) of using Frames:


• One of the main disadvantages of frames is search engines will not deal with them
properly. i.e, search engines will not index pages containing frames as its hard for
them to search for a specific content and move backwards to check to which
frameset each page belongs to and retrieve all the pages in the frameset.
• It’s hard to navigate through pages in frames when we have more than two or three
frames.
• It’s difficult to print the content of all frames when compared to a normal web page.
• Some browsers doesn't support frames, so we need to place the content separately
for the people who doesn't have frames using <noframes> ... </noframes>

Frameset: The splitting of a browser screen into frames can be done by using
<Frameset> and </Frameset> tags.
<Frameset>attributes:
ATTIBUTE DESCRIPTION
rows=n Specifies the number of rows and their height in pixels,
percentages, or relative lengths. Default is 100%
cols=n Specifies the number of columns and their width in
pixels, percentages, or relative lengths. Default is 100%
frameborder= YES | 1 | NO | 0 if the frames should have borders
framespacing=n space between the frames
border=n Specifies the border for frame
bordercolor=RGB(or)colorname color of frame borders

FRAME:
It is Possible to divide the browser window into several individual documents.
Each document is called frame. It is beginning with <frame>tag and ends with</frame>.
Note: Frame tag does not have any closing tag.

Frame tag Attributes:


ATTRIBUTE DESCRIPTION
src=URL Location of the frame contents
Name=”text String” Assigns a name to a frame. This is useful for loading
contents into one frame from another.
Noresize Specifies whether the frame is resizable or not (i.e.
whether the user can resize the frame or not).
29
Scrolling=yes | no |auto Whether the frame should be scrollable or not
frameborder= yes|1 |no | 0 Whether the frame should have a border or not

Marginwidth=size in pixels Specifies the margin, in pixels, between the frame's


contents and its left and right margins.
Marginheight= size in pixels Specifies the margin, in pixels, between the frame's
contents and its top and bottom margins.
Bordercolor=RGB(or)color name color of the surrounding border

<noframe>: The HTML noframes tag is used (in conjunction with the frameset tag) for
specifying alternative content for browsers that don't support frames.

Eg1:
<html>
<head>
<frameset cols="40%,60%" frameborder=1 bordercolor=red>
<frame src="web1.html" name=f1>
<frame src=”web2.html” name=f2>
</frameset>
</head> </html>

Web1.html
<html>
<body>
<h1>heading1</h1>
<h2>heading2</h2>
</body>
</html>

Web2.html
<html>
<body>
<h1>web2</h>
<p>computer is an electronic device it takes certain data as input and process the data
with the help of cpu and gives the result as output</p>
</body> </html>

Nested Framesets:
Frameset with in another frameset is known as nested frameset.

Eg:<html>
<head>
<frameset rows="90%,10%">
<frameset cols="30%,70%">
<frame name="A">
<frame name="B">
</frameset>
<frame name="C">
</frameset>
</head>
30
</html>

HTML Forms

HTML forms are used to collecting information from user and passed data to
server. The form tag is used to create HTML forms. Forms begin with the <form> tag
and end with the </form> tag.

All input elements should go between the <form> and</form> tags. We can
have more than one HTML form in a single page. Do not put one form into another form.

<form> tag has several attributes and important among them is METHOD and
ACTION.
A web form has two parts: the HTML ‘front end’ and a back end form processor. The
HTML front end part handles the presentation while the back end handles the form
submissions (like saving the form submissions, sending emails etc).

The back end form processor script is usually written in languages like PHP, ASP
or Perl.

The image below illustrates the concept:

A visitor visits a web page that contains a form. The web browser displays the HTML
form. The visitor fills in the form and submits. The browser sends the submitted form
data to the web server. A form processor script running on the web server processes
the form data. A response page is sent back to the browser.

The following are the attributes of the form tag:

• action=”Link to the form processor script”


The action attribute points to the server side script (the ‘back end’) that handles the
form submission. Usually, this will be a script (PHP,ASP, Perl) or a CGI program.

31
• method =get|post ( either GET or POST)
The method attribute of <form> tag specifies how to send form-data (the form-data is
sent to the page specified in the action attribute). We can use “get” and “post” as values
of method attribute. When we use get, form-data can be sent as URL variables and
when we use post, form-data are sent as HTTP post.

"get" method:
• This method appends the form-data to the URL in name/value pairs
• There is a limit to how much data you can place in a URL (varies between
browsers), therefore, you cannot be sure that all of the form-data will be correctly
transferred
• Never use the "get" method to pass sensitive information! (password or other
sensitive information will be visible in the browser's address bar)

"post" method:
• This method sends the form-data as an HTTP post transaction
• The "post" method is more robust and secure than "get", and "post" does not have
size limitations

Form elements are:

1. text fields
2. password fields
3. buttons
4. radio buttons
5. check boxes
6. comboboxs and List boxes
7. file
8. textarea etc.

1.Text Field:- A text field is an single-line input area where the user can type in
characters.
Eg: Student number<input type="text" size=20 name="sno">
Attributes:
Attribute Use
Size=n The size option defines the width of the field. That is how many
visible characters it can contain.
Maxlength=n The maxlength option defines the maximum length of the field.
That is how many characters can be entered in the field.
Name=”textString” Name of the field
Value=”textstring” Initial value of this field
Readonly indicates the text field information not modified

Ex: <form> First name: <input type="text" name="firstname" /> </form>


Output:

32
First name:

2.Password Field: - When the user typed the information in a text field it is displayed
as it is. But if you want display encoded characters like * for every type character, you
should go for Password Fields. Creation of Password field is very simple, change value
of Type parameter to "password".

Eg: Enter Password <Input type="password" size= 10 name="pwd">

Attributes:

Attribute Use
Size=n The size option defines the width of the field. That is how
many visible characters it can contain.
Maxlength=n The maxlength option defines the maximum length of the
field. That is how many characters can be entered in the
field.
Name=”string” Name of the field

3. Buttons: There are three types of buttons that you can create in HTML. They are
1.user defined buttons, 2.submit button and 3.reset button.
To create user defined button you can give <Input type="button">, to display text on it,
use Value parameter.
Eg:
<input type=button value="ok">
• Submit button is special kind of button, when the user selects that button, form
action should be invoked.
Eg:
<input type=submit value="submit">
• Other button is Reset button, when it is clicked, clears all entries the user
entered into the form.
Ex:
<input type=reset value=" clear">

• To create these buttons just you specify "submit" or "reset" in type parameter of
Input tag.
Attribute:
Attribute Use
Name=”text string” Name of the field
Value=”text String” Text written on the field

33
4.Radio Buttons:Radio buttons are used to allow a user to select only one option at a
time.So the name should be unique. Using input type="radio" we can place radio button
on the web page. This component allows us to make only one selection at a time.
Eg:
<form>
<input type="radio" name="sex" value="male" />
Male <br />
<input type="radio" name="sex" value="female" />
Female </form>
Output:

Male
Female

Attributes:
attribute Use
Name=”text String” Name of the group
Value=”text string” Value that is submitted if checked
Checked Default check this field.

5.Checkboxes:- Check boxes are used to allow a user to select one or more options
from a set of alternatives.
Eg:
<input type=" checkbox" name=" c1" value="CSE">
<input type="checkbox" name="c2" value="IT">
Attributes:
attribute Use
Name=”text string” Name of the field
Value=”text string” Value that is submitted if checked
Checked Default check this field.

6.Selection List or Drop down list: A selection list is also called as Drop down list,
allows visitors to choose one or more options among the set of options. A selection
list is created using the <select> tag. Items of a selection list are created using the
<option> tag. By default the first option is displayed. The size attribute specifies how
many items are to be displayed.
Ex:
Languages Known
<select size=2>
<option> English
<option> Telugu

34
<option> Hindi
<option> Tamil
<option> Oriya
</select>

Attributes:
Tag/attribute use
name=”text string” Name of the field.
size=n Visible items in the list
<option> Individual items in the menu.
selected Default selects the item.
value=”text string” Value to send if selected.

7.File: - used to include a file with in a form in a web page.


Eg: <input type=file name="fl">
attribute Use
Name=”text string” Name of the field

8. Textarea: - It is used to input multiple-line information from the end user like Address
field.
Eg:
<textarea name=”ta1” cols=25 rows=4> </textarea>
Wrap means specifies the size of the screen for displaying the text.
Attribute Use
rows=n Rows in the field
Cols=n Columns in the field
Name=”text string” Name of the field

Example form:
<html>
<head>
<title>Mailing system</title> </head>
<body>
<h2 align="center">Subscriber Information</h2>
<form>
UserName: <input type="text" maxlength=30 size=15><br>
Enter Password:<input type="password"><br>
Address for correspondence:<br>
<textarea name="b" rows=5 cols=35></textarea><br>
35
Gender: &nbsp;&nbsp; Male <input type="radio" name="gen" value="m">
Female: <input type="radio" name="gen" value="f"><br>
File to upload: <input type="file" value="browse"><br>
Country:
<select name="cou" size=1>
<option>United States</option>
<option>Brazil</option>
<option>Russia</option>
<option selected>India</option>
</select><br>
if u have already account in:<br>
<input type=checkbox name=acc1 checked>yahoo<br>
<input type=checkbox name=acc2 >gmail<br>
<input type=checkbox name=acc2>rediff<br>

<input type="image" src="Desert.jpg" width=50 height=50><br>


<input type="Submit" value="Submit">
<input type="Reset" value="Reset">
</form>
</body>
</html>

DOCTYPE declaration(document type declaration)

36
• The <!DOCTYPE> declaration must be the very first thing in your HTML document,
before the <html> tag.
• The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web
browser about what version of HTML the page is written in.
• In HTML 4.01, the <!DOCTYPE> declaration refers to a DTD, because HTML 4.01
was based on SGML. The DTD specifies the rules for the markup language, so that
the browsers render the content correctly. HTML5 is not based on SGML, and
therefore does not require a reference to a DTD.
Ex: <! Doctype wc3/html4.0 >

Explain Head section in detail ?


The head of the document contains control information to be used by servers and
browsers. The following tags are used in Head section.

1. <title>….</title>
It is used to display the title of the document at the top of the browser window.
Eg: <title> welcome> </title>

2. <base href=”URL” target=”frame_name”>


This tag is used to enforce relative links. But linking between pages and
documents will be implemented using <a> tag in body section. The target
attribute specifies the default frame name to which all links are displayed.
Eg: <base href=http://www.smiggins.com>

3. <link rel=”type” href=”URL” type=”string” media=”string”>


This tag is used to allow other documents to be linked ,or to included in the
current document. This tag has not commonly been used but it is important and useful
when using external stylesheets.
Eg: <link rel=”stylesheet” href=” test1.css” type=”text/css” media=”screen”>

4. <meta> tag:

The <meta> element is used to specify which character set is used, page
description, keywords, author, and other metadata. Metadata is used by
browsers (how to display content), by search engines (keywords), and other
web services.

Ex: Define the character set used <meta charset="UTF-8">

Define a description of your web page:


<meta name="description" content="Free Web tutorials">

Define keywords for search engines:


<meta name="keywords" content="HTML, CSS, XML, JavaScript">

Define the author of a page:


<meta name="author" content="John Doe">

37
Refresh document every 30 seconds:
<meta http-equiv="refresh" content="30">

5. <script> tag :

The HTML <script> tag is used for declaring a script (such as JavaScript) within
your HTML document. This tag can be placed either in head section or in body
section or in both sections.

Ex:
<html>
<head>
<script type="text/javascript">
// JavaScript code here
</script>
</head>
<body> ---- </body> </html>

Applet :
Applet is a java program that can be embedded into HTML pages. Java applets
run on the java enables web browsers such as mozilla and internet explorer. Applet is
designed to run remotely on the client browser, so there are some restrictions on it.
Applets are used to make the web site more dynamic and entertaining.

<applet> tag Attributes:

Attribute Value Description

align Left|right|top Deprecated - Defines the text alignment around the applet
bottom|middle

alt text Alternate text to be displayed in case browser does not


support applet

code URL A URL that points to the class file name of the applet

height pixels Height to display the applet

hspace pixels Deprecated - Defines the left and right spacing around the
applet

name name Defines a unique name for the applet

vspace pixels Deprecated - Amount of white space to be inserted above


and below the object.

width pixels Width to display the applet.

codebase URL A URL that points to the directory or path of the class file.

38
Ex: Lab 6

6. Create an applet that accepts two numbers and perform all the arithmetic operations
on them.

File name : arith.html

<html>
<body>
<applet code="arith.class" width="350" height="350"> </applet>
</body>
</html>

File name: arith.java

import java.applet.*;
public class arith extends Applet
{
public void paint(Graphics g)
{
int a=10,b=20;
int sum=a+b;
int diff=a-b;
int m=a*b;
int d=a/b;
String s=”sum=”+String.valueOf(sum);
String s1=”diff=”+String.valueOf(diff);
String s2=”pro=”+String.valueOf(m);
String s3=”div=”+String.valueOf(d);
g.drawString(s,100,100);
g.drawString(s1,100,150);
g.drawString(s2,100,200);
g.drawString(s3,100,250);
}
}

Lab 5: Embed a Calender Object into your webpage.

<html>
<head>
<title>Calender Object </title>
</head>
<body>
<h1 align=center> Inserting Calender Object </h1>
<object classid="clsid:8E27C92B-1264-101C-8A2F-040224009C02" width=400
height=400 border=2>
</object>
</body>
</html>

Start→run→regedit
39
CSS (Cascading Style Sheet)
DHTML:

Dynamic Hyper Text Markup Language is the name given to the


technique of dynamically changing the rendering content of an HTML code.
HTML is static, because images once defined cannot be changed or
predesigned layout cannot be altered. DHTML web pages react to the user
actions or to the changes. DHTML is not a technology rather it is the
combination of three technologies .

1.Cascading Style Sheets(CSS)


2.Client-side Scripting(Java Script or VB Script)
3.Document Object Model(DOM)

Q1). What is CSS? What are the advantages of CSS?

CSS Definition:

Cascading Style Sheets are styles for organizing the layout of an HTML
document including its color, faces, margins and other formatting
elements.CSS is designed primarily to enable the separation of document
content from document presentation.
Using CSS, we can control the color of the text, the style of fonts, the
spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, layout designs, variations in display
for different devices and screen sizes as well as a variety of other effects.
CSS is easy to learn and understand but it provides powerful control
over the presentation of an HTML document. Most commonly, CSS is
combined with the markup languages HTML or XHTML.

Advantages of CSS:

1. CSS Save time — CSS gives lots of flexibility to set the properties of an element.
You can write CSS once; and then the same code can be applied to the groups of
HTML elements, and can also be reused in multiple HTML pages.

2. Easy maintenance — CSS provide an easy means to update document formatting


and maintain consistency across multiple documents. By making one change to the
website's CSS, elements in all the web pages will be updated automatically.

3. Pages load faster — CSS enable multiple pages to share formatting, and reduce
complexity and repetition in the structural content. It significantly reduces the file
transfer size, which results in a faster page loading.
40
4. Superior styles to HTML — CSS has much wider presentation capabilities than
HTML, so you can give far better look to your HTML pages in comparison to the
HTML presentational elements and attributes.

5. Multiple Device Compatibility — CSS can also allow the HTML document to be
optimized for more than one type of device or media. Using CSS the same HTML
document can be presented in different viewing styles for different rendering devices
such as computer screen, cell phones, printer, etc.

6. Global web standards − Now HTML attributes are being deprecated and it
is being recommended to use CSS. So its a good idea to start using CSS in
all the HTML pages to make them compatible to future browsers.

Disadvantages of CSS :

• Browser compatibility
Browsers have varying levels of compliance with Style Sheets. This means that
some Style Sheet features are supported and some are not supported.

Q2). What is CSS Style (or) CSS Rule :

A style or rule is a set of formatting instructions that can be applied to a piece of text. A
Style Sheet consists of one or more rules that describe how document elements should
be displayed.

Syntax: Selector {property: value; property: value ; - - - - - }

Ex: h1 {color: blue; font-size: 12px ;}

• Selector − A selector is an HTML tag at which a style will be applied. This could
be any tag like <h1> or <table> etc.
• Property - A property is a type of attribute of HTML tag. Put simply, all the
HTML attributes are converted into CSS properties. They could
be color, border etc.
• Value - Values are assigned to properties. For example, color property can have
value either red or #F1F1F1 etc.

CSS Comments:
Comments are used to explain your code. Comments are ignored by browsers.
A CSS comments begins with /* and ends with */ like this:
EX:
/* This a comment */
41
P
{
Text-align: center;
/*this is another comment */
color: green;
}

Q3). Write about different types of selectors in CSS?

Types of selectors:

1. Type selector
2. Grouping
3. Class
4. ID
5. Universal
Type selectors

The most common and easy to understand selectors are type selectors. Type selectors
are tags used to specify styles to any HTML element on a page that matches the
selector, regardless of their position in the document tree.

Example: h1 {color: red; }

This rule represents all <h1> elements will be colored red, regardless of their position in
the document.

Ex:
<html>
<head>
<style type=text/css>
h1 {color:red}
</style>
</head>

<body>
<h1>this will be affected</h1>
<h2>this will be affected</h2>
<h3>this will be affected</h3>
</body>
</html>

Grouping
If multiple selectors share the same CSS properties, they can be declared together.
This is called "grouping". For example, the tags <h1>, <h2>, and <h3> share same
style, they can be declared together as follows:

h1 ,h2, h3 { property:value; }

42
Ex:
<html>
<head>
<style type=text/css>
h1, h2,h3 {color:green}
</style>
</head>
<body>
<h1>this will be affected</h1>
<h2>this will be affected</h2>
<h3>this will be affected</h3>
</body>
</html>

Class selectors (or) Anonymous class:

The class selector is used to specify a style for a group of elements. The
class selector is most often used on several elements. This allows you to set a
particular style for any HTML elements with the same class. The class selector
uses the HTML class attribute, and is defined with a “.”

The syntax for declaring a Class selector is as follows:

.class Name { property:value; ... }

The tree diagram would be:

<html>
<head>
<style type=text/css>
.big {color:yellow; font-weight:bold; }
</style>
</head>
<body>
<p class="big">This is some <em>text</em></p>
<p>This is some text</p>
<ul>
<li class="big">List item</li>
<li>List item</li>
<li>List <em>item</em></li>
</ul>
</body>
</html>

Combining class and type selectors

If you want to be more specific, you can use class and type selectors together. Any type
selectors can be used. This is achieved by using the following syntax:

43
Type Selector.Class Name { property: value; ... }

H1.big { color : yellow; }


Combining multiple classes

Perhaps the most powerful aspect of class selectors is that multiple classes can
be applied to one HTML element. For example, you may wish to use two rules on one
particular element like this:

<html
<head>
<style type=”text/css”>
.big { font-weight: bold; }
.indent { padding-left: 2em; }
</style>
</head>
<body>
<p class="big indent">this will be affected</p>
<p>This will not affect</p>
</body>
</html>

ID selectors
ID selectors are similar to class selectors. The difference is that
1. Each element can have only one ID.
2. Each page can have only one element with that ID.
3. # symbol before the selector name.

The syntax for declaring an ID selector is as follows:

# ID Name { property: value; ... }

Example:

<html>
<head>
<style type=”text/css”>
#abc { width: 12em; color: red; }
</style>
</head>
<body>
<p id="abc">this will be affected</p>
</body>
</html>
Universal selectors
Universal selectors are used to specify styles to any element. For example, the
rule below will color all HTML elements on a page blue - regardless of their position in
the document tree.

Syntax: * {property:value}
44
EX: * {color: blue; }

The document tree would be:


<html>
<head>
<style type=text/css>
* { color: blue; }
</style>
</head>
<body>
<p><em>this will be affected</em></p>
<div><em>this will be affected</em><div>
<h1><em>this will be affected</em></h1>
</body>
</html>

Q4). Explain different ways of adding styles to a webpage ( or) Types


of CSS?

There are three ways to apply a CSS style sheet to an HTML document:

1. Inline Style Sheet (style attribute)


2. Embedded (or) Internal Style Sheet (style tag)
3. External Style Sheet (link tag or import)

1. Inline Style sheet :


In this case the styles can be placed inside the individual tag, it will effect any one
particular tag only. To use inline styles you can use the style attribute in the relevant
tag. The style attribute can contain CSS properties

Example:

<html>
<body>
<p style=”color:red;”> The text color is red. This is example for inline style sheet. </p>
<br>
<p style=”font-family : verdana; color :blue ;”>This text color is blue and font face is
verdana.</p>
</body>
</html>

2. Embedded (internal) Style sheet :


• We can put your CSS rules into an HTML document using the <style> element.
The HTML <style> element contains style information for a document.
• This tag is placed inside <head>...</head> tags.
• Rules defined using this syntax will be applied to all the elements available in the
document body section.

EX:

45
<html>
<head>
<style type="text/css">
p { background-color : yellow; }
h1 { color : maroon; }
</style>
</head>

<body>
<h1> WELCOME </h1>
<p> The background color is red. This is an example for internal style sheet. </p>
</body>
<html>

3. External Style sheet :

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

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

Here is the generic syntax of including external CSS file −

<head>
<link rel: stylesheet type = "text/css" href = "URL"> </link>
</head>

<link> Tag Attributes:


Attribute value Description
type text/css Specifies the style sheet language as a content- type. This
attribute is required
href URL Specifies the style sheet file having style rules. This
attribute is required.
rel stylesheet The required rel attribute specifies the relationship
between the current document and the linked
document/resource.

<html>
<head>
<link rel=stylesheet type="text/css" href="a.css">
</head>

<body>
<p>
The background color is red. This is an example for External style sheet.

46
</p>
</body>

a.css

p { background-color:#FF0000; }
h1,h2 { color: #3645DB; letter-spacing : 1em;}
body { background-color : linen; }

import

Another way to add css to html is by using @import.External CSS declarations


can also be imported into an HTML document. To do so, use the @Import command.
The syntax is:

<STYLE TYPE="text/css">

@import url(filename.css);

</STYLE>

Ex:

<html>
<head>
<style type=text/css>
@import url(a.css);
</style>
</head>

<body>
<p>
The background color is red
</p>
</body>

a.css

p { background-color:#FF0000; }
h1,h2 { color: #3645DB; letter-spacing : 1em;}
body { background-color : linen; }

Q5). What are the Units of measure in Style Sheets ? What is URL ?

CSS supports a number of measurements including absolute units such as


inches, centimeters, points, and so on, as well as relative measures such as

47
percentages and em units. You need these values while specifying various
measurements in your Style rules e.g. border = "1px”.

We have listed out all the CSS Measurement Units along with proper Examples

Unit Description Example

% Defines a measurement as a percentage relative p {font-size: 16pt; line-height: 125%;}


to another value, typically an enclosing element.

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

em A relative measurement for the height of a font


in em spaces. Because an em unit is equivalent
to the size of a given font, if you assign a font to p {letter-spacing: 7em;}
12pt, each "em" unit would be 12pt; thus, 2em
would be 24pt.

ex This value defines a measurement relative to a


font's x-height. The x-height is determined by p {font-size: 24pt; line-height: 3ex;}
the height of the font's lowercase letter x.

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

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

pc Defines a measurement in picas. A pica is


equivalent to 12 points; thus, there are 6 picas p {font-size: 20pc;}
per inch.

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


defined as 1/72nd of an inch.

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

CSS uses color values to specify a color. Typically, these are used to set a
color either for the foreground of an element (i.e., its text) or else for the
background of the element. They can also be used to affect the color of
borders and other decorative effects.
48
You can specify your color values in various formats. Following table lists all
the possible formats −

Format Syntax Example

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

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

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

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

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

CSS Rules Overriding:


We have discussed four ways to include style sheet rules in a an HTML document.
Here is the rule to override any Style Sheet Rule.

• Any inline style sheet takes highest priority. So, it will override any rule defined in
<style>...</style> tags or rules defined in any external style sheet file.

• Any rule defined in <style>...</style> tags will override rules defined in any
external style sheet file.

• Any rule defined in external style sheet file takes lowest priority, and rules
defined in this file will be applied only when above two rules are not applicable.

Q6). Write about Properties and values in styles ?


1. Font Properties:

The font property can set the style, weight, variant, size, line height and font

1. The font-family property is used to change the face of a font.


font-family :Times New Roman, Arial, serif, sans-serif, monospace

2. The font-style property is used to make a font italic or oblique.

49
font-style : normal, italic, oblique

3. The font-variant property is used to create a small-caps effect.


font-variant : normal small-caps

4. The font-weight property is used to increase or decrease how bold or light a


font appears.

font-weight :normal,bold,bolder,lighter,100,200,300,400,500,600

5. The font-size property is used to increase or decrease the size of a font.


font-size : small, medium, large, x-large, or size measurement

6. The font property is used as shorthand to specify a number of other font


properties.

Ex:
<html>
<head>
</head>

<body>

<p style = "font-style:italic; font-variant:small-caps; font-


weight:bolder; font-size:20px;">
This text will be rendered in italic style
</p>
</body>
</html>

2.Text Properties:

Text properties specify the characteristics of text blocks. The following table shows
some of the most common text properties.

1) The color property is used to set the color of a text.


Color : color name
2) The direction property is used to set the text direction either Left to Right or Right
to Left.
direction : ltr,rtl
3) The letter-spacing property is used to add or subtract space between the letters
that make up a word.
letter-spacing : measurement or %
50
4) The word-spacing property is used to add or subtract space between the words of
a sentence.
word-spacing : measurement

5) The text-indent property is used to indent the text of a paragraph.


text-indent :measurement or %

6) The text-align property is used to align the text of a document.


text-align : left, right, center, justify

7) The text-decoration property is used to underline, overline, and strikethrough


text.
text-decoration : none, underline, overline, line-through, blink
8) The text-transform property is used to capitalize text or convert text to uppercase
or lowercase letters.
text-transform :none, capitalize, uppercase, lowercase

Ex:
<html>
<head>
</head>

<body>

<p style = "color:red; direction:rtl; letter-spacing:5px; word-


spacing:5px; text-indent:1cm;">
This text will be written in red.
</p>
</body>
</html>

3.Background Properties:

To establish background properties for the sample document or for any block-level
elements, use the properties and values shown in the following table.

1) The background-color property is used to set the background color of an element.


background-color : #rrggbb, transparent

2) The background-image property is used to set the background image of an


element.
background-image :url(tulips.jpg)
51
3) The background-repeat property is used to control the repetition of an image in
the background.
background-repeat : repeat-x, repeat-y,no-repeat
4) The background-position property is used to control the position of an image in
the background.
background-position : right top, right bottom, left top, left bottom

5) The background property is used as a shorthand to specify a number of


other background properties.
Ex:

<html>
<head>
<style>
body {
background-image: url("abc.jpg");
background-repeat: repeat-x;
}
</style>
</head>

<body>
<p> Background properties example</p>
</body>
</html>

4. Box Properties:

To create a box, apply these box-level characteristics to existing text in an HTML


document, including, for example, paragraphs, block quotes, or headings.
Property Value

margin-top measurement,%
margin-right measurement,%
margin-bottom measurement,%
margin-left measurement,%
margin measurement,%
border-width measurement,thick,medium,thin
border-color #rrggbb
border-style none, dotted, dashed, solid, double, groove, ridge, inset,
outset
width measurement or %
height measurement or %

Ex:
52
<html>
<head>
<style>
p { margin: 15px; border:1px; border-style: dotted; border-color:green; }
</style>
</head>
<body>

<p>Here, some CSS properties are applied to this paragraph </p>

</body>
</html>

Q7). Explain Formatting Blocks of Information? or Explain SPAN and


DIV tags?

To format blocks of information <div> and <span> tags are used

Divisions:

The <div> tag defines a division or section in an HTML document.The <div> tag is often
used to group block of elements to format them with styles. Any formatting that needs
adding styles is placed inside the <div>---</div> pair of tags.

Syntax:

<div class=”classname” | id=”….” | style=”….”>


Some tags
</div>

Spans:

The <span> tag is used to for grouping and applying styles to inline elements in a document.
<span> tag is similar to <div> in that they both divide the content into individual sections.

Syntax:
<span class=”…..”| id= “……” | style=”…….”> some text </span>

The primary difference between a div and a span is their default behavior. By default, a <div> is
a block-level-element and a <span> is an inline element. In other words, if you want to adjust a
small portion of text and not break it out of the current line, you should use a <span>. If you
need to modify a large division, the height, move an element, or contain other elements, you
should use a <div>.

Example:

53
<html>
<head>
<style type="text/css">
.abc { color:red; background-color:green; text-transform:uppercase; }
.jkc { color:blue; background-color:black; text-transform:lowercase; }
</style>
</head>
<body>
<div class="abc">

<p>
Welcome to formatting blocks of information.<span style = "color: red;”> hello
</span>This is a
paragraph.<br> See the difference between span and div.
</p>
</div>

<div class="jkc">
<p>
Welcome to formatting blocks of information.<span style = "color:green;”> hello
</span>This is a
paragraph. See the difference between span and div.
</p>
</div>

</body>
</html>

Q8). Write about Layers ?

• CSS gives opportunity to create layers of various divisions. The CSS layers refer to
applying the z-index property to elements that overlap with each other.
• To create layers all we need to do is assign the position attribute to our style. The position
can be either absolute or relative.
• The position itself is defined with the top and left properties.

There are a few variables that need to be defined

1. position: absolute | relative:

Absolute:
An element with position: absolute is positioned at the specified coordinates
relative to your screen top-left corner.
You can use two values top and left along with the position property to move an HTML
element anywhere in the HTML document.
• Move Left - Use a negative value for left.
• Move Right - Use a positive value for left.
• Move Up - Use a negative value for top.
• Move Down - Use a positive value for top.

54
Relative:
If you define the position: relative, it will be relative to the position of the tag that
carries the style. (i.e. one after other) .That is, if you add a relatively positioned layer in
the middle of the page, then the position will be calculated from that exact spot in the
middle of your page where it was added.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
2. Left: n, top: n
The location of the division in pixels. You locate divisions around the screen by
specifying the position of their top-left corner. These parameters are optional and both
default value is 0, 0.

3. Z-index: n
The z-index property is used along with the position property to create an effect of
layers. You can specify which element should come on top and which element should
come at bottom. CSS Z-index property is used to layer elements in front or behind each
other. This is referred to the stack level.

Example:

<html>
<head>
<style type="text/css">
.abc { z-index:1; position:absolute; top:200; left:200; }
.jkc { z-index:2; position:absolute; top:250; left:250; }
.sai { z-index:3; position:absolute; top:300; left:300; }
</style>
</head>

<body>
<div class="abc">
<img src="Sunset.jpg" width=300 height=300>
</div>

<div class="jkc">
<img src="Winter.jpg" width=300 height=300>
</div>

<div class="sai">
<img src="Blue hills.jpg" width=300 height=300>
</div>

</body>
</html>

Write the html program including the style sheets.

<html>
55
<head>
<link rel=stylesheet type="text/css" href="a.css">
<style type="text/css">
h1 { color : red; }
</style>
</head>

<body>
<! - - This is inlinel style sheet - - >
<p style=”color : geen;”> The text color is red </p>

<! - - This is internal style sheet - - >


<h1> Welcome </h1>

<! - - This is external style sheet - - >


<h2> Welcome </h2>
<p> This document contains three types of style sheets.</p>
</body>
</html>

a.css

p { background-color:#FF0000; }
h2 { color: #3645DB; letter-spacing : 1em;}

INTRODUCTION TO JAVASCRIPT
JavaScript is a scripting language used for client side scripting developed by
Netscape Communications Corp in 1995 as a method for validating forms and providing
interactive content to web site.
Are Java and JavaScript the same?
NO!
Difference between Java and JavaScript:
Java and JavaScript are programming languages. Java is purely
object oriented programming language where as JavaScript is a scripting language.
Both can be used to make web pages more interactive. However, java is also used to
develop server side applications and standalone programming.
Following are some points which differentiate java & JavaScript
• Java follows strong type checking where as JavaScript is very flexible in data
type (loosely typed).

• Variables in java declared as datatype varname;

Ex: int sum;


But in java script variable declaration will be as var varname;
Ex: var sum;
• JavaScript support function declarations, but without access specifiers,
parameter data type, return type.

• JavaScript:

56
function funname(str)
{
…..Function body…..
}
• Java:

public int function funname(int n)


{
…..function body…..
}

Benefits or advantages of JavaScript:

The following are the benefits of JavaScript:


• It is widely supported in Web browsers.
• It gives easy access to the document objects and can manipulate most of them.
• Java script can give interesting animations without the long download times
associated with multimedia.
• Web surfers don’t need a special plug-in to use your scripts.
• Java script is relatively secure.
Disadvantages of JavaScript:
• Developer depends on the browser support for the JavaScript.

• Complex scripts can take a long time to start up.

• JavaScript cannot write to files on the server without the help of a server side
script.

• JavaScript cannot access databases

How to put a JavaScript into an HTML page:


To insert a JavaScript into an HTML page, we use the html <script> and
</script> tags. Inside the <script> and </script> tag we use the type attribute to define
the scripting language.
So, the <script type=”text/javascript”> and </script> tells where the javascript starts
and ends.

Syntax:
<script type=”text/javascript”>
…………….
…………….
</script>

The document.write() is a standard JavaScript statement for writing output to a page.


By entering the document.write() statement between the <script> and </script> tags,
the browser will recognize it as a JavaScript statement and execute the code line.
The example below shows how to use JavaScript to write text on a web page:
57
Example:
<html>
<body>
<script type="text/javascript">
document.write("Welcome to jkc college!");
</script>
</body>
</html>
The example below shows how to add HTML tags to the JavaScript:
Example:
<html>
<body>
<script type="text/javascript">
document.write("<h1>welcome to jkc college!</h1>");
document.write("<br>");
document.write("<h1>welcome to III B.Sc F1</h1>");
</script>
</body>
</html>
Note: If we had not entered the <script> tag, the browser would have treated the
document.write("welcome to Jkc College!") command as pure text, and just write the
entire line on the page.

Case Sensitivity:
JavaScript is a case-sensitive language. This means that language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
So identifiers jkc, Jkc and JKC will have different meanings in JavaScript.
JavaScript Comments:
Comments can be added to explain the JavaScript, or to make the code more readable.
Comments are ignored by the browser and they are only for programmer benefit.

1.Single line comments start with //.

The following example uses single line comments to explain the code:

2. JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.

Example:
<html>
<head>
</head>
<body>
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
58
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
//document.write("<p>This is another paragraph.</p>");
</script>
</body>
</html>

Where to Put the JavaScript:

JavaScript’s in a page will be executed immediately while the page loads into the
browser. This is not always what we want. Sometimes we want to execute a script when
a page loads, other times when a user triggers an event.
The following most preferred ways to include JavaScript in your HTML file are:
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in external file and then include in <head>...</head> section.
JavaScript in <head>...</head> section:
Scripts to be executed when they are called, or when an event is triggered,
go in the head section.
If you want to have a script run on some event, such as when a user clicks somewhere,
then you will place that script in the head section.

Example:
<html>
<head>
<script type="text/javascript">
function message()
{
document.write("Javascript is a client-side scripting language”);
}
</script>
</head>
<body onload="message()">
</body>
</html>
JavaScript in <body>...</body> section:
Scripts to be executed when the page loads go in the body section.
If you need a script to run as the page loads so that the script generates content in the
page, the script goes in the <body> portion of the document. In this case you would not
have any function defined using JavaScript.

Example:
<html>

59
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>

Scripts in <head> - -</head> and <body>- -</body> sections:


You can place an unlimited number of scripts in your document, so you can have scripts
in both the body and the head section.
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>
</html>

JavaScript’s in the body section will be executed while the page loads.
JavaScript’s in the head section will be executed when called.

Example:
<html>
<head>
<script language="javascript">
function bsc()
{
document.write("MSCs"+"<br>");
document.write("MPCs"+"<br>");
document.write("MECs"+"<br>");
}
function bcom()
{
document.write("Bcom(computers)"+"<br>");
document.write("Bcom(general"+"<br>");
}
</script>
</head>
<body>
<script>
bsc();
bcom();
</script>
</body>
</html>

60
Using an External JavaScript
If you want to run the same JavaScript on several pages, without having to write
the same script on every page, you can write a JavaScript in an external file. Save the
external JavaScript file with a .js file extension.
Note: The external script cannot contain the <script> tag! To use the external script,
point to the .js file in the "src" attribute of the <script> tag:
Syntax:
<html>
<head>
<script type="text/javascript" src=”filename.js”>
</script>
</head>
<body>
</body>
</html>

Example:
sai.js

function message()
{
document.write("MSCs"+"<br>");
document.write("MPCs"+"<br>");
document.write("MECs"+"<br>");
document.write("Bcom(computers)"+"<br>");
document.write("Bcom(general"+"<br>");
}

Jkc.html
<html>
<head>
<script type="text/javascript" src="sai.js">
</script>
</head>
<body onload="message()">
</body>
</html>

Data types in JavaScript

Programming languages usually have several different types of data.


Commonly programmers may use characters, integers (whole numbers), Booleans
(logical values of true or false), strings (collection of characters), reals (complex
numbers), and many other types. But JavaScript can process only four types of data:

• Numeric : These are basic numbers. They can be integers such as 22 and 1000
or floating point values 23.34 and 2e45. You don’t need to differentiate between
them as you declare and use them. You don’t enclose them in quotation marks.
The numbers can be either positive or negative. Eg: var a=22;
61
• Strings : Collection of characters enclosed in quotation marks. Strings can have
spaces and digits. Eg: var a=”rama”;

• Boolean- used to evaluate whether a condition is satisfied or not. Boolean


variables hold values true and false.

• Null : It is an empty value. A null value means not yet decided. It does not mean
nil or zero.

JavaScript variables:

Variables in JavaScript behave the same as variables in most popular


programming languages do, but in JavaScript you don't have to declare variables before
you use them. Variables are declared in JavaScript with the var keyword as follows:
Syntax: var variablename;

Example:
<script language="javascript">
var a=10;
var b="jkc":
</script>

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

<script language="javascript">
var a=10,b=20.2,c="jkc";
</script>

Storing a value in a variable is called variable initialization. You can do variable


initialization at the time of variable creation or at that time when you need that variable
to use.

<script language="javascript">
function bsc()
{
var a=10;
var b=20.113;
var c='h';
document.write(a+"<br>");
document.write(b+"<br>");
document.write(c+"<br>");
d="jkc";
document.write(d+"<br>");
}
</script>

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

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

JavaScript Variable Scope:


The scope of a variable is the region of your program in which it is defined. JavaScript
variable will have only two scopes.
• Global Variables: A global variable has global scope which means it is defined
everywhere in your JavaScript code.
• Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the same
name as a global variable, you effectively hide the global variable.
Example:
<html>
<head>
<script type="text/javascript">
var a = "20"; //Declare a global variable
function checkscope( )
{
var a = "10";//Declare a local variable
document.write(a);
}
</script>
</head>
<body>
<script language="javascript">
checkscope();
</script>
</body>
</html>

Rules for JavaScript Variable Names:


While naming your variables in JavaScript keep following rules in mind.
• You should not use any of the JavaScript reserved keyword as variable name.
For example, break or boolean variable names are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must begin
with a letter or the underscore character. For example, 123test is an invalid
variable name but _123test is a valid one.
• JavaScript variable names are case sensitive. For example, Name and name are
two different variables.
63
JavaScript Reserved Words or Keywords:
The following are reserved words in JavaScript. They cannot be used as JavaScript
variables, functions, methods, loop labels, or any object names.

abstract else instanceof switch


boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super

Write a program to add two numbers in javascript.

parseInt(): parseInt() is a function used to convert string into an integer.


parseFloat(): parseFloat() is a function used to convert string into an floating value.
Example:
<html>
<head>
<title>parseInt and parseFloat example</title>
</head>
<body>
<script language="javascript">
var a=parseInt(window.prompt("enter value into a","0"));
var b=parseInt(window.prompt("enter value into b","0"));
c=a+b;
document.writeln("c="+c);
</script>
</body>
</html>

JavaScript Operators:
Operator is a Symbol which takes one or more operands and operates on them to
produce a result.
JavaScript language supports following type of operators:
• Assignment operator (=)
• Arithmetic operators (+,-,*, /, %)
• Relational operators (>,>=, <. <=, ==, !=, ===)
• Logical operators (&&, ||,!)
64
• Increment and Decrement operator(++,--)
• Conditional operator (? :)
• typeof operator

1. Assignment Operator:
The assignment operator is used to assign the value to a variable.

Example: a=10; a+=2; a-=10;

2. Arithmetic Operators:
The arithmetic operators are used to perform all arithmetic operations such
as addition, subtraction, multiplication, division, and modulo division.
There are following arithmetic operators supported by JavaScript language:
Assume variable A= 5 and variable B= 2
Operator Description Example
+ Addition A + B will give 7
- Subtraction A - B will give 3
* Multiplication A * B will give 10
/ Division B / A will give 2.5
% Modulus Division (remainder of a division) B % A will give 1

Note: The + operator can also be used to add string variables or text together.

Ex1: “jkc”+”college”=jkccollege.

Ex2: “jkc”+”123”=jkc123

3.Relational Operators:

The relational operators are used to check the relation between two values.

There are following relational operators supported by javascript language is:


Assume variable A = 2 and variable B = 5
Operator Description Example
Checks if the value of two operands is equal or
== (A == B) is not true.
not, if yes then condition becomes true.
Checks if the value of two operands is equal or
!= not, if values are not equal then condition (A != B) is true.
becomes true.
Checks if the value of left operand is greater
> than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then condition (A < B) is true.
becomes true.
Checks if the value of left operand is greater
>= (A >= B) is not true.
than or equal to the value of right operand, if
65
yes then condition becomes true.
Checks if the value of left operand is less than
<= or equal to the value of right operand, if yes (A <= B) is true.
then condition becomes true.
Checks if the value of two operands is equal to
=== and is of the same type, if yes then condition (A===B) is false
becomes true.

• Logical Operators:
The logical operators are used to combine two or more relational expressions.
There are following logical operators supported by JavaScript language
Assume variable A =10 and variable B =20
Operator Description Example
Called Logical AND operator. If both the
&& operands are true then only the condition (A > B)&&(A< B) is false.
becomes true.
Called Logical OR Operator. If any of the one
|| operand is true then only the condition (A > B)||(A<B) is true.
becomes true.
Called Logical NOT Operator. If a condition is
! !(A<B) is false.
true then Logical NOT operator will make false.

5. Increment and Decrement operator: (++,--):


1. Increment operator:
It is indicated with ++. It is used to increase the value of the variable
by one. It is classified into two types. They are:
• Pre increment:
In pre-increment the value is incremented first and then the value will be
assigned.
Syntax: ++operand;
• Post increment:
In post-increment the value is assigned first and then the value is
incremented.
Syntax: operand++;
2. Decrement operator:
It is indicated with --. It is used to decrease the value of the variable
by one. It is classified into two types. They are:
• Pre decrement:
In pre-decrement the value is decremented first and then the value will be
assigned.
Syntax: --operand;

66
• Post decrement:
In post-decrement the value is assigned first and then the value is
decremented.
Syntax: operand--;

• Conditional operator (? :)
The conditional operator is also known as ternary operator. This first
evaluates an expression for a true or false value and then execute one of the two given
statements depending upon the result of the evaluation.
Syntax: (test-condition)? statement1:statement2;
In this first test-condition is evaluated, if it is true then the statement1 is executed
otherwise statement2 is executed.
• typeof operator:
The typeof is a unary operator. It is used to specify the type of the data the
operand must contain.
Syntax: typeof (operand);
Here is the list of return values for the typeof Operator:

Type String Returned by typeof


Number "number"
String "string"
Boolean "Boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"

Example:
<html>
<head>
<title>Increment and Decrement Operators</title>
</head>
<body>
<script language="javascript">
var a=12;
var b=76.54;
var c="sita";
var d=null;
var e=true;
function jkc ()
{
a=10;
b=20;
c=a+b;
67
}
document.write(typeof (a) +"<br>");
document.write(typeof (b) +"<br>");
document.write(typeof(c) +"<br>");
document.write(typeof (d) +"<br>");
document.write(typeof (e) +"<br>");
document.write(typeof (jkc) +"<br>");
</script>
</body>
</html>

Output:
number
number
string
object
boolean
function
STRING MANIPULATIONS
Strings in JavaScript are actually objects with a bunch of properties and functions (also
called methods) that can be accessed. The String object is used to manipulate a stored
piece of text.
String Object Properties:

• constructor: The constructor property returns the function that created the
string object's prototype.
Syntax: string.constructor
• length: The length property returns the number of characters that are in a string.
Syntax: string.length

String object methods:

1. toLowerCase():
a. The toLowerCase() method converts a string to lowercase letters.
Syntax: string.toLowerCase()
2. toUpperCase():
a. The toUpperCase() method converts a string to uppercase letters.
Syntax: string.toUpperCase()
3. concat():
a. The concat() method is used to join two or more strings. This method
does not change the existing strings, but returns a new string containing
the text of the joined strings.
Syntax: string.concat(string1, string2, ..., string x)
4. charAt():
a. The charAt() method returns the character at the specified index in a
string.The index of the first character is 0, the second character is 1, and
so on.

68
Syntax: string.charAt(index)

5. indexOf():
a. The indexOf() method returns the position of the first occurrence of a
specified character in a string.This method returns -1 if the value to
search for never occurs.
Syntax: string.indexOf(searchcharacter)

6. lastIndexOf():
a. This function does same as indexOf() but works from backwards along the
string.

7. substr():
i. The substr() method extracts parts of a string, beginning at the
character at the specified
ii. position to rest of the string.
Syntax: string.substr(index,n)
8. substring():

a. The substring() method extracts the characters from a string, between


two specified indices, and returns the new sub string.This method
extracts the characters in a string between "from" and "to", not including
"to" itself.
Syntax: string.substring(index1, index2)

9. replace(regexp,replacetext):
a. This function searches and replaces the regular expression portion(match)
or specified value with the replaced text.
Syntax: string.replace(searchvalue,newvalue)

10. split(separator):
The split() method is used to split a string into an array of substrings, and returns
the new array.
Syntax: string.split(separator)
Example:
<html><head>
<script language="javascript">
var s1="jagaRlamudi";
var s2="kuppuswamy";
var s3="choudary#coll.ege#guntur";
var s4="college";
document.write("<br>"+s1.toLowerCase());
document.write("<br>"+s2.toUpperCase());
document.write("<br>"+s1.replace('a','s'));
document.write("<br>"+s1.charAt(4));
document.write("<br>"+s2.concat(s1));
document.write("<br>"+s1.substring(4));
document.write("<br>"+s1.substring(6,17));

69
document.write("<br>"+s4.indexOf('e'));
document.write("<br>"+s4.length);
document.write("<br>"+s3.split("."));
</script>
</head> </html>

Output:
jagarlamudi
KUPPUSWAMY
jsgaRlamudi
R
kuppuswamyjagaRlamudi
Rlamudi
amudi
4
7
choudary#coll,ege#guntur

Mathematical Functions
The Math object allows you to perform mathematical tasks or calculations.
The Math object provides you properties and methods for mathematical constants and
functions.
Math Object Properties:

• Math.PI : This returns 3.14


Syntax: Math.PI
• Math.E : Euler’s Constant 2.718

• Math.LN2 : Log of 2.

• Math.LN10 ; Log of 10.

• Math.SQRT_2 : The square root of 2.

• Math.SQRT1_2 : The square root of ½.

Math Object Methods:

• Math.abs():

The abs() method returns the absolute value of a number.

Syntax: Math.abs(n)

2.Math.ceil():

The ceil() method returns the smallest integer greater than or equal to a number.
Syntax: Math.ceil(n)
70
3.Math.floor():

This floor() method returns the largest integer less than or equal to a number
Syntax: Math.floor(n)

4.Math.round():

This method returns the value of a number rounded to the nearest integer.

Syntax: Math.round(n)

5.Math.max():

The max() method returns the number with the highest value. If no arguments are
given, the results is -Infinity

Syntax: Math.max(n1, n2, n3….)

6.Math.min():

The min() method returns the number with the lowest value. If no arguments are
given, the results is -Infinity

Syntax: Math.min(n1, n2, n3….)

7.Math.pow():

The pow() method returns the value of x to the power of y (xy).


Syntax: Math.pow(x, y)

8.Math.random():

The random() method returns a random number from 0 (inclusive) up to but not
including 1 (exclusive).
Syntax: Math.random()

9.Math.sqrt():

The sqrt() method returns the square root of a number. If the value of number is
negative, sqrt returns NaN.

Syntax: Math.sqrt(n)

• Math.log():

This method returns the natural logarithm (base E) of a number. If the value of
number is negative, the return value is always NaN.

71
Syntax: Math.log(n)

11.Math.sin():

The sin() method returns the sine of a number. The sin method returns a numeric
value between -1 and 1, which represents the sine of the angle.
Syntax: Math.sin(n)

12.Math.cos():

The cos() method returns the cosine of a number. The cos method returns a numeric
value between -1 and 1, which represents the cosine of the angle.
Syntax: Math.cos(n)

• Math.tan():

The tan() method returns the tangent of a number. The tan method returns a
numeric value that represents the tangent of the angle.

Syntax: Math.tan(n)

• acos(), asin(), atan()

Example:
<html><head></head>
<body>
<script type="text/javascript">
document.write(Math.max(5,10) + "<br />");
document.write(Math.min(0,150,30,20,38) + "<br />");
document.write(Math.sqrt(36) + "<br />");
document.write(Math.pow(3,4) + "<br />");
document.write(Math.ceil(1.5)+ "<br />");
document.write(Math.floor(1.5)+ "<br />");
document.write(Math.round(1.5)+ "<br />");
document.write(Math.abs(-12.345)+ "<br />");
document.write(Math.sin(30)+ "<br />");
document.write(Math.cos(30)+ "<br />");
document.write(Math.tan(30)+ "<br />");
document.write(Math.log(5)+ "<br />");
document.write(Math.random(-12.345)+ "<br />");
document.write(Math.random(11)+ "<br />");
document.write(Math.random()+ "<br />");
</script></body></html>
Output:
10
0
6
81
2
72
1
2
12.345
-0.9880316240928618
0.15425144988758405
-6.405331196646276
1.6094379124341003
0.7091526409954392
0.6440733917520216
0.09861611898007938
CONTROL STATEMENTS
The control statements are used to control the flow of execution of the program. This
execution order depends on the supplied data values and the conditional
logic. JavaScript contains the following types of control statements:
• Conditional Statements.
• Looping Statements.
• Unconditional Statements.

• Conditional Statements:

Conditional statements are used to execute block of block of statements based on


the given condition. JavaScript provides two types of built-in conditional statements.
They are:
• if statement and its types.
• switch statement.
• simple if statement:
The general syntax of simple if statement is:
if (test-condition)
{
Statement(s) to be executed if test-condition is true
}
The test-condition can be a relational, logical or any other expression
which evaluates to true or false. In simple if, first the test-condition is
executed. If the resulting value is true, given statement(s) are executed.
If test-condition is false then no statement would be not executed.
Example:
<html><head></head>
<body>
<script type="text/javascript">
var a=parseInt(window.prompt("Enter value into a","0"));
var b=parseInt(window.prompt("Enter value into b","0"));
if(a>b)
{
document.write(a+"is big");
}
</script></body></html>

• if-else statement:

The general syntax of if-else statement is:


73
if (test-condition)
{
Statements;
}
else
{
Statement(s) to be executed if test-condition is false
}

The test-condition can be a relational, logical or any other expression


which evaluates to true or false. In if-else, first the test-condition is
executed. If the resulting value is true, if block statement(s) are executed.
If test-condition is false then else block statements would be executed.
Example:<html><body>
<script type="text/javascript">
var a=parseInt(window.prompt("Enter value into a","0"));
var b=parseInt(window.prompt("Enter value into b","0"));
if(a>b)
{
document.write(a+"is big");
} else
{
document.write(b+"is big");
}
</script></body></html>

• Nested if-else: The general syntax of nested if-else statement is:

if (test-condition1)
{
if (test-condition2)
{
Statement-1
}
else
{
Statement-2
}

}
else
{
Statement-3
}

In this, first the test-condition1 is evaluated. If it evaluates to true, test-


condition2 is evaluated. If the test-condition2 also evaluates to true, then
statements-1 would get executed. If the condition-2 evaluates to false,
then the else block of the inner if, statement-2 would get executed. If

74
condition-1 itself evaluates to false, then the else block of the outer if,
statements-3 would get executed.
Example:
<html>
<head>
<script language="javascript">
var a=parseInt(prompt("enter value into a"));
var b=parseInt(prompt("enter value into b"));
var c=parseInt(prompt("enter value into c"));
if(a>b)
{
if(a>c)
{
document.write("a is big"+a);
}
else
{
document.write("c is big"+c);
}
}
else
{
if(b>c)
{
document.write("b is big"+b);
}
else
{
document.write("c is big"+c);
}
}
</script></head></html>

• else if ladder:

The general syntax of else if ladder is:


if (test-condition 1)
{
Statement-1(s)
}
else if (test-condition 2)
{
Statement-2(s)
}
else if (test-condition 3)
{
Statement-3(s)
}
-
-
-
75
-
else
{
Statement(s)
}

In else if ladder, the conditions are evaluated from top to downwards. As soon
as the true condition is found, the statements associated with it are executed.
When all the conditions become false, then the final else containing the
statements will be executed.
Example:
<html>
<head>
</head>
<body>
<script language="javascript">
var gender=window.prompt("enter your gender");
var age=parseInt(window.prompt("enter your age"));
if((gender=="male")||(gender=="m"))
{
if((age>=20)&&(age<=90))
{
document.write("He is eligible for vote");
}
else
{
document.write("He is not eligible for vote");
}
}
else if((gender=="female")||(gender=="f"))
{
if((age>=18)&&(age<=90))
{
document.write("She is eligible for vote");
}
else
{
document.write("She is not eligible for vote");
}
}
else
{
document.write("Wrong gender");
}
</script>
</body>
</html>

• switch:

76
The switch statement allows the user to specify an unlimited number of
execution paths based on the value of a single expression. Each execution path
is referred as a case.
However, all the cases should be unique. Each case must be terminated by a
‘break’ statement. The ‘default’ case is not mandatory.
In a switch statement, there are four different keywords to be used:

• switch
• case
• break
• default

Though the switch control structure enables the user to improve clarity of the
program, it causes more errors. So, it requires more attention while implementation.

Syntax:
switch(expression)
{
case value1:
statement;
break;
case value2:
statement;
break;
:
:
:
default :
statement;
}
Among all the cases, only one case can be executed successfully because each case is
terminated by a ‘break’ statement.
Example:
<html>
<head></head>
<body>
<script language="javascript">
var i=parseInt(prompt("enter i value"));
switch (i)
{
case 1:
document.write("monday");
break;
case 2:
document.write("tuesday");
break;
case 3:
document.write("wednesday");
break;
case 4:
document.write("thursday");
77
break;
case 5:
document.write("friday");
break;
case 6:
document.write("saturday");
break;
case 7:
document.write("sunday");
break;
default:
document.write("no day");

}
</script></body></html>

• Looping statements:

The process of repeatedly executing a block of statements as long as some


condition is true is called looping statements. It is classified into three types. They
are
• while loop
• do-while loop
• for loop

• While loop:

The general syntax of while loop is:

Syntax:

while(test-condition)
{
body of the loop;
}

The while loop is an entry-controlled loop. The purpose of a while loop is to


execute a statement or code block repeatedly as long as is true. Once test-condition
becomes false, the loop will be exited.

Example :

<html><head>
<script language="javascript">
var i=1;
var n=parseInt(prompt("enter avalue"));
while(i<=n)
{
document.write(i+”<br>”);
i++;
78
}
</script></head></html>

• Do-while loop:

The general syntax of while loop is:

do
{
body of the loop;

} while(test-condition);

The do-while is an exit-controlled loop. In do-while, the body of the loop


executed first, later at the end of the loop test- condition in the while statement is
evaluated. If the test-
condition is true, the body of the loop gets executed as long as given condition is true.
When the test-condition becomes false, the control comes out of the loop.

Example:

<html>
<head>
<script language="javascript">
var i=1;
var n=parseInt(prompt("enter avalue"));
do
{
document.write(i+”<br>”);
i++;
}
while(i<=n);
</script></head></html>

• For loop:

The general syntax of for loop is:

for (initialization; test-condition; updation)


{
body of the loop;
}

The for loop contains initialization, test-condition and updation statement.


Basing on them the statements within the for loop will be executed. In for loop
each statement
79
is separated by semicolon.

Example:
<html><body>
<script type="text/javascript">
var i;
for (i=1;i<=5;i++)
{
document.write("The number is " + i+”<br>”);
}
</script>
</body></html>

• unconditional statements:

• Continue statement:

During the loop operat ions, it may be necessary to skip a part


of the body of the loop under certain conditions. i.e., skip the following
statements and continue with the next iteration can be done by continue
statement.

Syntax: continue;

Example:

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i+”<br>”);
}
</script>
<p>Explanation: The loop will break the current loop and
continue with the next value when i=3.</p>
</body></html>

• break statement :

This statement takes control out of the switch statement or


loop structure. In other words, a break statement takes the control out of
the current block in execution. The control is transferred to the statement
that follows the block.

80
Syntax: break;

Example:

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
}
</script>
<p>Explanation: The loop will break when i=3.</p>
</body>
</html>

Arrays
In JavaScript, an array is a collection of data items of different types stored under a
single variable name.
You can access the data items either sequentially by reading from the start of the
array or by their index. The index is the position of the data item or element in the array.
In array, the first element begins at position or index 0 and the last element at
arraylength-1.
0 1 2 3 length-1
Item one Item two Item three Item four -------------- Item n

Creating an array:
In JavaScript arrays can be created in three different ways:
• The first approach is simply to declare a variable and pass it some
elements in array format:

Syntax: var array_name = [item1, item2, item3, --- item n];


Ex: var day = [“Monday”,”Tuesday”,”Wednesday”];
Note: The array of elements is surrounded by square brackets. In most
programming language square brackets denotes arrays and array operations.

• The second approach is to create an array object using the keyword new
and a set of elements to store.

Syntax: var array_name= new Array (item1, item2, -----item n);


Ex: var day=new Array (“Monday”,”Tuesday”,”Wednesday”);
Using this construct, the contents of the array are surrounded by parenthesis
because they are parameters to the constructor of the array object.

81
• The third approach is to create an empty array which has space for a
number of elements to be stored.

Syntax: var array_name=new Array ( )


Ex: var day=new Array ( );
day [0] =”Monday’;
day [1] =”Tuesday’;
day [2] =”Wednesday”;
In JavaScript arrays can hold mixed data types as the following:
Ex: var student = [100,”Krishna”, 540, 87.56];
Adding and accessing elements to or from an array:
Adding elements:
Array elements are added by their index. The index denotes the position of the
elements in the array.
Syntax: var array_name [index] = dataitem;
Ex: var data = [“Monday”, “Tuesday”, 34, 76.34,”Wednesday”];
data [5] = “Thursday”;
data [23] = 48;
Accessing elements:
The elements in the array are accessed through their index. The same access
method is used to find elements and to change their value.
Example:

The following code shows how to add and access elements in array.

<html>
<head>
<script language="javascript">
var data = ["Monday","Tuesday", 34,76.34,"Wednesday"];
data[5] = "Thursday";
var len=data.length;
for(var count=0;count<len;count++)
{
document.write(data[count]+" ");
}
</script>
</head>
</html>

Output:

Monday Tuesday 34 76.34 Wednesday Thursday

Note: length is an array property used to count the no of data items in an array.

Searching element in an Array:

To search an array, simply read each element in turn and compare it with the value that
you’re looking for.

Example:
82
The following code shows how to search an element in an array.

<html>
<head></head>
<body>
<script language="javascript">
var data = ["Monday","Tuesday",34,76.34,"Wednesday"];
data[5] = "Thursday";
var len=data.length;
for(var count=0;count<len;count++)
{
if(data[count] == "Tuesday")
{
document.write(“Element found at position”+(count+1));
break;
}
}
</script></body></html>

Output:

Element found at position 1

JavaScript Array Object


In JavaScript array is an object contains both properties and methods used to perform
manipulation on data items of an array.
Array Object Properties:
1.length:
The length property sets or returns the number of elements in an array.
Syntax: array_name.length;
2.constructor:
The constructor property returns the function that created the array object's
prototype.
Syntax: array_name.constructor;
Array Object Methods:
1.concat ():
The concat () method is used to join two or more arrays. This method does
not change the existing arrays, but returns a new array, containing the values of the
joined arrays.

Syntax: array_name1.concat (array_name2, array_name3-----);

2.join():
The join () method joins the elements of an array into a string, and returns the
string. The elements will be separated by a specified separator. The default separator is
comma (,).

83
Syntax: arrayname.join (separator);

3.pop():
The pop () method removes the last element of an array, and returns that
element.
Syntax: arrayname.pop ();
4.push():
The push () method adds new items to the end of an array, and returns the
new length.

Syntax: arrayname.push (new item);

5.shift ():
The shift () method removes the first item of an array, and returns that
item.

Syntax: arrayname.shift ();

6.unshift ():
The unshift () method adds new items to the beginning of an array, and returns
the new length.

Syntax: arrayname.unshift (new item);

7. reverse ():
The reverse () method reverses the order of the elements in an array.
Syntax: arrayname.reverse ();
8.sort ():
The sort () method sorts the items of an array. Default sort order is
alphabetic and ascending.

Syntax: arrayname.sort ();

9.slice ():
The slice () method returns the selected elements in an array, as a new array
object. The slice () method selects the elements starting at the given start argument,
and ends at, but does not include, the given end argument.

Syntax: arrayname.slice (start, end);

10.splice ():
The splice () method adds/removes items to/from an array, and returns the
removed item(s).

Syntax: arrayname.splice (index, how many item to delete, new items);

Example:
<html>
<head>
</head>
<body>
84
<script>
var a = [10,20,45,30,40];
var b = [10.2,20.2,30.3,40.2,"jkc"];
document.write(a.concat(b)+"<br>");
document.write(a.join()+"<br>");
document.write(a.pop()+"<br>");
document.write(b.push(45)+"<br>");
document.write(a.reverse()+"<br>");
document.write(b.shift()+"<br>");
document.write(a.unshift("college")+"<br>");
document.write(b.slice(2,5)+"<br>");
document.write(b.splice(2,1)+"<br>");
document.write(a.sort()+"<br>");
</script>
</body> </html>

Output:
10,20,45,30,40,10.2,20.2,30.3,40.2,jkc
10,20,45,30,40
40
6
30,45,20,10
10.2
5
40.2,jkc,45
40.2
10,20,30,45,college

JavaScript Functions
Function:
A function is a self contained block of code that is to be executed when it is called
anywhere in our program.
In JavaScript function is defined in the head section and then it can be invoked or called
somewhere later in the html document. You must have seen functions (built-in)
like alert(), prompt() and write() in previous chapters. JavaScript allows us to write our
own functions (user defined) as well.
Defining a function:
Before we use a function we need to define that function. The most common
way to define a function in JavaScript is by using the function keyword, followed by a
unique function name, a list of parameters (that might be empty), and a statement
block surrounded by curly braces.
The basic syntax for defining a function is:
function function_name (parameter-list)
{
Statements
}
Calling a function:
To invoke or call a function somewhere later in the script, you would simple need
to write the name of that called function as follows:
Syntax: function_name ();
85
Example:
<html>
<head>
<title>Calling a function</title>
<script language="javascript">
function Good()
{
window.alert("Good morning");
}
</script></head>
<body>
<script language="javascript">
Good();
</script>
</body></html>

Function parameters or passing arguments to function:


Till now we have seen function without a parameters or arguments. But there is a
facility to pass different parameters while calling a function. These are variables, either
numbers or strings, with which the function is supposed to do something.
These passed parameters can be captured inside the function and any
manipulation can be done over those parameters. A function can take multiple
parameters separated by comma.

Syntax for passing arguments to a function is:


function_name (agrument1, argument2 …)
Example for passing arguments to a function:
<html>
<head>
<title>Calling a function</title>
<script language="javascript">
function Addition(x,y)
{
var a,b,c;
a=x;
b=y;
c=a+b;
document.write("The addition of a and b is"+c);

}
</script>
</head>
<body>
<script language="javascript">
Addition(10,15);
</script>
</body>
</html>

86
The return statement:

A JavaScript function can have an optional return statement. This is required if you
want to return a value from a function. This statement should be the last statement in a
function.

Syntax: return value;

Example for return statement:

<html>
<head>
<title>Calling a function</title>
<script language="javascript">

function Addition(x,y)
{
var a,b,c;
a=x;
b=y;
c=a+b;
return c;
}
</script>
</head>
<body>
<script language="javascript">
var sum;
sum=Addition(11,15);
document.write("The addition of a and b is"+sum);
</script>
</body>
</html>

Objects

• An Object is a thing. It contains data and set of methods. Objects


are designed using classes.
• An object is a run-time instance of a class.
• In JavaScript everything is an Object: a String, a Number, an
Array, a Function....
• In addition, JavaScript allows you to define your own objects.
Class: A class usually contains both data items and some methods. Each class
provides services to other classes in the system.

this: “this” can be used inside any method to refer to the current object. The keyword
helps us to avoid name conflicts. As we can see in the program that we have declare

87
the name of instance variable and local variables same. Now to avoid the confliction
between them we use this keyword.

new: The new operator is used to create an instance of an object. It allocates memory
for objects and sets all variables. New calls a function which has the same name as the
type of object that is being created. This function is called constructor. A constructor is a
function that creates and initializes an object. JavaScript provides a special constructor
function called Object() to build the object.

.(dot): when referring to a property of an object, whether a method or a variable, a dot is


placed between the object name and the property.

Creating JavaScript Objects

We can create object by using two ways.


1. By using the keyword “Object”
var <objectname>=new Object();
Example1: <html>
<body>
<script>
var person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
document.write(person.firstname + " is " + person.age + " years old.");
</script></body></html>

2. By using function name as class name (creating our own objects)


var <objectname>=new functionname();
new keyword is used to allocate memory for the object.

Example2: <html> <head>


<script>
function book()
{
this.title="I &WT";
this.author="Bates";
}
</script>
</head>
<body><script>
var obj=new book();
document.write("title is"+obj.title);
document.write("author is"+obj.author);
</script></body></html>
88
Built-in Objects
1. Document Object:
A document is a webpage that is being either displayed or created. The
document has a number of properties that can be accessed by JavaScript programs
and used to manipulate the content of the page.
• write():Writes HTML expressions or JavaScript code to a document.
document.write(“welcome”);
• writeln():Same as write(), but adds a newline character after each statement
• anchors: Returns a collection of all the anchors in the document. Any named
point inside an HTML document is an anchor. <a name=…>
Anchors can be accessed like document.anchors[0];
• forms: This is a array contains all the forms in the document in the order.
• links. An array contains all the links in the document in the same order as they
appear on the webpage.
• bgcolor: This property defines a document's background color.
document.bgcolor=”blue”
• fgcolor: This property defines a document's foreground (text) color.
document.fgcolor=”red”

Example:
<html>
<body>
<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>
<a href=”abc.html”>JavaScript Tutorial</a>
<script>
document.bgcolor="pink";
document.fgcolor="blue";
document.write("hai");
document.writeln("welcome");
document.write(document.anchors.length);
document.write(document.links[o]);
</script></p>
</body></html>

2. Window Object:
• open():Opens a new browser window.
Syntax: window.open(“url”, ”name”, ”window features”);

url: Optional. Specifies the URL of the page to open.


Name: Optional. Specifies the name of the window.
89
Window features:toolbar:1|0|yes|no Location: 1|0|yes|no Status: 1|0|yes|no
Menubar: 1|0|yes|no Scrollbars: 1|0|yes|no

• close():Closes the current window


Syntax: window.close();
• Width: used to set the width of the new window.
• Height: used to set the height of the new window.
• alert():Displays an alert box with a message and an OK button.
• confirm():Displays a dialog box with a message and an OK and a Cancel button.
• prompt()Displays a dialog box that prompts the visitor for input.

Example:
<html><head><script>
function open_win()
{
window.open("");
}

function open_mul()
{
window.open("");
window.open("");
}

function closeWin()
{
window.close();
}

function moveWin()
{
window.moveBy(250,250);
window.focus();
window.alert("welcome");
window.confirm("welcome");
}
}
</script></head>
<body><form>
<input type="button" value="Open Window" onclick="open_win()"><br>
<input type="button" value="Open multiWindow" onclick="open_mul()"><br>
<input type="button" value="close Window" onclick="closeWin()"><br>
<input type="button" value="movigWindow" onclick="moveWin()"><br>
</form></body></html>

3. Browser Object:
No two browser models will process your JavaScript in the same way. JavaScript has
the capability to identify the properties of the browser object. The Navigator object
contains information about the visitors browser name, version and more
• navigator.appCodeName: Returns the code name of the browser
• navigator.appName Returns the name of the browser.
90
• navigator.appVersion: Returns the version information of the browser
• navigator.plugins : An array containing details of all installed plug-ins.
• navigator.userAgent: Returns the strings appCodeName and appVersion
concatenated together.
Example:
<html>
<body>
<script>
document.write("appletCodeName: " + navigator.appCodeName+"<br>");
document.write("appletName: " + navigator.appName+"<br>");
document.write("version: " + navigator.appVersion+"<br>");
document.write("platform: " + navigator.plugins);
document.write("useragent: " + navigator.userAgent+"<br>");
</script>
</body>
</html>
4. Form Object:
The form object represents an HTML form. For each <form>tag in an HTML
document, a form object created. All elements of form are held in an array.
Forms[0].method;
Forms are used to collect user input and contain input elements like textfields,
checkboxes…..
• length: Returns the number of elements in a form.
• onClick=”method” : The event is triggered when the user clicks on that element.
• onSubmit=”method” : This event can only be triggered by the form itself and
occurs when a form is submitted.
• onReset=”method” : This event occurs when a form is reset by the user.

Example: <html><head>
<script>
function jk()
{
f1.submit();
}
function jk1()
{
f1.reset();
}
</script></head>
<body>
<form name=f1>
user name:<input type=text name=t1><br>
password:<input type=password name=t2><br>
<input type=button value=submitform onclick=jk()><br>
<input type=button value=resetform onclick=jk1()><br>
</form></body></html>

5. Date Object:
The java script does not have a date datatype. Java script includes well-developed
Date class which provides functions to perform many different date manipulations.

91
In javascript Dates and Times represent the number of milliseconds since 1st January
1970 UTC. Time formats are UTC and local. UTC is Universal time(Greenwich Mean
Time). Local time is the time on the machine.
Mon, 9 April 2001 14:02:35 GMT
To create a date object: Date objects are created with new Date().
Syntax:
var d = new Date(); Construct an empty date object.
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getYear() Use the getFullYear() method instead
setDate() Sets the day of the month of a date object
setFullYear() Sets the year (four digits) of a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes of a date object
setMonth() Sets the month of a date object
setSeconds() Sets the seconds of a date object
setTime() Sets a date and time by adding or subtracting a specified number
of milliseconds to/from midnight January 1, 1970
setYear() Use the setFullYear() method instead

Example:
<html>
<body>
<script>
var d=new Date();
document.write("today date is"+d+"<br>");
document.write("today date "+d.getDate()+"<br>");
document.write("today is"+d.getDay()+"<br>");
document.write("month is"+d.getMonth()+"<br>");
document.write("year is"+d.getYear()+"<br>");
document.write("hours is"+d.getHours()+"<br>");
document.write("minutes are is"+d.getMinutes()+"<br>");
92
document.write("seconds areis"+d.getSeconds()+"<br>");
d.setYear(2013);
document.write(d+"<br>");
d.setMonth(10);
document.write(d+"<br>");
d.setDate(13);
document.write(d+"<br>");
d.setHours(03);
document.write(d+"<br>");
d.setminutes(45);
document.write(d+"<br>");
d.setSeconds(20);
document.write(d+"<br>");
</script>
</body> </html>

DYNAMIC HTML WITH JAVASCRIPT


1.What is DHTML?
DHTML means Dynamic Hyper Text Markup Language. It is a
combination of HTML, JavaScript, CSS (Cascading Style Sheets) and DOM
(Document Object Model). It creates some interactive and animated web sites.
Commonly, DHTML is used to make rollover buttons or drop-down menus on a
web page.

2. Explain about Data Validation in DHTML?


Validation is the process of checking the validity of user-supplied data in a form
before it is submitted to a server-side program. Data Validation is the process of
ensuring that users submit only the set of required characters and they are within
a particular range, otherwise we should not accept invalid data, display an error
message.
JavaScript Regular Expressions can be used to validate data in HTML forms
before sending off the content to a web server.
In this example we can validate our entered form data before submitting it
to the web server.
Example:
<html>
<head>
<script language="javascript">
function validate()
{
var name=document.f1.n.value;
var age=document.f1.a.value;
if(name==null )
93
window.alert(“ name should not be null”);
if(age<18 II age>30)
window.alert(“ Enter correct age”);
else
window.confirm("Are you want to submit data");

}
</script>
</head>
<body>
<form name=f1>
Enter your name:<input type=text name=n><br>
Enter your age:<input type=text name=a><br>
<input type=submit value=submit onclick=validate()>
<input type=reset value=reset>
</form>
</body>
</html>
This example shows how to validate an entered username must
contain starting letter capital letter and from second letter it contains both
capital, small letters and also contain symbols space,_,.,’ but does not
contain any numbers at any position and the age must contain only
numbers within range but not alphabets.

3. Explain how to Open a new window ?

To open a new browser window, use the window. open () method.


Syntax: window. open (“URL to open”, “window name”, ‘attrbt1, attrbt2 …’);
• URL to open: This is the web address of the page you wish to appear in the
new window.
• Window name: you can name your window whatever you like, in case you
need to make a reference to the window later.
• Attrbt1, attrbt2…: These are optional and are used to specify the features
of new window.
Window attributes:
• width: used to define the width of the new window.
Syntax: width = pixels
• height: used to define the height of the new window.
Syntax: height = pixels
• resizable: used to control whether or not you want the user to be able to
resize the window.
94
Syntax: resizable = yes|no (or) 1|0
• scrollbars: This lets you decide whether or not to have scroll bars on the
new window.
Syntax: scrollbars = yes|no (or) 1|0
• toolbar: This lets you decide whether or not the new window should have
the browser navigation bar at the top.
Syntax: toolbar = yes|no (or) 1|0
• location: This let you decide whether or not you wish to show the location
box with the current URL ( The place you type http://address)
Syntax: location = yes|no (or) 1|0
• status: This let you decide whether or not to show the window status bar at
the bottom of the window.
Syntax: status = yes|no (or) 1|0
• menubar: This let you decide whether or not to show the menus at the top
of the new window.
Syntax: yes|no (or) 1|0

window.close ():
The close () method closes the current window.
Syntax: window. close ();
Example:
<html>
<head>
<script language="javascript">
function op()
{
win=window.open("web1.html","web1",’width=200,height=200,menubar=yes’);
}
function cls()
{
win.close();
}

</script>
</head>
<body>
<form>
<input type=button value=open onclick=op()>
<input type=button value=close onclick=cls()>
</form>
</body>
</html>

95
4. Explain built-in window types or dialog boxes?
Or
Explain message passing and confirmations in DHTML?

JavaScript supports three built-in window types of dialog boxes.


These dialog boxes can be used to raise and alert, or to get confirmation on any
input or to have a kind of input from the users. The three important dialog boxes
are:
• Alert Box
• Confirmation Box
• Prompt Box

Alert dialog box:


An alert dialog box is mostly used to give a warning message to the
users. It displays the text string and “ok” button to select and proceed.

Example: window. alert (“warning message”);

Confirmation dialog box:


It shows a window containing a message and two buttons: “ok” and
“cancel”. If the user clicks on ok button the window method confirm () will return
true. If the user clicks on the cancel button the window method confirm () will
return false. When we click ok, then the action proceeds.

Example: window.confirm (“do you want to proceed?”);

96
Prompt dialog box:
It shows a window containing a prompt and a text filed in which the user
can enter data. This method has two parameters: a text string to be used as the
prompt and a string to use as the default value. If you don’t want to display a
default value then simply use an empty string. This dialog box contains two
buttons: Ok and cancel. If the user click on ok button the window method prompt
() will return entered value. If the user clicks on the cancel button the window
method prompt () returns null.

Syntax: window.prompt (“String”, “default value”);

Ex: window.prompt (“enter a number”,”0”);

5. Explain how to write to status bar?


The status bar is the small message area you see at the bottom of the
browser window. The status property sets or returns the default text in the status
bar at the bottom of the browser. The status bar usually displays helpful
information about the operation of the browser.

Syntax:
window.status = ”text”;
(or)
self.status = ”text”;
Example:

<html>
<body>
<script>
window.status=”Welcome to jkc college!!”;
</script>
<h1>welcome to III B.Sc </h1>
</body>
</html>

97
self: Sometimes the script needs to act upon the browser window in which it is
running. Other times objects need to change their own parameters. In both cases
“self” is used so that the object can identify itself or its browser.

6. Explain about writing to a different frame in DHTML?

Frames in HTML allow you to divide a browser window into several


independent parts. A group of frames in a single browser window is called a
frameset. Each frame contains a single document. Each frame has a unique name
and we can use that name to write or read those documents. Once frames and
java script are combined on the same page we can develop some interesting and
interactive web pages.
We are using is a combination of HTML, JavaScript to develop an
interactive web pages. A site can have links in one frame and output in another
frame.
One popular use of frames and JavaScript is a color picker.
The simple color picker webpage consists of two frames. Through the top
frame we are writing text to bottom frame and also changing the text color and
background color. This application runs totally on the client side

Color.html
<html>
<frameset rows="60%,40%">
<frame name="topbox" src="abc.html">
<frame name="bottombox" src="">
</frameset>
</html>
abc.html
<html>
<head>
<script language="javascript" >
function changecolor()
{
var bcolor=f1.bgcol.value;
var tcolor=f1.txtcol.value;

parent.bottombox.document.write(“<h1 align=”center”>Welcome to DHTML</h1>”);


parent.bottombox.document.bgColor=bcolor;
parent.bottombox.document.fgColor=tcolor;
}
</script>
</head>
<body>
<h1 align=center>Color Picker Program </h1>

98
<br> <br>
<form name=f1>
Background Color:<input type=text name=bgcol> &nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;
Text Color:<input type=text name=txtcol><br><br>
<input type=button value=showit onclick=changecolor()>&nbsp;&nbsp;&nbsp;&nbsp;
<input type=reset value=reset>
</form> </body> </html>

The structure of the color picker is:

frameset

Lower Upper
frame frame
document document

form

elements

Each frame is a part of the main window and contains a single document. Each
frame has a unique name and we can use that name to write to or read from,
those documents.

99
The parent window has an array of all frames which can be referred to
either by their position in the array or by its name.
parent.bottombox.document
or
parent.frames[1].document

7. Write about Rollover buttons?


The most common usage of dynamic HTML is the image rollover. The
technique is used to give visual feedback about the location of the mouse cursor
by changing the images on the page as the mouse moves over them. This is a
highly effective technique, especially where images are used as the hyperlinks in a
menu, or where an image map is being used.
The java script rollover is far simpler because it uses two image files. Which
it moves between as the mouse is moved. One image is created for the inactive
state. When the mouse is not over it. A second image is created for the active
state when the mouse cursor is placed over it.
Example:
<html>
<head>
<title>rollover buttons</title>
<script language=javascript>
function mymouseon( )
{
document.top.src="Desert.jpg";
}
function mymouseoff()
{
document.top.src="Winter.jpg";
}
</script>
</head>
<body>
<h1>Demonstrating the mouseover effect</h1>
<a href="#" onMouseOver="mymouseon()" onMouseOut="mymouseoff()">
<img alt="showpicture" name=top width=200 height=200>
</a>
<br>
<br>
<p>this is the simple page to test the rollover buttons</p>

100
</body> </html>

Explanation:
onmouseover and onmouseout are event handless they tell javascript
function. When an event occurs.
 onMouseOver calls a JavaScript function. When the cursor passes over the
image i.e. OnMouseOver=”mymouseon()” would tell JavaScript to execute the
function mymouseon() when the cursor passes over the image.
 OnMouseOut calls a JavaScript function when the cursor moves away from the
image i.e. OnMouseOut = “mymouseoff( )” would tell JavaScript to execute the
function mymouseoff( ) when the cursor moves away from the image.
The address tag includes this construct: href=”#” If you use # as the address of a
link, the browser will simply reload the current page.

8. Write about Moving images?


Moving images around the screen is pretty simple. javascript can be used to move
a number of elements (<img>, <div> or any other HTML element) around the page
according to some sort of pattern determined by a logical equation or a function.
JavaScript provides two built-in functions to be frequently used in
animation programs.
1) setTimeout( )
2) clearTimeout( )

1) setTimeout( function, duration):


This function calls a function after a specified number of
milliseconds (duration) from now.
Syntax: setTimeout(“function”, duration);
Example: setTimeout(“abc()”, 100); Note: 100ms=1 sec
2) clearTimeout(SetTimeOut-variable):
This function clears any timer set by the setTimeout() function.
Syntax: clearTimeout(setTimeout-variable);
JavaScript can also set a number of attributes of an object including its position on
the screen you can set top and left attribute of an object to position it anywhere
on the screen.
Syntax to set position:
object.style.position = “position”; i.e., either relative or absolute.
Syntax to set distance from left edge of the screen:
object.style.left = distance in pixels (or) points;
Syntax to set distance from top edge of the screen:
object.style.top=distance in pixels (or) points
Example:

101
<html>
<head>
<script language=javascript>
var i=0;
function starttimer()
{
document.getElementById("myimage").style.position="relative";
document.getElementById("myimage").style.left=i;
i++;
timer=setTimeout("starttimer()",10);
}
function stoptimer()
{
clearTimeout(timer);
document.getElementById("myimage").style.left=i;
}
</script>
</head>
<body>
<img id="myimage" src=abc.jpg width=100 height=100>
<input type=button value=move onclick=starttimer()>
<input type=button value=stop onclick=stoptimer()>
</body> </html>

Explanation:
In this example, we are using javascript function getElementById( ) to
get an object and positioned to “relative”. We have defined a function starttimer(
) to initiate object where we have set its position and left attribute. We are calling
initialization function starttimer( ) in the function setTimeout( ) for every 10
milliseconds and clearTimeout( ) function clears timer set by the setTimeout( )
function.

102
XML

XML stands for eXtensible Markup Language, which became a W3C


Recommendation on 10th February 1998. XML is a markup language much like
HTML. XML was designed to transport and store data, not to display data. XML
tags are not predefined. You must define your own tags.

1. What are the Difference between XML and HTML:

HTML XML
1.HTML is used to display data and 1.XML is a software and hardware
focuses on how data looks. independent tool used to transport and
store data.
2. HTML is a markup 2.XML provides a framework to define
language itself. markup languages.
3. HTML is not case sensitive. 3. XML is case sensitive.

4.HTML tags are predefined. 4. We can define tags according to our


need.

5.In HTML, it is not necessary to use 5.XML makes it mandatory to use a


a closing tag. closing tag.
6.HTML is static because it is used 6.XML is dynamic because it is used to
to display data. transport data.
7.HTML does not preserve 7.XML preserve whitespaces.
whitespaces.
8. HTML code for library catalog: 8. XML code:

<html> <student>
<body> <name>Divya</name>
<h1>Divya</h1> <section>III BBA</section>
<h2>III BBA</h2> <total>234</total>
<h3>234</h3> </student>
</body>
</html>

103
2. What are the Features and Advantages of XML:
XML is widely used in the era of web development. It is also used to simplify data
storage and data sharing. The main features or advantages of XML are given
below.

1) XML separates data from HTML

If we need to display dynamic data in your HTML document, it will take a lot of
work to edit the HTML each time the data changes. With XML, data can be stored
in separate XML files. Changes in the underlying data will not require any changes
to the HTML. With a few lines of JavaScript code, you can read an external XML
file and update the data content of your web page.

2) XML simplifies data sharing

In the real world, computer systems and databases contain data in incompatible
formats. XML data is stored in plain text format. This provides a software and
hardware independent way of storing data. This makes it much easier to create
data that can be shared by different applications.

3) XML simplifies data transport

One of the most time-consuming challenges for developers is to exchange data


between incompatible systems over the Internet. Exchanging data as XML greatly
reduces this complexity, since the data can be read by different incompatible
applications.

4) XML simplifies Platform change


Upgrading to new systems (hardware or software platforms), is always time
consuming. Large amounts of data must be converted and incompatible data is
often lost. XML data is stored in text format. This makes it easier to expand or
upgrade to new operating systems, new applications, or new browsers, without
losing data.
5) XML increases data availability
Different applications can access your data, not only in HTML pages, but also from
XML data sources. With XML, your data can be available to all kinds of "reading
machines" (Handheld computers, voice machines, news feeds, etc), and make it
more available for blind people, or people with other disabilities.
6) XML can be used to create new internet languages
104
A lot of new Internet languages are created with XML. Here are some examples:
XHTML, WSDL for describing available web services, WAP and WML as markup
languages for handheld devices, RSS languages for news feeds, RDF and OWL for
describing resources and ontology, SMIL for describing multimedia for the web.

3. Explain the basic structure of XML ?

Let us discuss the syntax of the XML document with the help of the following
example.

<?xml version="1.0" ?> XML declaration


<!DOCTYPE document SYSTEM "tutorials.dtd"> Document Type
Definition
<!-- Here is a comment --> Comments
<?xml-stylesheet type="text/css" href="myStyles.css"?> Processing
instructions
Elements and
contents
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

XML Declaration:
The XML declaration indicates that the document is written in XML and specifies
which version of XML. <?xml version=”1.0”?> This instruction tells the parser
that the data in the file follows the rules of XML version 1.0. This instruction must
be the first instruction in your XML file.

Document Type Definition (DTD):


The DTD defines the rules of your XML document. Although XML itself has rules,
the rules defined in a DTD are specific to your own needs. More specifically, the
DTD allows you to specify the names of the elements that are allowed in the
document, which elements are allowed to be nested inside other elements, and
which elements can only contain data. DTD may be internal or external to the
XML file.
<!DOCTYPE document SYSTEM "tutorials.dtd">

105
Comments:
XML comments are the same as HTML comments begin with <!-- and end with --
>. The same type of comments are used in both XML source files and in DTD files.

Processing Instructions:
Processing instructions begin with <? and end with ?>. Processing instructions are
instructions for the XML processor to control applications.
Elements & Content:
XML documents must contain a root element. This element is "the parent" of all
other elements. The elements in an XML document form a document tree. The
tree starts at the root and branches to the lowest level of the tree. All elements
can have sub elements (child elements). The terms parent, child, and sibling are
used to describe the relationships between elements. Parent elements have
children. Children on the same level are called siblings. All elements can have text
content and attributes .

XML elements:

XML elements are represented by tags. Elements usually consist of an opening tag
and a closing tag, but they can consist of just one tag. Opening tags consist of <,
followed by the element name, and ending with >. Closing tags are the same but
have a forward slash inserted between the less than symbol and the element
name. XML elements are case sensitive.<book> is different from <BOOK>. XML
elements must be nested properly.XML elements may have attributes.

Syntax: <tag>Data</tag>
Example: <author>Bala guruswamy</author>

4. Explain about Document Type Definition: (DTD) ?

DTD stands for Document Type Definition. A DTD allows you to create rules for
the elements within your XML documents. Although XML itself has rules, the rules
defined in a DTD are specific to your own needs.

The DTD is declared at the top of your XML document. The actual contents of
the DTD can be included within your XML document or included in another
document and linked to (or both).
The XML document contains data where as DTD file contains rules that apply to
the data. A DTD is a file with a .dtd (filename.dtd) extension.

106
A <!DOCTYPE> declaration in an XML document specifies that we want to
include a reference to a DTD file. Whenever any program reads our XML
document containing a DOCTYPE tag, it understands that we have defined a DTD
for our XML document. Therefore it attempts to load the content of that file and
applies its rules to the content of our XML document.

Syntax of DTD:

<!DOCTYPE root-element
[
<!ELEMENT ELEMENTNAME-1 (sub elements list)>
<!ELEMENT ELEMENTNAME-2 (data-type)>
-
-
-
<!ELEMENT ELEMENTNAME-N (data-type)>
<!ATTLIST element-name attribute-name attribute-type default-value>
]>

DTD elements:
In the DTD, XML elements are declared with an element declaration.
An element declaration has the following syntax:

<!ELEMENT element_name subelements list or data-type>

Here, element_name is the name of the element you're defining, followed by a


data-type or another element needs to be surrounded by brackets . Data types
are
CDATA: CDATA is plain text character data which is not parsed through the engine
of the XML parser.
PCDATA: PCDATA is parsed character data which may contain XML markup and
hence has to be handle by the parser.
The default data type for elements is PCDATA , but CDATA can be very useful. If
the content of the element contains any of the characters which are used for
markup such as <, > or & you will not want the parser to handle these. If they are
parsed then you may get errors about the structure of your document. The use of
CDATA lets you avoid parsing.

107
Element names:
You can use any name you like for your elements as long as they adhere to the
following rules:

• Element names can contain any character (including letters and numbers)
• Element names must not contain spaces
• Element names must not begin with a number or punctuation character
(for example a comma or semi-colon etc)
• Element names must not start with the letters xml (whether lowercase,
uppercase, or mixed case)

You shouldn't use a colon (:) in your element names, as this is reserved for
another purpose.

Example: <! ELEMENT note (to, from, heading, body) >


<!ELEMENT to (#PCDATA)>

Empty elements:
Empty elements are declared with the keyword EMPTY inside the
parentheses:
Syntax: <! ELEMENT element-name (EMPTY) >
Example: <! ELEMENT header (EMPTY)>

DTD attributes:

In DTD, XML elements attributes are declared with an <!ATTLIST> declaration. An


attribute declaration has the following syntax:

<!ATTLIST element_name attribute_name TYPE DEFAULT_VALUE


attribute_name TYPE DEFAULT_VALUE attribute_name TYPE DEFAULT_VALUE
....>

The ATTLIST declaration defines the element which can have the attribute, the
name of the attribute, the type of the attribute, and the default attribute value.

DTD example:
<! ATTLIST payment type CDATA “check” >
XML example:
<payment type=”check”>

108
Types of DTD:

They are two types of DTDs, they are:


1) Internal DTD
2) External DTD

The only difference between internal and external is in the way it's declared with
<!DOCTYPE>.

1) Internal DTD declaration:

In this we enclose the DTD in a <DOCTYPE> element providing the name of


the root element of the document as (<! DOCTYPE note). If the DTD is declared
inside the XML file, it should be wrapped in a DOCTYPE definition with the
following syntax:

Syntax: <! DOCTYPE root-element [element-declarations]>

Example:
<?xml version="1.0"?>
<!DOCTYPE tutorials
[
<!ELEMENT tutorials (tutorial)+>
<!ELEMENT tutorial (name,url)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ATTLIST tutorials type CDATA #REQUIRED>
]>
<tutorials type="web">
<tutorial>
<name>XML Tutorial</name>
<url>http://www.jkcc.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML
Tutorial</name>

Item* The item appears 0 or more times. <url>http://www.jk


Item+ The item appears 1 or more tiles. cc.com/html/tutori
Item? The item appears 0 or 1. al</url>
(Item1|item2) Set of alternatives. </tutorial>
(item1,item2) Group of items. </tutorials>
109
2) External DTD declaration:

If the DTD is declared in an external file, it should be wrapped in a


DOCTYPE definition with the following syntax:

Syntax: <!DOCTYPE root-element SYSTEM “filename.dtd”>


<!DOCTYPE root-element PUBLIC “http://www.xml.com/abc.xml”>

In the above code the keyword SYSTEM is used, which indicates that the code is
executed on a local system. If the keyword PUBLIC is used it indicates that the
code is accessible globally.

This is the same XML document as above, but with an external DTD.

Example:

<?xml version="1.0"?>
<!DOCTYPE tutorials SYSTEM "tutorials.dtd">
<tutorials type="web">
<tutorial>
<name>XML Tutorial</name>
<url>http://www.jkcc.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.jkcc.com/html/tutorial</url>
</tutorial>
</tutorials>

And this is the file “tutorials.dtd” which contains the DTD:

<!ELEMENT tutorials (tutorial+)>


<!ELEMENT tutorial (name,url*)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT url (#PCDATA)>
<!ATTLIST tutorials type CDATA #REQUIRED>

110
DTD entities:
Entities are used as containers which will be filled with some form of content.
The content may be included in the XML file, an internal entity, or stored in
another file, an external entity. As with attributes and elements, entities may be
either parsed or non-parsed. All complex data items which do not need to pass
through the XML parser should be defined as non-parsed.
There are two types of entities. They are:
1) Internal Entities.
2) External Entities.

1) Internal Entities:
Internal entities associate a name with a string of literal text.
They allow us to define shortcuts for frequently typed text or text that is
expected to change.
The XML specification predefined internal entities are
&lt; produces the left angle bracket <
&gt; produces the right angle bracket >
&amp; produces the ampersand &
&apos; produces a single quote character (an apostrophe) ‘
&quot; produces a double quote character “
&copy; produces copyright symbol ©
User defined entities :
Syntax : <! ENTITY entity-name “entity-value”>

DTD example:
<!ENTITY writer "harish">
<! ENTITY pos “pinch of salt”>

XML example:
<author >&writer;&copy;</author>
<item> Finally add &pos;</item>

2) External entities:
External entities associate a name with the content of another
file. They allow an XML document to refer to the contents of another file.

Syntax: <! ENTITY entity-name SYSTEM/PUBLIC “URL”>

DTD example:
<! ENTITY writer SYSTEM “mydocument.xml”>

111
The writer entity is defined in mydocument.xml file.
<! ENTITY writer PUBLIC “http://www.xml.com/entities/entities.xml”>

5.Write about XML Namespaces?

XML document allow us to create our own XML elements with our own
element
names. This can result in naming collisions i.e., different xml elements can have
the same name in one xml document.

Example:

<?xml version="1.0"?>
<college>
<staff>
<name>rajesh</name>
<dept>cse</dept>
</staff>
<student>
<name>harish</name>
<dept>cse</dept>
</student>
</college>

From the above example it is clear that the xml elements say the name and dept
of both staff and student starting element have the common element (name and
dept). This could provide the naming collisions. To solve such problem in the XML
documents, we use the XML Namespaces.

The XML namespaces provides us to prevent collisions by differentiating these


two elements by using namespace prefixes staff before name and dept and for
student name and dept use student in front of name and dept. This can be seen
as follows:

<?xml version="1.0"?>
<college xmlns:staff="java book.textinfo"
xmlns:student="web technologies book.studentinfo">
<staff>
<staff:name>rajesh</staff:name>
<staff:dept>cse</staff:dept>
</staff>
<student>
112
<student:name>harish</student:name>
<student:dept>cse</student:dept>
</student>
</college>

XML namespaces uses the keyword xmlns to create namespaces prefixes and
assign corresponding URL that uniquely identifies the namespace. For example,
the string “java and web technologies book. tectinfo” could be a URL for a
namespace that contains elements and attributes related to java and web
technologies.

In the above program to get the file and description of the staff and student of
the book, we have prefixed with the namespace staff. So it searches it in
javabook. textinfo. Similarly, we have prefixed with the namespace student. So it
searches student in web technologies book. studentinfo.

5. Explain about various XSL elements?

XSL can be used to define how an XML file should be displayed by


transforming the XML file into a format that is recognizable to a browser. Once
such format is HTML. Normally XSL does this by transforming each XML element
into an HTML element.
XSL can also add completely new elements into the output file, or remove
elements. It can rearrange and sort the elements, test and make decisions about
which element to display, and a lot more.
There are various elements that can be used with XSL.

Element Description

xsl:value-of Extracts the value of a selected node.


xsl:element Creates an element in the output
document.
xsl:script Global variables and functions can be
declared within a template.
xsl:stylesheet Define the root element of the style sheet.
xsl:template Defines a single template for output based
on a specific pattern.
xsl:comment A comment is added to the output
document. The application will usually not
display.
xsl:copy Creates a copy of the Current node (XML
113
element) without child nodes and
attributes.
xsl:copy-of Creates a copy of the current node with
child nodes and attributes.
xsl:import Imports the content of one style sheet into
another.
xsl:message Write a message to the output.
xsl:transform Define the root element of the style sheet.
xsl:variable Declares a local or global variable.
xsl:attribute Allows to create an attribute node
Xsl: for-each Element selects a set of nodes and
processes each of them.
Ex:
<xsl:stylesheet xmlns:xsl=http://www.w3.org/transform version=”1.0”>
<xsl: template match=”/”>
<xsl:for-each select=”programmer”>
<xsl:element name=”staff-member>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

6. Explain about presenting XML ?


We can Present XML in two ways.
1. Presenting XML with Extensible Style Sheet Language (XSL):

XML also has it's own styles language - XSL. XSL stands for Extensible Styles
Language and is a very powerful language for applying styles to XML documents.
XSL has two parts — a formatting language and a transformation language.
The formatting language allows you to apply styles similar to
what CSS does. Browser support for the XSL formatting language is limited at this
stage.
The transformation language is known as XSLT (XSL Transformations). XSLT
allows you to transform your XML document into another form. For example, you
could use XSLT to dynamically output some (or all) of the contents of your XML
file into an HTML document containing other content.
Example:
sri.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="URI:xsl">
<xsl:template>
<html>
114
<body>
<table border="1" bgcolor="yellow">
<tr>
<th>name</th>
<th>pnone no</th>
<th>Email id</th>
</tr>
<xsl:for-each select="Contacts/contact">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="phoneno"/></td>
<td><xsl:value-of select="emailid"/></td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
Jkc.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sri.xsl"?>
<Contacts>
<contact>
<name>rajesh</name>
<phoneno>123456</phoneno>
<emailid>[email protected]</emailid>
</contact>
</Contacts>
<contact>
<name> Anand</name>
<phoneno> 123456</phoneno>
<emailid>[email protected]</emailid>
</contact>
</Contacts>

The root element that declares the document to be an XSL style sheet is
<xsl:stylesheet> or <xsl:transform>
The XSL style sheet is linked to the XML document using the following statement:
<?xml:stylesheet type="text/xsl" href="sri.xsl"?>

115
An XSL style sheet consists of one or more set of rules called templates. Each
template contains rules to apply when a specific node is matched. The
<xsl:template> element is used to create templates.

The <xsl:value of> element is used to extract the value of an XML element and
add it to the output stream of transformation.
The <xsl:for-each> element allows to select every XML element of specified node-
set.

2. Presenting XML with Cascading Style sheets (CSS)

Formatting XML using XSL means that you need a complex processor to get any
meaningful output. Generally, at the moment, we are converting XML into HTML.
Some web browsers are able to parse XML, although those parsing capabilities
may quite limit.

We used CSS to apply styles to the contents of our XML document. Applying
styles improved the look of our document when viewing it with a browser. The
formatting language allows you to apply styles similar to what CSS does. Browser
support for the XSL formatting language is limited at this stage.

Example presenting xml using css:

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml-stylesheet type="text/css" href="jkc.css"?>
<CATALOG>
<BOOK>
<TITLE>Web programming</TITLE>
<AUTHOR>Chris Bates</AUTHOR>
<COUNTRY>INDIA</COUNTRY>
<PUBLISHER>Wiley India pvt ltd</PUBLISHER>
<PRICE>245RS</PRICE>
<YEAR>1985</YEAR>
</BOOK>

<BOOK>
<TITLE>LET US ‘C’</TITLE>
<AUTHOR>Yeswanth Kanitkar</AUTHOR>
<COUNTRY>INDIA</COUNTRY>
<PUBLISHER >TATA MAGRILL</PUBLISHER >
<PRICE>325RS</PRICE>
<YEAR>1975</YEAR>
116
</BOOK>
</CATALOG>

jkc.css:
CATALOG
{
background-color:yellow;
}
BOOK
{
display: block;
margin-bottom: 30pt;
margin-left: 0;
}
TITLE
{
color:red;
font-size: 20pt;
}
AUTHOR
{
color:brown;
font-size: 20pt;
}
COUNTRY,PRICE,YEAR,PUBLISHER
{
display: block;
color:green;
margin-left: 20pt;
}

XML Parsers
An XML parser is a software library or package that provides interfaces for client
applications to work with an XML document. The XML Parser is designed to read the
XML and create a way for programs to use XML.

XML parser validates the document and check that the document is well formatted.

Let's understand the working of XML parser by the figure given below:

Let's understand the working of XML parser by the figure given below:

117
Types of XML Parsers
These are the two main types of XML Parsers:

1. DOM
2. SAX

DOM (Document Object Model)


A DOM document is an object which contains all the information of an XML document.
It is composed like a tree structure. The DOM Parser implements a DOM API. This API is
very simple to use.

Features of DOM Parser


A DOM Parser creates an internal structure in memory which is a DOM document object
and the client applications get information of the original XML document by invoking
methods on this document object.

DOM Parser has a tree based structure.

Advantages
1) It supports both read and write operations and the API is very simple to use.

2) It is preferred when random access to widely separated parts of a document is


required.

Disadvantages
1) It is memory inefficient. (consumes more memory because the whole XML document
needs to loaded into memory).

118
2) It is comparatively slower than other parsers.

SAX (Simple API for XML)


A SAX Parser implements SAX API. This API is an event based API and less intuitive.

Features of SAX Parser


It does not create any internal structure.

Clients does not know what methods to call, they just overrides the methods of the API
and place his own code inside method.

It is an event based parser, it works like an event handler in Java.

Advantages
1) It is simple and memory efficient.

2) It is very fast and works for huge documents.

Disadvantages
1) It is event-based so its API is less intuitive.

2) Clients never know the full information because the data is broken into pieces.

119

You might also like