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

Advanced Web Tech Notes

The document provides an introduction to HTML, explaining its purpose as a markup language for creating web pages and its platform-independent nature. It details the basic structure of an HTML document, including essential tags like <html>, <head>, <title>, and <body>, along with various attributes and formatting options for text. Additionally, it covers different types of lists and how to customize them using HTML tags.

Uploaded by

ayushmehta091
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Advanced Web Tech Notes

The document provides an introduction to HTML, explaining its purpose as a markup language for creating web pages and its platform-independent nature. It details the basic structure of an HTML document, including essential tags like <html>, <head>, <title>, and <body>, along with various attributes and formatting options for text. Additionally, it covers different types of lists and how to customize them using HTML tags.

Uploaded by

ayushmehta091
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 149

WEB TECHNOLOGIES

UNIT I
INTRODUCTION TO HTML
INTRODUCTION:
HTML stands for Hypertext Markup Language. It is a Language used to create Web
Pages or Hypertext document. A Markup Language is a set of instructions often called TAGS
which can be added to text files. HTML is only a formatting language are not a programming
language. The idea behind hypertext is that instead of reading text in a right linear structure we
can easily jump from one point to another point.HTML is all about specifying the structure and
format of our webpage i.e, it is mainly used for describing the structure document.
HTML is platform independent i.e, for example if we can access internet, we can access
WORLD WIDE WEB (WWW) irrespective of client OS and OS of the webserver are accessing.
So, we can view one download HTML files on www through browser.
Elements of a web document are labelled through the usage of HTML tags. It is the tags
that describe the document. Anything that is not a tag will be displayed in the document itself.
HTML does not describe any page layout i.e, for example, word for windows have different
styles for headings, font size etc. But HTML doesn’t have all these. Based on the Platforms,
appearance of any element will change. The formatted text will appear differently on different
machines / Platforms. By separating the Structure of the document and appearance, a Program
that reads and Understands HTML can make formatting decision based on capabilities of
individual Platform. Web Browsers are best examples of HTML formatters.
Advantages of HTML:-
• A HTML document is small and hence easy to send over the net. It is small because it
doesn’t include format information.
• HTML documents are cross platform compatible and device independent. We need
a HTML readable browser to view them.

Basic HTML tags:-


(1) <!doctype> :
This tag formally starts an HTML document and it also indicates the version of HTML
used.

2
WEB TECHNOLOGIES

<!doctype HTML PUBLIC “//w3c//DTDHTML Q.o//EN”>


(2) <HTML>:
Every HTML document starts with a <html> tag and it is always the firsttag in a html
page and indicates that the document is a HTML document.The end tag <html> is
</html>.
Example:
<html> ......... </html>
(3) <head>:
It contains the head of an html document, which holds about the document such as title.
Each property defined html page should have a head which we create with <head> tag.
It has header information and it isdisplayed at the top of the browser. Each tag for
<head> is </head>.
<head> ........ </head>
(4) <title>:
It contains the title of the html document which includes the content thatwill actually
appear in the web browser. The entire content of the web page is placed in the pages
<body> tag. The end tag <body> is </body>
<title> ........ </title>
(5) <body>:
It contains the body of the HTML Document , which includes the contentthat will
actuall appear in the web browser. The entire content of the webpage will be placed in
the pages <body> tag. The end tag of the
<body> tag will be </body>.
<body>........... </body>
STRUCTURE OF THE HTML PROGRAM:-
The HTML Program is generally divided into two sections i.e head and body. Weuse
<head> and <body> tags to indicate these two sections. <head> section holds the header
information of a webpage document indicated by a title that is provided by using <title> tag in
the <head>. The title helps us to referto the webpage. <body> section contains the content which

3
WEB TECHNOLOGIES

we want to display which the webpage.Anything that is not a tag will be displayed within the
webpage.
Example:
<html>
<head>
<title>First Webpage</title>

</head>
<body>
This is my first page
</body>
</html>
Output:

Attribute:
An Attribute is a Keyword we use in an opening tag to give more information tothe web
browser. HTML tags tell the web browsers how to format and organizeour webpages. But we
can customize tags using attributes. The Format of an attribute is:
<tagname Attribute=value>
Attributes of the <body> tag:
(1) Background:

4
WEB TECHNOLOGIES

The URL or a graphic file to be used in the filling the browser’sBackground.


(2) Bgcolor:
The color of the browser’s background.
(3) Bgproperties:
It Indicates if the background should scroll when text does. If we set it to“FIXED”,
the background will not scroll when the text does.
(4) Bottommargin:
Specifies the bottom margin ,the empty space at the bottom of the documentin pixels.

(5) Id:
It is a unique alphanumeric identifier for the tag which we can use to refer toit.
(6) Language:
Scripting language used for the tag.
(7) Leftmargin:
Specifies the left margin, the empty space at the left of the document.
(8) Marginheight:
Gives the height of the margin at the top and bottom of the page in pixels.
(9) MarginWidth:
Gives the width of the left and right margins of the page in pixels.
(10) Rightmargin:
It specifies the right margin, the empty space to the right margin of thedocument in pixels.
(11) Scroll:
It specifies whether a vertical scrollbar appears to the right of the documentcan be yes
(or) no.
(12) Style:
Inline style indicating how to render the element.

(13) Text:
Color of the in the document.

5
WEB TECHNOLOGIES

(14) Topmargin:
It specifies the top margin the space at the top of the document in pixels.
(15) Link:
It specifies the color of hyperlinks that have not yet been visited.
(16) Alink:
It specifies the color of hyperlinks as they are being clicked.
(17) Vlink:
It specifies the color of hyperlinks as they have been visited.
(18)<! ------ > Comment tag:
Annotates a web page with a comment. In the HTML that we can by lookingat the HTML
but it will not be displayed in the web browser.
<! ------ This is a comment --------- >
Formatting with HTML tags:
To set the actual style of text as displayed in a web page we can text style tags.There are a
number of ways to apply styles to text.
(1) <b>:
It creates a bold text i.e, sets the text style to bold.
Attributes:
a. Id:
It is a unique alphanumeric identifier for the tag which we can use to refer toit.
b. Style:
The Inline style indicating how to render the element.
Example:
<html>
<head>
<title>Using Bold Tag </title>
</head>
<body bgcolor=”pink”>
Here is some text displayed as <b> Bold Text </b>

6
WEB TECHNOLOGIES

</body>
</html>
Output:

(2) <I>:
It displays text in Italics.(3)
<U>:
It displays text in Underlined text. (4)
<P>:
It displays the Paragraph text.
Example:
<html>
<head>
<title> Using Styles </title>
</head>
<body bgcolor=”pink”>
<p> This is a paragraph <br>
Here is some text that is <i> Displayed in Italics </i>
<br>Here is some <u> Underlined text </u>
</body>
</html>

7
WEB TECHNOLOGIES

Output:

(5) <s> and <strike>:


It Displays text in smile through style. The <s> and <style> tags are used forthe same
effect. HTML 2 used <strike> , HTML 3 called it <s>, HTML 3.2 caused it <strike> again.
(6) <big>:
Renders text in a bigger font than the current default.
(7) <small>:
Renders text in a smaller font than the current default.
Example:
<html>
<head>
<title> Using Big and small tags </title>
</head>
<body>
Here is some text that is <big> Bigger than the normal </big> <br>and here is
some text that is <small> smaller than normal </small>
</body>
</html>

8
WEB TECHNOLOGIES

Output:

(8) <sub>: It Styles the text as a subscript.


(9) <sup>: It Styles the text as a superscript.
(10) <strong>: Emphasizes text strongly, usually rendered in bold.
Example:
<html>
<head>
<title>Using Styles </title>
</head>
<body bgcolor=”pink”>
H <sub> 2 </sub> SO <sub> 4 </sub> H
<sub> 2 </sub> O
<br>
<b>Here is some text that appears as a <sup> Super </sup> Script <br>Here is some
<strong> strong </strong> text.
</body>
</html>
Output:

9
WEB TECHNOLOGIES

(11) Headings:
<h1>,<h2>,<h3>,<h4>,<h5> & <h6>
The heading element tags are <h1>,<h2>,<h3>,<h4>,<h5><h6>. These elements create
the headings in our web pages by displaying bold text in avariety of sizes <h1> being
larger <h6> being smaller.
Example:
<html>
<head>
<title> Heading tags </title>
</head>
<body bgcolor=”pink”>
<center>
<h1> Using Heading Tags</h1><br>
<h1> RGMCET </h1><br>
<h2> RGMCET </h2><br>
<h3> RGMCET </h3><br>
<h4> RGMCET </h4><br>
<h5> RGMCET </h5><br>

10
WEB TECHNOLOGIES

<h6> RGMCET </h6><br>


</center>
</body>
</html>
Output

(12) <font>:
This tag will give us an option to select text size, color and face.
Attributes:
a. color: Color of the text.
b. Size: Size of the text in points
c. Face: The font face can be a list of names separated by commas.
d. Id: Unique alphanumeric identifier for a tag, which we can use to refer to it.
Example:

11
WEB TECHNOLOGIES

<html>
<head>
<title> Using Font Styles </title>
</head>
<body bgcolor=”pink”>
<center>
<font size=”1” color=”red”> The Font Size is 1 </font> <br>
<font size=”10” color=”yellow”> The Font Size is 10 </font> <br>
<font size=”20” color=”orange”> The Font Size is 20</font> <br>
<font size=”30” color=”aqua”> The Font Size is 30 </font> <br>
</center>
</body>
</html>
Output

(13) <marquee> tag:


Displays scrolling text in a marquee style.
Attributes:
a. Align:
Sets the alignment of the text relative to marquee.Set to:

12
WEB TECHNOLOGIES

Top(default), middle (or) bottom.


b. behavior:
Sets how the text in the marquee should move can be scroll (default), slide(text enters
from one side and stops at the other side), alternate (text seemsto bounce from one side
to the other).
c. bgcolor:
It sets the background color for the marquee box.
d. Direction:
Sets the direction the text should scroll can be left, right, down or up.
e. Height:
It specifies the height of the marquee.
f. Loop:
Sets how many times we want the marquee to cycle. Is set to positive integeror -1 for
continuous cycling.
g. Scrolldelay:
Sets the number of the milliseconds between each successive display text.
Example:
<html>
<head>
<title> Marquee tag </title>
</head>
<body bgcolor=”pink”>
<marquee align=”top” loop=”infinite” behavior=”scroll” bgcolor=”red”
direction=”right”> <h3> The Text Scrolls </h3></marquee>
<marquee align=”middle” loop=”infinite” behavior=”slide” bgcolor=”blue”
direction=”left”> <h3> The Text Scrolls </h3></marquee>
</body>
</html>
Output

13
WEB TECHNOLOGIES

(14) <pre> tag(preformatted text):


<pre> marks the text as preformatted text i.e, all the spaces and carriage returns as
rendered exactly as you type them.
Example:
<html>
<head>
<title> Pre Tag </title>
</head>
<body bgcolor=”pink”>
<center>
<h4> Example of preformatted text </h4> <br> <br>
<pre>

SNo Name Designation


1. aaaa Manager
2. bbbb Project Lead
3. cccc Team Lead
4. dddd S/w Engineer
</pre>

14
WEB TECHNOLOGIES

</center>
</body>
</html>
Output:

Lists:
Lists lets us display information in a compact, right format. There are three kindsof lists:
1. Unordered List
2. Ordered List
3. Definition List
Unordered List:
An Unordered list is a list of items that are marked with burden. The Unordered list is
created by using <ul>tag are the list items in the list are createdby </ul> tag and the list items in
the list are created by <li> tag.
<ul>
<li>List Item 1 </li>
<li>List Item 2 </li>
</ul>
Example:
<html>

15
WEB TECHNOLOGIES

<head>
<title> Creating Unorder List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Unorder List</h1>
<h1 align=”center”>List of Colleges in Kurnool</h1>
<ul>
<li>GPREC</li>
<li>RGMCET</li>
<li>GPCET</li>
</ul>
</body>
</html>
Output

Creating Customized Unordered Lists:


We customized unordered lists by setting the “Type” attribute to three different values. DISC
(default), SQUARE and CIRCLE which sets the type of bullet thatappears before the list item.

16
WEB TECHNOLOGIES

Example:
<html>
<head>
<title> Creating Unorder List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Unorder List</h1>
<h1 align=”center”>List of Colleges in Kurnool</h1>
<ul type=”square”>
<li>GPREC</li>
<li>RGMCET</li>
<li>GPCET</li>
</ul>
</body>
</html>
Output

Ordered List:
While the unordered lists display simple bullet before each list item. Ordered lists use a number
system / lettering scheme to indicate that the items are ordered in some ways, ordered lists are

17
WEB TECHNOLOGIES

created by <ol> tag and the list items are created using
<li> tag.
Example:
<html>
<head>
<title> Creating Order List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Order List</h1>
<h1 align=”center”>List of branches in RGMCET</h1>
<ol>
<li>CSE</li>
<li>IT</li>
<li>ECE</li>
<li>EEE</li>
<li>CIVIL</li>
<li>ME</li>
</ol>
</body>
</html>
Output

18
WEB TECHNOLOGIES

Creating Customized Ordered Lists:-


We can customize the numbering system used in ordered lists by using the TYPEattribute, which
we can set to these values:
1. Default numbering system (1, 2, 3, ….)
A. Uppercase Letters (A, B, C, …..)
a. Lowercase Letters (a, b, c, …)
I. Large Roman Numerals (I, II , III, ….)
i. Small Roman Numerals (i, ii, iii, …..)
Example:
<html>
<head>
<title> Creating Order List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Order List</h1>
<h1 align=”center”>List of branches in RGMCET</h1>

19
WEB TECHNOLOGIES

<ol type=”A”>
<li>CSE</li>
<li>IT</li>
<li>ECE</li>
<li>EEE</li>
<li>CIVIL</li>
<li>ME</li>
</ol>
</body>
</html>
Output

Definition List:-
These lists include both definition terms as well as their definition. To create the definition lists
we use <dl> tag. For creating definition terms we use <dt> tag andfor data definitions we use
<dd> tag.
Example:
<html>
<head>
<title>Creating Definition List</title>

20
WEB TECHNOLOGIES

</head>
<body bgcolo=”pink”>
<h1 align=”center”>Definition List</h1>
<dl>
<dt>CSE<dd>Computer Science & Engineering
<dt>ECE<dd>Electronics & Communication Engineering
<dt>IT<dd>Information Technology
<dt>EEE<dd>Electrical & Electronics Engineering
<dt>CE<dd>Civil Engineering
</dl>
</body>
</html>
Output

Nesting Lists:-

21
WEB TECHNOLOGIES

We have the capability of nesting lists inside other lists.


Example:
<html>
<head>
<title>Nested Lists</title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”>List of Colleges in Kurnool</h1>
<ol>
<li>Kurnool</li>
<ul>
<li>GPREC</li>
<li>BITS</li>
<li>GPCET</li>
</ul>
<li>Nandyala</li>
<ul>
<li>RGMCET</li>
<li>SREC</li>
</ul>
</ol>
</body>
</html>
Output

22
WEB TECHNOLOGIES

Creating Hyperlinks:
What makes the web so effective is the ability to define links from one page to another. In web
terms, a “hyperlinks” is a reference on the web. Hyperlinks can point to any resources on the
web. An anchor is a term used to define a hyperlinkdestination inside a document. Format of
anchor tag is:
<a href=”address”> Line Text </a>
The <a> anchor tag has the following attributes.
1. href: It holds the target URL of the hyperlink.
2. Id: A unique alphanumeric identifier for the tag, which we can use to refer toit.
3. name: It specifies an anchor name, the name we want to use when referringto enclose
items.
4. Target: This attribute defines where the linked document will be opened.
Example:
<html>
<head>
<title>Creating Hyper Links</title>

23
WEB TECHNOLOGIES

</head>
<body bgcolor="pink">
<center><h1>This is page 1</h1>
<a href=”page2.html”>Click here</a>to goto page2
</center>
</body>
</html>
Output

24
WEB TECHNOLOGIES

Setting hyperlink colors:


The default color of hyperlinks in a page is blue. Hyperlink that we have already visited are
displayed in violet and when we click a hyperlink,it turns red when themouse button is down.We
can set these colos in <body> tag attributes link,vlink(visited link),alink(active link).
Example
<html>
<head>
<title>Setting Hyperlink colors</title>
</head>
<body bgcolor="pink" link=”green” vlink=”blue” alink=”red”>
<center><h1>Setting Hyperlink colors</h1>
<a href=”login.html”>Click here</a>to goto login page
</body>
</html>
Output

25
WEB TECHNOLOGIES

Providing navigation with in the page:


<html>
<head>
<title>Nested Lists</title>
</head>
<body bgcolor="pink">
<center><h1>Linking to a section in a page</h1>
<a name=”top”>This is the top of the page</a>
Click here to goto the <a target=”#bottom”>bottom</a>of the page
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br>
<a name=”bottom”>This is the bottom of the page</a> Click here to
goto <a target=”#top”>top</a>of the page
</center>
</body>
</html>
Output

26
WEB TECHNOLOGIES

Creating HML tables:


A HTML table arranges data/information in terms of rows and columns.Tables are defined in
HTML using <table> tag.A table is divided into rows and each row each divided into data
cells(columns).The rows of table are created using <tr> tag and data cells are created by <td> tag.
<tr> - Table row
<td> - Table data
Format
<table>
<tr>
<td>row1,col1</td>
<td>row1,col2</td>
</tr>
<tr>
<td>row2,col1</td>
<td>row2,col2</td>
</tr>
</table>
• Heading in a table are defined with <th> tag
Format
<table>
<tr>
<th>heading 1</th>
<th>heading 2</th>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
</tr>
</table>
Attributes of <table> tag:

27
WEB TECHNOLOGIES

• align : specifies the horizontal alignment of the table in the browserwindow,set


to ”left,center,right”.
• background : specifies the URL of a background image to be used asbackground
for the table.
• bgcolor : sets the background color of the table cells.
• border : sets the border width.
• bordercolor : sets the external border color of the entire table.
• cellpadding : sets the spacing between cell walls and content.
• cellspacing : sets the spacing between table cells.
• height : sets the height of the whole table.
• width : sets the width of the table.
Attributes of <tr> tag:
• align : specifies the horizontal alignment content in the table cells set to
“left,center,right”.
• bgcolor : sets the background color of the table cells.
• bordercolor : sets the external border color of the entire table.
• Valign : sets the vertical alignment of data,set to top,middle,bottom.
Alignment of <td> tag
• align : specifies the horizontal alignment content in the table cells set to
“left,center,right”.
• bgcolor : sets the background color of the table cells.
• bordercolor : sets the external border color of the entire table.
• colspan : indicates the how many cell columns of the table this cell shouldspan.
• rowspan : indicates the how many cell rows of the table this cell shouldspan.
Example
<html>
<head>

28
WEB TECHNOLOGIES

<title>Creating Tables</title>
</head>
<body bgcolor="pink">
<center><h1>Creating tables</h1>
<table border=”1” cellpadding=”3” cellspacing=”3”>
<tr>
<th colspa=”2”>Websites</th>
</tr>
<tr>
<td>Mail sites</td>
<td>Job sites</td>
</tr>
<tr>
<td>Gmail.com</td>
<td>Frushersworld.com</td>
</tr>
<tr>
<td>Yahoo.com</td>
<td>Nauted.com</td>
</tr>
</center>
</table> </body></html>

29
WEB TECHNOLOGIES

Output

Advanced Table elements :


• <caption> : the element is an ptional element and it used to provide a string which
describes,the contern of the table ,it must follow the table element.
• <thead> : The rows in a table can bc groudated one are more time we cancreate a table
by using this <thead>.
• <tbody> : creates a table body when grouping rows.
• <tfoot> : Creates a table foot when groupin rows
Example:
<html>
<head>
<title>Advance Table Elements</title>
</head>
<body bgcolor="pink">
<h1 align="center">Contents of Web Technologies</h1>
<center>
<table border="2">

30
WEB TECHNOLOGIES

<caption>Subject Description</caption>
<thead>
<tr> <td colspan="2">Advance Java Programming</td>
</thead>
<tbody>
<tr> <td>Units</td>
<td>Contents</td>
</tr>
<tr> <td>I</td>
<td>HTML & CSS</td>
</tr>
<tr> <td>II</td>
<td>JavaScript</td>
</tr>
<tr> <td>III</td>
<td>XML</td>
</tr>
</tbody>
<tfoot align="center">
<tr>
<td colspan="2">The table foot</td>
</tr>
</tfoot>
</table>
</center>
</body>
</html>
Output

31
WEB TECHNOLOGIES

Nesting of Tables:
<html>
<head>
<title>Nesting of Tables</title>
</head>
<body bgcolor="pink">
<center><h1>Nested tables</h1>
<table border="1" cellpadding="3" cellspacing="3">
<tr>
<td>
<table border="2">
<tr>
<th>Mail sites</th>
<th>Job sites</th>
</tr>

32
WEB TECHNOLOGIES

<tr>
<td>Gmail.com</td>
<td>Frushersworld.com</td>
</tr>
<tr>
<td>Yahoo.com</td>
<td>Nauted.com</td>
</tr>
</table>
</td>
<td>
<table border="2">
<tr>
<th>Number</th>
<th>Words</th>
</tr>
<tr>
<th>1</th>
<th>One</th>
</tr>
<tr>
<th>2</th>
<th>Two</th>
</tr>
</table>
</td>
</tr>
</table>
</center>
</body>

33
WEB TECHNOLOGIES

</html>
Output

Images in HMTL:
In HTML we have the capability of displaying images in a webpage.This imagesmust be in a
format that the web browser can handle , such as Graphics Interchange Format(GIF) , Joint
Photograph Expert Group(JPEG) , and for somebrowser Portable Network Graphics(PNG)
formats.
Displaying images in webpage is done by using <img> tag
Format
<img src=”URL of image source”>
Attributes of <img> tag:
• alt : this attribute is used to specify text to be displayed in place of image forbrowser that
cannot handle graphics.
• src : specifies the URL of the image to display.
• border : sets the border for the image.
• height : indicates the height of the image.
• width : indicates the width of the image.

34
WEB TECHNOLOGIES

• hspace : sets the horizontal space around the image.


• vspace : sets the vertical space around the image.
Example
<html>
<head>
<title>Images</title>
</head>
<body bgcolor="pink">
<center>
<h1>Images Example</h1>
<h3>Here is an image</h3>
<img src="one.jpg" alt="here is an image" width="300" height="150">
</center>
</body>
</html>
Output

35
WEB TECHNOLOGIES

Adding borders and spaces around image:


<html>
<head>
<title>Borders & Spaces</title>
</head>
<body bgcolor="pink">
<center>
<h1>Adding border & spacing image</h1>
<h3>Here is an image</h3>
<img src="one.jpg" alt="here is an image" width="100" height="100"
hspace="50" vspace="50" border="8">
<img src="two.png" alt="here is an image" width="100" height="100"
hspace="50" vspace="50" border="8">
<img src="three.png" alt="here is an image" width="100" height="100"
hspace="50" vspace="50" border="8">
</center>
</body>
</html>
Output:

36
WEB TECHNOLOGIES

Creating HTML Forms:


Form is a collection of various HTML control files , buttons ,checkboxes , radio buttons ,text
fields et., and they use to send the data to the server. There are severalform elements.
• Button : <input type=”button”> :- are the standard clickable buttons.
• Checkbox : <input type=”checkbox”> :- displayed usually as a small boxwith a check
mark in it. The use can toggle the checkbox on or off by checking the checkbox
• Customizable Buttons : <button> :- display images one other HMTL insideitself.
• File uploading controls : <input type=”file”> :- allow the user to upload filesto the server.
• Hidden controls : store data that is not visible to users unless they view theweb page
source code.
• Image controls : <input type=”image”> :- are like submit buttons except thatthey are
images the user can click.
• Password controls : <input type=”password”> :- are like text fields , buteach typed
character displaying by an asterisk or instead any character.

37
WEB TECHNOLOGIES

• Radio buttons : <input type=”radio”> :- displaying usually as a circle whichwhen selected


displayed a dot in the middle. These controls are much like checkboxes except that they
work int mutually exclusive at a time.
• Reset button : <input type=”reset”> : - allow the user to clear all the data they has
entered.When the user click reset button all controls in the form areremoved to that
original state displaying the data they had when they first appeared.
• Selection : Works much like drop down list boxes also called select controlsFormat is:
<select>
<option>Item1</option>
<option>Item1</option>
<option>Item1</option>
</select>
• Submit button : when we click the button all the data in the form will be sentto web server
for processing.
• Text area : are two dimensional text fields allowing user to enter more thanone line of
text.
Format is: <textarea>
• Text fields : allow the user to enter one line of text also called a textboxFormat is :
<input type=”text”>
In order to create form we use <form> tagFormat
is :
<form>
|
|
</form>
Attributes of <form> tag:
• name : gives the name of the form so that we can return it in code . Set to analphanumeric
string.
• target : indicates a named frame for browser to display the form results.

38
WEB TECHNOLOGIES

• method : indicates a method or protocol for sending data to the target actionURL.
• action : gives the URL that that will handle the form data.
Example
Registration.html
<html>
<head>
<title>HTML Form</title>
</head>
<body bgcolor="pink">
<center>
<form name="form1">
<table border="0" cellpadding="4" cellspacing="4">
<caption>Registration form</caption>
<tr>
<th>Name</th>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password"/></td>
</tr>
<tr>
<th>Enter your address</th>
<td><textarea rows="5" cols="10"></textarea></td>
</tr>
<tr>
<th>Enter your email</th>
<td><input type="email"/></td>
</tr>
<tr>

39
WEB TECHNOLOGIES

<th>Enter your mobile</th>


<td><input type="number"/></td>
</tr>
<tr>
<th>Select your gender</th>
<td>
male<input type="radio" name="g" value="m"/>
female<input type="radio" name="g" value="f"/>
</td>
</tr>
<tr>
<th>Language prference</th>
<td>
English<input type="checkbox" value=" "/>
Telugu<input type="checkbox" value=" "/>
Hindi<input type="checkbox" value=" "/>
</td>
</tr>
<tr>
<th>Select your DOB</th>
<td><input type="date"/></td>
</tr>
<tr>
<td ><input type="submit" value="Register"/></td>
<td><input type="reset" value="Cancel"/></td>
</td>
</tr>
</table>
</form>
</body>

40
WEB TECHNOLOGIES

</html>
Output

Working with Frames:


HMTL frames allow user to present documents in multiple views which may beindependent
windows or sub windows. To divide a webpage into multiple parts and load different pages in a
single web page we use the concept of frames. To dothis we use “<frameset>” tag which indicates
the browser that the webpage window has a frame. We can divide it into rows and columns by
using attributes such as ‘rows’ & ‘cols’. In order to provide definition or each frame we use
“<frame>” tag.
Format is :
<frameset rows=”30%,70%”>
<frame src=”source page URL” name=”frame name”>
<frame src=”source page URL” name=”frame name”>
</frameset>
• <frameset> element actually takes place of <body> tag.

41
WEB TECHNOLOGIES

Attributes of <frameset> tag:


• border : used in the outermost <frameset> tag to set the border thickness forframes.
• bordercolor : set the color of the borders for all frames in the frameset.
• frameborder : set whether or not border for all frames in the frameset.Can be set
to ‘yes’ or ‘no’ or ‘1’ or ‘0’.
• framespacing : set the pixel spacing between frames. set to the positiveintegers.
• cols : set the number of columns in the frameset. Separate the values assigned to this
attribute with comma(,) each value represents width of acolumn. Can be set to pixel
values,percentages.
• Rows : set the number of rows in the frameset. Separate the values assigned to this attribute
with comma(,) each value represents width of a column. Can be set to pixel
values,percentages.
Attributes of <frame> tag:
• bordercolor : set the color used for the frmae border. This setting overridesthe color
specified in the surrounding <frameset> element.
• frameborder : sets whether or not border surround the frame. Can be set to‘yes’ or ‘no’
or ‘1’ or ‘0’.
• name : sets the name of the frame we can use named frames as target for <a>tag.
• scrolling : determines scrolling possible values are : auto,yes or no.
• src : specifies the URL of the frame document. If we don’t specify a URLthe frame
will appear blank.
Creating vertical frames:
In order to display vertical frame we have use of ‘cols’ attribute.
Example
<html>
<head>
<title>Vertical Frames</title>
</head>

42
WEB TECHNOLOGIES

<frameset cols="30%,70%">
<frame src=frame1.html>
<frame src=frame2.html>
</frameset>
</html>
Frame1.html
<html>
<head>
<title>page1</title>
</head>
<body>
<h1>Web Technologies</h1>
</body>
</html>
Frame2.html
<html>
<head>
<title>page2</title>
</head>
<body>
<h1>Web Technologies</h1>
</body>
</html>

Output

43
WEB TECHNOLOGIES

Creating horizontal frames:


In order to display horizontal frame we have use of ‘cols’ attribute.
Example
<html>
<head>
<title>Horizontal Frames</title>
</head>
<frameset cols="50%,50%">
<frame src=page1.html>

44
WEB TECHNOLOGIES

<frame src=page2.html>
</frameset>
</html>
page1.html
<html>
<head>
<title>page1</title>
</head>
<body>
<h1 align=”center”>This is page1</h1>
</body>
</html>
page2.html
<html>
<head>
<title>page2</title>
</head>
<body>
<h1 align=”center”>This is page2</h1>
</body>
</html>
Output

45
WEB TECHNOLOGIES

Creating horizontal & vertical frames :


<html>
<head>
<title>Horizontal Frames</title>
</head>
<frameset cols="30%,70%">
<frameset cols="25%,50%,25%">
<frame src=page1.html>
<frame src=page2.html>
<frame src=page3.html>
</frameset>
<frameset cols="25%,50%,25%">
<frame src=frame1.html>
<frame src=frame2.html>
<frame src=frame3.html>
</frameset>
</frameset> </html>

46
WEB TECHNOLOGIES

Output

<noframes> tag:
When the browser does not support frameset use <noframes> element to indicateto users that
the browser doesnot support frames.The <noframes> element is ignored that handle frames.
Example
<html>
<head>
<title>Vertical Frames</title>
</head>
<frameset cols="30%,70%">
<noframes>Your browser does not support frames...</noframes>
<frame src=on.html>
<frame src=two.html>
</frameset>

47
WEB TECHNOLOGIES

</html>
Output

Named frames:
One important aspect of working with frames is using named frames. When wegive frmae a
name , we can use as a target to load new page into the frame.
Example
<html>
<head>
<title>Vertical Frames</title>
</head>
<frameset cols="40%,60%">
<frame src=menu.html>
<frame src=default.html name="display">
</frameset>
</html>

48
WEB TECHNOLOGIES

menu.html
<html>
<head>
<title>Menu</title>
</head>
<body bgcolor="green">
<center><b>Click on below link</b>
<br><a href="page1.html" target="display">Page1
<br><a href="page2.html" target="display">Page2
</center>
</body>
</html>
Defual.html
<html>
<head>
<title>Vertical Frames</title>
</head>
<frameset cols="40%,60%">
<frame src=menu.html>
<frame src=default.html name="display">
</frameset>
</html>
Output

49
WEB TECHNOLOGIES

RGMCET CSE DEPT 50


WEB TecHnologies

Cascading Style Sheets:


Style sheets represent the World Wide Web consortium‟s effort to improve on the tag
andattribute based style of formatting. Style sheets provide a way of customizing whole pages
all at once and in much richer detail than the simple use of tags and attributes. The format of
style sheet will be:
<style type=”text/css”>
selector{property:value;property:value;}
selector{property:value;property:value;}
</style>
Every line in <style> tag is called as a „Rule‟ and a style rule has two parts:
a. Selector.
b. Set of declarations.
A selector is used to create a link between the rule and the HTML tag. The declaration has two parts
again:
a. Property.
b. Value.
A property specifies additional information and value specifies property value. For example:
<style type=”text/css”>
body {background-color: #d0e4fe;}
h1 {
color: orange;
text-align: center;
}
p{
font-family: "Times New Roman";
font-size: 20px;
}
</style>
If we add above code in the <head> element of web page , entire web page will be displayed in

51
WEB TecHnologies

various styles given in style element.


Style sheets are implemented with cascading style sheets specification. Conventionally styles are
cascaded i.e., we don‟t have to use just a single set of styles inside a document, but we can import
as many styles as we like. There are three mechanisms by which we can apply styles to our HTML
documents:
1. Inline Style sheets.
2. Embedded Style sheets.
3. External Style sheets.
Inline Style Sheets:
Inline style sheets mix content with presentation. To use inline styles we use style
attribute in the relevant tag.
Example:
<html>
<head>
<title>HTML Tables</table>
</head>
<body bgcolor=‟pink‟>
<center>
<h1>Creating HTML Tables</h1><br>
<table border=”2” cellpadding=”4” cellspacing=”4”>
<tr>
<th colspan=”2” style=”background-color:red”> WebSites</th>
</tr>
<tr>
<th style=”background-color:blue”>MailSites</th>
<th style=”background-color:green”>JobSites</th>
</tr>
<tr>
<td style=”background-color:grey”>Gmail</td>
<td style=”background-color:aqua”>Naukri</td>

52
WEB TecHnologies

</tr>
<tr>
<td style=”background-color:yellow”>Yahoo</td>
<td style=”background-color:purple”>JobStreet</td>
</tr>
</table>
</center>
</body>
</html>
Output:

Embedded Style sheets:


An embedded style sheet is used when a single document has a unique style. We
define internal styles in the head section of a HTML page by using „<style>‟ tag. The styles
defined using embedded style sheets are applied throughout the page and we put the
styles into oneplace.

53
WEB TecHnologies

Example:
<html>
<head>
<title>Embedded Style sheets</title>
<style type=”text/css”>
body{background-color:
pink;}
h1 {
color:orang
e;
text-align:
center;
}
p{
font-family: "Times New
Roman";
font-size: 20px;
}
</style>
</head>
<body>
<h1>Embedded Style Sheets</h1><br>
<p>This is a paragraph
</body>
</html>
Output:

54
WEB TecHnologies

External Style Sheets:


External style sheets are just that the style sheets are stored separately from our web
page.These are useful especially if we are setting the styles for an entire website. When we
change the styles in external style sheet we change the styles of all pages. We use „<link>‟
element to access the style sheet file defined into our web page. The format of <link> element
is:
<link rel=”stylesheet” type=”text/css” href=”extstylesheet.css”>
Example:
extern.css:
body {background-color: #d0e4fe;}
h1 {
color: orange; text-align: center;
}
p{
font-family: "Times New Roman"; font-size: 20px;
}
extern.html:
<html>
<head>
<title>External Style Sheets</title>

55
WEB TecHnologies

<link rel=”stylesheet” type=”text/css” href=”extern.css”>


</head>
<body>
<h1>External Style Sheets</h1><br>
<p>This is a paragraph
</body>
</html>
Output:

56
WEB TecHnologies

UNIT-II
CSS
Introduction to CSS:
CSS (Cascading Style Sheets) is a language designed to simplify the process of making web pages
presentable. It allows you to apply styles to HTML documents, describing how a webpage should
look by prescribing colors, fonts, spacing, and positioning. CSS provides developers and designers
with powerful control over the presentation of HTML elements.
HTML uses tags and CSS uses rulesets. CSS styles are applied to the HTML element using selectors.
CSS is easy to learn and understand, but it provides powerful control over the presentation of an
HTML document.
CSS (Cascading Style Sheets) is a language for styling HTML or XML documents,

controlling layout, colors, fonts, and overall appearance to enhance user

experience.
Why CSS?
• Saves Time: Write CSS once and reuse it across multiple HTML pages.
• Easy Maintenance: Change the style globally with a single modification.
• Search Engine Friendly: Clean coding technique that improves readability for search engines.
• Superior Styles: Offers a wider array of attributes compared to HTML.
• Offline Browsing: CSS can store web applications locally using offline cache, allowing offline
viewing.
CSS Syntax
CSS consists of style rules that are interpreted by the browser and applied to the corresponding elements. A
style rule set includes a selector and a declaration block.
• Selector: Targets specific HTML elements to apply styles.
• Declaration: Combination of a property and its corresponding value.
• The selector points to the HTML element that you want to style.
• The declaration block contains one or more declarations separated by semicolons.
• Each declaration includes a CSS property name and a value, separated by a colon.

57
WEB TecHnologies
Using CSS: In this example, we will add some CSS styles inside the HTML document to show how CSS
makes a HTML page attractive and user-friendly.

<html>

<head>
<title>Simple web page</title>
<style>
main {
width: 600px;
height: 200px;
padding: 10px;
background: beige;
}

h1 {
color: olivedrab;
border-bottom: 1px dotted darkgreen;
}

p {
font-family: sans-serif;
color: orange;
}
</style>
</head>

<body>
<main>
<h1>My first Page </h1>
<p>This is a basic web page.</p>
</main>
</body>

</html>

CSS Selector
CSS selectors are used to select the content you want to style. Selectors are the part of CSS rule set. CSS
selectors select HTML elements according to its id, class, type, attribute etc.

58
WEB TecHnologies

There are several different types of selectors in CSS.

1. CSS Element Selector


2. CSS Id Selector
3. CSS Class Selector
4. CSS Universal Selector
5. CSS Group Selector

1) CSS Element Selector


The element selector selects the HTML element by name.

1. <html>
2. <head>
3. <style>
4. p{
5. text-align: center;
6. color: blue;
7. }
8. </style>
9. </head>
10. <body>
11. <p>This style will be applied on every paragraph.</p>
12. <p id="para1">Me too!</p>
13. <p>And me!</p>
14. </body>
15. </html>

2) CSS Id Selector
The id selector selects the id attribute of an HTML element to select a specific element. An id is always
unique within the page so it is chosen to select a single, unique element.

59
WEB TecHnologies

It is written with the hash character (#), followed by the id of the element.

Let?s take an example with the id "para1".

1. <html>
2. <head>
3. <style>
4. #para1 {
5. text-align: center;
6. color: blue;
7. }
8. </style>
9. </head>
10. <body>
11. <p id="para1">Hello Javatpoint.com</p>
12. <p>This paragraph will not be affected.</p>
13. </body>
14. </html>

3) CSS Class Selector


The class selector selects HTML elements with a specific class attribute. It is used with a period
character . (full stop symbol) followed by the class name.

1. <html>
2. <head>
3. <style>
4. .center {
5. text-align: center;
6. color: blue;

60
WEB TecHnologies

7. }
8. </style>
9. </head>
10. <body>
11. <h1 class="center">This heading is blue and center-aligned.</h1>
12. <p class="center">This paragraph is blue and center-aligned.</p>
13. </body>
14. </html>

4) CSS Universal Selector


The universal selector is used as a wildcard character. It selects all the elements on the pages.

1. <html>
2. <head>
3. <style>
4. * {
5. color: green;
6. font-size: 20px;
7. }
8. </style>
9. </head>
10. <body>
11. <h2>This is heading</h2>
12. <p>This style will be applied on every paragraph.</p>
13. <p id="para1">Me too!</p>
14. <p>And me!</p>
15. </body>
16. </html>

61
WEB TecHnologies

CSS Combinators
CSS Combinators clarifies the relationship between two selectors, whereas the selectors in CSS are
used to select the content for styling. There can be more than one simple selector in a CSS selector,
and between these selectors, we can include a combinator. Combinators combine the selectors to
provide them a useful relationship and the position of content in the document.

There are four types of combinators in CSS that are listed as follows:

o General sibling selector (~)


o Adjacent sibling selector (+)
o Child selector (>)
o Descendant selector (space)

General Sibling Selector (~)


o It uses the tlide (~) sign as the separator between the elements. It selects the elements that
follow the elements of first selector, and both of them are the children of the same parent. It
can be used for selecting the group of elements that share the common parent element.

It is useful when we have to select the siblings of an element even if they are not adjacent directly.

Syntax

1. element ~ element {
2. /*style properties*/
3. }

Suppose we have to select all <p> elements that are the siblings of <div> element, then we can write
it as:

62
WEB TecHnologies

1. div ~ p {
2. /*style properties*/
3. }

The figure given below helps us to understand the General sibling selector (~).

In this figure, the blocks with the green color are the selected blocks affected after using the general
sibling selector.

Example

In this example we are selecting the <p> elements that come after the <h1>. There is
a <div> element which will not get selected and the paragraph element inside the div will also not get
selected. But those <p>elements that come after the <div> will be affected.

This example will illustrate the use of a General sibling selector (~).

1. <html>
2. <head>
3. <title>General Sibling Selector</title>
4. <style>

63
WEB TecHnologies

5. body{
6. text-align: center;
7. }
8. h1 ~ p{
9. color: blue;
10. font-size: 25px;
11. font-weight: bold;
12. text-align: center;
13. }
14. div {
15. font-size: 32px;
16. }
17. </style>
18. </head>
19.
20. <body>
21. <h1>General sibling selector (~) property</h1>
22. <p>It is the first paragraph element which will get effected.</p>
23. <div> It is the div element
24. <p> It is the paragraph under the div element </p>
25. </div>
26. <p>It is the paragraph element after the div</p>
27. <p>It is the paragraph element which will also get affected</p>
28. </body>
29. </html>

Adjacent Sibling Selector (+)


It uses the plus (+) sign as the separator between the elements. It matches the second element only
when the element immediately follows the first element, and both of them are the children of the same
parent. This sibling selector selects the adjacent element, or we can say that the element which is next

64
WEB TecHnologies

to the specified tag.

It only selects the element which is just next to the specified first element.

Syntax

1. element + element {
2. /*style properties*/
3. }

If we have to select the paragraph that comes immediately after another paragraph, then by using the
adjacent selector, it will be written as follows:

1. p + p {
2. /*style properties*/
3. }

The figure given below helps us to understand the Adjacent sibling selector (+).

In this figure, the blocks with the green color are the selected blocks affected after using the adjacent
sibling selector. There is the selection of those paragraph elements that immediately comes after
another paragraph element.

65
WEB TecHnologies

Example

In this example we are selecting the <p> element that comes immediately after the <p> element.
There is an <div> element that will not be selected, and the paragraph element after the div will also
not be selected. But the <p> element that comes just next to the third paragraph will be affected.

1. <html>
2. <head>
3. <title> Adjacent Sibling Selector </title>
4. <style>
5. body{
6. text-align: center;
7. }
8. p + p{
9. color: Blue;
10. font-size:25px;
11. font-weight: bold;
12. text-align: center;
13. }
14. p {
15. font-size: 32px;
16. }
17. </style>
18. </head>
19.
20. <body>
21. <h1> Adjacent sibling selector (+) property</h1>
22. <p> It is the first paragraph </p>
23. <p> It is the second paragraph which is immediately next to the first paragraph, and it get sele
cted. </p>
24. <div> This is the div element </div>
25. <p> This is the third paragraph which does not get affected </p>

66
WEB TecHnologies

26. <p> This paragraph is also selected because it immediately next to third paragraph </p>
27. </body>
28. </html>

Child Selector (>)


It uses the greater than (>) sign as the separator between the elements. It selects the direct
descendant of the parent. This combinator only matches the elements that are the immediate child in
the document tree. It is stricter as compared to the descendant selector because it selects the second
selector only when the first selector is its parent.

The parent element must always be placed at the left of the ">". If we remove the greater
than (>) symbol that designates this as a child combinator, then it will become the descendant
selector.

Syntax

1. element > element {


2. /*style properties*/
3. }

If we have to select the paragraph elements that are the children of <div> element then by using the
child selector, it will be written as follows:

1. div > p {
2. /*style properties*/
3. }

The figure given below helps us to understand the child selector (>).

67
WEB TecHnologies

In this figure, the blocks with the green color are the selected blocks affected after using the child
selector. As we can see in the figure, there is only the selection of those paragraph elements that are
the direct child of the div element.

Example

In this example we are selecting the <p> elements that are the child of a <div> element. It only selects
those paragraph elements that are the direct child of the div element.

This example will illustrate the use of the child sibling selector (>).

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> Child Selector </title>
5. <style>
6. body{
7. text-align: center;
8. }
9.
10. div > p{
11. color: Blue;

68
WEB TecHnologies

12. font-size:25px;
13. font-weight:bold;
14. text-align:center;
15. }
16. p {
17. font-size: 20px;
18. }
19.
20. </style>
21. </head>
22.
23. <body>
24. <h1> Child selector (>) property</h1>
25. <p> It is the first paragraph </p>
26. <p> It is the second paragraph </p>
27. <div>
28. <h1>This is the div element</h1>
29. <p> This is the third paragraph which is the child of div element </p>
30. <p> This is the fourth paragraph and also get selected because it is also the child of div elemen
t </p>
31. </div>
32. </body>
33. </html>

Descendant Selector (space)


It uses the space as the separator between the elements. The CSS descendant selector is used to match
the descendant elements of a particular element and represent it using a single space. The word
descendant indicates nested anywhere in the DOM tree. It can be a direct child or deeper than five
levels, but it will still be referred to as a descendant.

69
WEB TecHnologies

It combines two selectors in which the first selector represents an ancestor (parent, parent's parent,
etc.), and the second selector represents descendants. The elements matched by the second selector
are selected if they have an ancestor element that matches the first selector.

Syntax

1. element element {
2.
3. /*style properties*/
4. }

If we have to select the paragraph elements that are the children of an <div> element, then by using
the descendant selector, it will be written as follows:

1. div p {
2. /*style properties*/
3. }

The figure given below helps us to understand the descendant selector.

70
WEB TecHnologies

Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> Descendant Selector </title>
5. <style>
6. body{
7. text-align: center;
8. }
9. div p{

71
WEB TecHnologies

10. color: blue;


11. font-size:28px;
12. font-weight: bold;
13. text-align: center;
14. }
15. p,div {
16. font-size: 25px;
17. }
18.
19. </style>
20. </head>
21.
22. <body>
23. <div>
24. <p> This is 1st paragraph in the div. </p>
25. <p> This is 2nd paragraph in the div. </p>
26. <span>
27. This is the span element in the div
28. <p> This is the paragraph in the span. It will also be affected. </p>
29. </span>
30. </div>
31.
32. <p> Paragraph 4. It will not be affected because it is not in the div. </p>
33.
34. </body>
35. </html>

CSS Pseudo Classes


What is Pseudo Classes?
72
WEB TecHnologies

A pseudo-class can be defined as a keyword which is combined to a selector that defines the special
state of the selected elements. It is added to the selector for adding an effect to the existing elements
based on their states. For example, The ":hover" is used for adding special effects to an element when
the user moves the cursor over the element.

Pseudo-classes are unique keywords in CSS that target states or elements depending on their location
or user interaction. They enable you to style inaccessible elements using just standard class ID
selectors.

Syntax
A pseudo-class starts with a colon (:). Let's see its syntax.

1. selector: pseudo-class {
2. property: value;
3. }

A colon follows the keyword to indicate pseudo-classes. Listed below are some popular pseudo-
classes:

o :active: Applies styles when an element is activated by the user, such as clicking a button.
o :hover: Applies styles when the mouse pointer is over an element.
o :focus: When an element receives focus, such as when an input field is selected, the styling
property :focus is applied.
o :first-child: Selects the first child element of its parent; last-child - Selects the last child element
of its parent; visited - Applies styles to links the user has visited.
o :nth last child(n): Selects elements that fall into a particular numerical pattern, such as every
second or third child, using the :nth-child(n) function.
o :nth-of-type(n): Chooses elements of a particular type that adhere to a predetermined pattern
of numbers.

73
WEB TecHnologies

o :nth-last-of-type(n): It selects elements of a particular type that match a numerical pattern,


counting from the end. :nth-last-child(n) selects elements that match a specific numerical
pattern, starting at the end.

Many more Pseudo classes are available in CSS, just a few examples. Pseudo-classes are effective tools
that let you target and style particular elements depending on their status or position, improving your
web pages' visual appeal and interactivity.

Let's discuss the above pseudo-classes, along with an example.

:hover pseudo-class
This pseudo-class adds a special style to an element when the user moves the cursor over it. If you
want to make it effective, it must be applied after the ":link" and ":visited" pseudo-classes.

Example

1. <html>
2. <head>
3. <style>
4. body{
5. text-align:center;
6. }
7. h1:hover{
8. color:red;
9. }
10. h2:hover{
11. color:blue;
12. }
13. </style>
14. </head>
15.
16. <body>
17. <h1>Hello world </h1>

74
WEB TecHnologies

18. <h2>This is an example of :hover pseudo class</h2>


19. </body>
20. </html>

:active pseudo-class
It applies when the elements are clicked or activated. It selects the activated element.

We can understand it with the example given below.

Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body{
6. text-align:center;
7. }
8. a:active{
9. color: yellow;
10. }
11. h1, h2, h3{
12. color:red; ;
13. }
14. </style>
15. </head>
16.
17. <body>
18. <h1>Hello World</h1>
19. <h2>The :active pseudo-class</h2>

75
WEB TecHnologies

20. <h3>Click the following link to see the effect</h3>


21. <a href="#">Click the link</a>
22. </body>
23. </html>

:visited pseudo-class
It selects the visited links and adds special styles to them. Its possible values can be any color name in
a valid format.

Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body{
6. text-align:center;
7. }
8. a:visited{
9. color: red;
10. }
11.
12. </style>
13. </head>
14.
15. <body>
16. <h1>Hello World</h1>
17. <h2>The :visited pseudo-class</h2>
18. <h3>Click the following link to see the effect</h3>
19. <a href="#">Click the link</a>

76
WEB TecHnologies

20. </body>
21. </html>

:lang pseudo-class
It is helpful in documents that require multiple languages. It allows us to define special rules for
different languages.

Example
In this example, we specify p:lang(fr) which selects the elements having attribute lang="fr".

1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <style>
5. body{
6. text-align:center;
7. }
8. p:lang(fr)
9. {
10. font-family:Verdana;
11. color:blue;
12.
13. }
14. </style>
15. </head>
16. <body>
17.
18. <p>Without :lang pseudo class</p>
19. <p lang="fr">With :lang pseudo class with the value fr</p>

77
WEB TecHnologies

20. </body>
21. </html>

:focus pseudo-class
It selects the elements that are currently focused on by the user. It is generally used in input elements
of the forms and triggers when the user clicks on it.

Example

1. <!DOCTYPE HTML>
2. <html>
3. <style>
4. form{
5. text-align:center;
6. }
7. input:focus{
8. border:5px solid lightblue;
9. box-shadow:10px 10px 10px black;
10. color: blue;
11. width:300px;
12. }
13. </style>
14. <body>
15. <form>
16. <h1>Name: <input type="text" value="Enter your name"></h1>
17. </form>
18. </body>
19. </html>

:first-child pseudo-class
78
WEB TecHnologies

It matches a particular element, which is the first child of another element and adds a special effect to
the corresponding element.

The following illustration explains it more clearly.

Example

1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <style>
5. h1:first-child {
6. text-indent: 200px;
7. color:blue;
8. }
9. </style>
10. </head>
11.
12. <body>
13.
14. <div>
15. <h1>It is the first heading in div. It will be indented, and its color will be blue.</h1>
16. <h1>It is the Second heading in div, which will not be affected.</h1>
17. </div>
18. </body>
19. </html>

The simple tooltip hover


A tooltip specifies extra information about something when the user moves the cursor over the
element. Let's create a tooltip by using the ":hover" pseudo-class.

79
WEB TecHnologies

Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body{
6. text-align:center;
7. }
8. h2{
9. display: none;
10. background-color: red;
11. color:white;
12. padding: 20px;
13. }
14. div{
15. font-size:40px;
16. }
17. div:hover h2 {
18. display: block;
19. }
20. </style>
21. </head>
22. <body>
23. <h1>Move your mouse to the below text to see the effect</h1>
24. <div>Hello World
25. <h2>Welcome to the javaTpoint</h2>
26. </div>
27.
28. </body>
29. </html>

80
WEB TecHnologies

CSS classes and pseudo-classes


The classes in CSS can be combined with pseudo-classes. We can write it as-

Syntax

1. selector.class: pseudo-class {
2. property: value;
3. }

We can understand it with the following example.

Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body{
6. text-align:center;
7. }
8. div.hello:hover {
9. color: red;
10. font-size:40px;
11. }
12. </style>
13. </head>
14. <body>
15. <h1>CSS Classes and pseudo-classes</h1>
16. <h2>Move your cursor to the below text</h2>
17. <div class="hello">Hello World</p>

81
WEB TecHnologies

18.
19. </body>
20. </html>

CSS Pseudo-elements
A pseudo-class can be defined as a keyword which is combined to a selector that defines the special
state of the selected elements. Unlike the pseudo-classes, the pseudo-elements are used to style the
specific part of an element, whereas the pseudo-classes are used to style the element.

As an example, a pseudo-element can be used to style the first letter or the first line of an element. The
pseudo-elements can also be used to insert the content after or before an element.

Syntax

Pseudo-element has a simple syntax which is given as follows:

1. selector::pseudo-element {
2. property: value;
3. }

We have used the double colon notation (::pseudo-element) in the syntax. In CSS3, the double
colon replaced the single colon notation for pseudo-elements. It was an attempt from W3C to
differentiate between the pseudo-elements and pseudo-classes. So, it is recommended to use double
colon notation (::pseudo-element) instead of using single-colon notation (:).

In CSS1 and CSS2, there is the use of a single colon (:) syntax for both pseudo-elements and pseudo-
classes. The single colon syntax is valid for pseudo-elements in CSS1 and CSS2 for backward
compatibility.

Although there are several CSS pseudo-elements, we are discussing some of the most commonly used.
The widely used CSS pseudo-elements are tabulated as follows:

pseudo-element Description

::first-letter (:first- It selects the first letter of the text.

82
WEB TecHnologies

letter)

::first-line (:first-line) It styles the first line of the text.

::before (:before) It is used to add something before the element's content.

::after (:after) It is used to add something after the element's content.

::selection It is used to select the area of an element that is selected by the


user.

Let's discuss the above pseudo-elements, along with an example.

The ::first-letter pseudo-element


As its name implies, it affects the first letter of the text. It can be applied only to block-level elements.
Instead of supporting all CSS properties, it supports some of the CSS properties that are given below.

o Color properties (such as color)


o Font properties (such as font-style, font-family, font-size, font-color, and many more).
o Margin properties (such as margin-top, margin-right, margin-bottom, and margin-left).
o Border properties (like border-top, border-right, border-bottom, border-left, border-
color, border-width, and many more).
o Padding properties (such as padding-top, padding-right, padding-bottom, and padding-
left).
o Background properties (such as background-color, background-repeat, background-
image, and background-position).
o Text related properties (such as text-shadow, text-transform, text-decoration, etc.).
o Other properties are vertical-align (only when the float is 'none') word-spacing, line-height,
line-spacing, etc.

Example

1. <html>

83
WEB TecHnologies

2. <head>
3. <style>
4. body{
5. text-align: center;
6. }
7. h1::first-letter {
8. font-family: Lucida Calligraphy;
9. font-size: 3cm;
10. color: red;
11. text-shadow: 5px 8px 9px green;
12. }
13. h1{
14. color: blue;
15. }
16. </style>
17. </head>
18. <body>
19. <h1> Welcome to the javaTpoint.com </h1>
20. <h2> This is an example of ::first-letter pseudo-element. </h2>
21. </body>
22. </html>

The ::first-line pseudo-element


It is similar to the ::first-letter pseudo-element, but it affects the entire line. It adds the special effects
to the first line of the text. It supports the following CSS properties:

o Color properties (such as color)


o Font properties (such as font-style, font-family, font-size, font-color, and many more).

84
WEB TecHnologies

o Background properties (such as background-color, background-repeat, background-


image, and background-position).
o Other properties are word-spacing, letter-spacing, line-height, vertical-align, text-
transform, text-decoration.

Example

In this example we will see the use of ::first-line element to add special effects to the element's first
line.

1. <html>
2. <head>
3. <style>
4. body{
5. text-align: center;
6. }
7. h1::first-line {
8. font-family: Lucida Calligraphy;
9. font-size: 1cm;
10. color: red;
11. text-shadow: 5px 8px 9px green;
12. }
13. </style>
14. </head>
15. <body>
16. <h1> Welcome to the javaTpoint.com. This site is developed so that students may learn com
puter science related technologies easily. The javaTpoint.com is committed to provide easy and
in-depth tutorials on various technologies. </h1>
17. <h2> This is an example of ::first-line pseudo-element. </h2>
18. </body>
19. </html>

85
WEB TecHnologies

The ::before pseudo-element


It allows us to add something before the element's content. It is used to add something before the
specific part of an element. Generally, it is used with the content property.

We can also add the regular strings or images before the content using this pseudo-element.

Example

1. <html>
2. <head>
3. <style>
4. body{
5. text-align: center;
6. }
7. h1::before {
8. content: "'Hello World.'";
9. color: red;
10. }
11. </style>
12. </head>
13. <body>
14. <h1>Welcome to the javaTpoint.com. </h1>
15. <h2> This is an example of ::before pseudo-element. </h2>
16. <h3> In the first line the "Hello World" has added by using the pseudo-
element ::before </h3>
17. </body>
18. </html>

The ::after pseudo-element


It works similar to ::before pseudo-element, but it inserts the content after the content of the element.

86
WEB TecHnologies

It is used to add something after the specific part of an element. Generally, it is used with the content
property.

It also allows us to add regular strings or images after the content.

Example

1. <html>
2. <head>
3. <style>
4. body{
5. text-align: center;
6. }
7. h1::after {
8. content: "'Welcome to the javaTpoint.com.'";
9. color: red;
10. }
11. </style>
12. </head>
13. <body>
14. <h1> Hello World. </h1>
15. <h2> This is an example of ::after pseudo-element. </h2>
16. <h3> In the first line the "Welcome to the javaTpoint.com." has added by using the pseudo-
element ::after </h3>
17. </body>
18. </html>

The ::selection pseudo-element


It is used to style the part of an element that is selected by the user. We can use the following CSS
properties with it:

o color.

87
WEB TecHnologies

o background-color.
o Other properties include cursor, outline, etc.

Example

1. <html>
2. <head>
3. <style>
4. body{
5. text-align: center;
6. }
7. h1::selection {
8. color: red;
9. }
10. </style>
11. </head>
12. <body>
13. <h1> Hello World. </h1>
14. <h2> Select the text in first line to see the effect. </h2>
15. <h3> This is an example of ::selection pseudo-element. </h3>
16. </body>
17. </html>

CSS classes and pseudo-element


The pseudo-elements can be combined with CSS classes to style the specific element having that class.
The syntax of combining the CSS classes with the pseudo-elements is given below.

Syntax

It can be written as:

88
WEB TecHnologies

1. selector.class::pseudo-element {
2. property: value
3. }

Example

This example will affect the first letter of those <h1> elements that have class="example" rather than
affecting the all <h1> elements.

1. <html>
2. <head>
3. <style>
4. body{
5. text-align: center;
6. }
7. h1.example::first-letter {
8. color: red;
9. font-size: 2cm;
10. font-family: Lucida Calligraphy;
11. }
12. </style>
13. </head>
14. <body>
15. <h1 class="example"> Hello World. </h1>
16. <h1> Welcome to the javaTpoint.com. </h1>
17. <h3> This is an example of pseudo-element with CSS classes.</h3>
18. </body>
19. </html>

CSS Box Model


The components that can be depicted on the web page consist of one or more than one rectangular

89
WEB TecHnologies

box.

A CSS box model is a compartment that includes numerous assets, such as edge, border, padding and
material. It is used to develop the design and structure of a web page. It can be used as a set of tools
to personalize the layout of different components. According to the CSS box model, the web browser
supplies each element as a square prism.

The following diagram illustrates how the CSS properties of width, height, padding, border and margin
dictate that how much space an attribute will occupy on a web page.

The CSS box model contains the different properties in CSS. These are listed below.

90
WEB TecHnologies

o Border
o Margin
o Padding
o Content

Now, we are going to determine the properties one by one in detail.

Border Field

It is a region between the padding-box and the margin. Its proportions are determined by the width
and height of the boundary.

Margin Field

This segment consists of the area between the boundary and the edge of the border.

The proportion of the margin region is equal to the margin-box width and height. It is better to
separate the product from its neighbor nodes.

Padding Field

This field requires the padding of the component. In essence, this area is the space around the subject
area and inside the border-box. The height and the width of the padding box decide its proportions.

Content Field

Material such as text, photographs, or other digital media is included in this area.

It is constrained by the information edge, and its proportions are dictated by the width and height of
the content enclosure.

Elements of the width and height


Typically, when you assign the width and height of an attribute using the CSS width and height assets,
it means you just positioned the height and width of the subject areas of that component. The
additional height and width of the unit box is based on a range of influences.

The specific area that an element box may occupy on a web page is measured as follows-

91
WEB TecHnologies

Example 1
Here, to explain the CSS box model, we have an instance.

1. <!DOCTYPE html>
2. <head>
3. <title>CSS Box Model</title>
4. <style>
5. .main
6. {
7. font-size:30px;
8. font-weight:bold;
9. Text-align:center;
10. }
11. .gfg
12. {
13. margin-left:50px;
14. border:50px solid Purple;
15. width:300px;
16. height:200px;
17. text-align:center;
18. padding:50px;
19. }
20. .gfg1

92
WEB TecHnologies

21. {
22. font-size:40px;
23. font-weight:bold;
24. color:black;
25. margin-top:60px;
26. background-color:purple;
27. }
28. .gfg2
29. {
30. font-size:20px;
31. font-weight:bold;
32. background-color:white;
33. }
34. </style>
35. </head>
36. <body>
37. <div class = "main">CSS Box-Model Property</div>
38. <div class = "gfg">
39. <div class = "gfg1">JavaTpoint</div>
40. <div class = "gfg2">A best portal for learn Technologies</div>
41. </div>
42. </body>
43. </html>

Example 2
Here, we also have an illustration to describe the CSS box model.

1. <!DOCTYPE html>
2. <head>
3. <style>

93
WEB TecHnologies

4. .main
5. {
6. font-size:30px;
7. font-weight:bold;
8. text-align:left;
9. }
10. #box
11. {
12. padding-top:30px;
13. width: 300px;
14. height: 100px;
15. border: 40px solid red;
16. margin: 30px;
17. text-align:center;
18. font-size:32px;
19. font-weight:bold;
20. }
21. </style>
22. </head>
23. <body>
24. <div class="main">CSS Box-Model Property</div>
25. <div id="box">JavaTpoint</div>
26. </body>
27. </html>

94
WEB TecHnologies

UNIT – III
JAVASCRIPT
INTRODUCTION TO JAVASCRIPT:
Static web pages are useful and can be informative. A number of technologies have been
developed that enable the creation of web applications rather than static web pages. The java
programming language is probably the best known such technology. Few programming languages
other than java have been adapted for use in client-side web applications. One such language that is
used in programming client-side web applications is javascript.
Javascript originates from a language called Live Script and was developed by Sun
microsystems and Netscape navigator. Scripts are small pieces of code which accomplish a single
relatively simple task. Javascript is a scripting language that is used for the development of Client-
side-in-browser applications. Javascript is a simple script based language which is only suitable for
fairly simple tasks. Javascript is a language that is best suited to tasks that run for a short time. Most
of the developers experience problems when they try to build web pages which have embedded
javascript.
Important things about Javascript:
1. Javascript is embedded into HTML:
Javascript code is usually embedded into HTML code and is executed within the HTML
document. Javascript has no user interface and it relies on HTML to provide a means of
interaction with the users. Most of the javascript objects have HTML tags and provide event-
driven code to execute it.
2. Javascript is browser dependent:
Javascript depends on the web browser to support it. If the browser does not support it
javascript will be ignored. Javascript was given support from I.E 3.0 & N.N 2.0 onwards.
3. Javascript is an interpreted language:
Javascript is interpreted at runtime by the browser before it is executed. It is not compiled
into a separate program like .exe but remains part of HTML file.
4. Javascript is a loosely typed language:
Javascript is very flexible when compared to java. There is no need to specify the data
type of a variable while declaring it. We can declare variables whenever it is necessary i.e.,

95
WEB TecHnologies

variables can be declared explicitly.


5. Javascript is an object-based language:
Javascript is an object-based language that means that we can work with objects that
encapsulate data and behaviour. However, javascript object model is instance based and there
is no inheritance.
6. Javascript is Event-Driven:
HTML objects such as buttons are enhanced to support event handlers. We can specify
functionality.
7. Javascript is not Java:
Java is object oriented language, whereas javascript is object-based, interpreted, loosely-
typed language meant for creating scripts.
8. Javascript is multi functional:
Javascript can be used to:
• Enhance HTML pages.
• Develop client-side applications.
• Build to a certain extent client/server web applications.
• Create extensions to a web server.
• Provide database connectivity without using CGI.
9. Javascript language spans context:
Javascript can be used in server side Netscape live wire pro environment and microsoft’s
Active X server framework. It is not just a client side scripting tool.
Benefits of Javascript:
• It is widely supported in web browsers.
• It gives easy access to the document objects and can manipulate most of them.
• Javascript can give interesting animations without long download times associated with any
multimedia data types.
• Web surfers do not need any special plug-in to use your scripts.
• Javascript is relatively secure i.e., javascript can neither read from a local hard drive nor write
to it and we cannot get a virus directly from javascript.

96
WEB TecHnologies

Problems with Javascript:


• If our script does not work then our page is useless.
• Most of the web surfers disable javascript support in their browsers because of the problems
of broken scripts.
• Scripts can run slowly and complex scripts can take a long time to start up.
Javascript Basics:
Javascript programs contain variables, objects and functions. The key points that we need to
apply in all scripts are:
• Each line of code is terminated by semicolon.
• Blocks of code must be surrounded by a pair of curly braces. A block of code is a set of
instructions that are to be executed together as a unit.
• Functions have parameters which are passed inside parentheses.
• Variables are declared using keyword “var”.
• Scripts neither require a main function nor an exit condition. Execution of scripts starts with
the first line of code and runs until there is no more code.
Javascript and HTML page:
Javascript need to be included in a HTML page. We cannot execute these scripts from a
command line as the interpreter is part of the browser. The script is included in the web page and
run by the browser, usually as soon as the page has been loaded. The browser is able to debug the
script and can display errors.
Javascript is embedded in HTML using <SCRIPT> element. Usually <SCRIPT> is
included in <HEAD> element. A simple javascript code:
<html>
<head>
<title>Javascript</title>
<script language=“javascript”>
document.write(“Welcome to Javascript”);
</script>
</head>
<body>

97
WEB TecHnologies

<h1>Javascript First Page</h1>


</body>
</html>
If javascript is written as a separate file, then it must be saved with .js extension. External
javascript file is included into HTML by using src attribute of <SCRIPT> element. Then also the
script is evaluated when page loads and before any script action takes place.
In case of functions, all javascript statements within the function block are interpreted but
executed only when the function is called from a javascript event. Javascript statements which are
not in a function block are executed after document loads into browser.
JavaScript alert()
• The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to
give a warning message to the users. It displays an alert dialog box that consists of some
specified message (which is optional) and an OK button. The syntax is:
alert(“message”);
JavaScript prompt()
The prompt() method in JavaScript is used to display a prompt box that prompts the user for the
input. It is generally used to take the input from the user before entering the page. When the prompt
box pops up, we have to click "OK" or "Cancel" to proceed. Syntax is:
prompt(“message”, “default”)
Javascript Statements:
Programs are composed of data and code which manipulates that data. Program instructions
are grouped into units called statements. We create programs from lot of statements.
If-else:
The JavaScript if-else statement is used to execute the code whether condition is true or false. There
are three forms of if statement in JavaScript.
• if Statement
• if else statement
• if else if statement

98
WEB TecHnologies

If statement:
It evaluates the content only if expression is true. The signature of JavaScript if statement
is:
if(expression){
//content to be evaluated
}
Example:
<html>
<head>
<title>If statement</title>
</head>
<body bgcolor="pink">
<script type="text/javascript">
var age=parseInt(prompt("Enter age of the person",""));
if(age>60){
document.write("<h1>Senior Citizen</h1>");
}
</script>
</body>
</html>
Output:

99
WEB TecHnologies

JavaScript If...else Statement:


It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example:
<html>
<head>
<title>If statement</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var n=parseInt(prompt("Enter a value"," "));
if(n%2==0){
document.write(n+"is even number");
}
else{
document.write(n+"is odd number");
}
</script>
</body>
</html>
Output:

100
WEB TecHnologies

JavaScript If...else if statement:


It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is:
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

101
WEB TecHnologies

Example:
<html>
<head>
<title>if statement</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var m1=parseInt(prompt("Enter Marks1","0"));
var m2=parseInt(prompt("Enter Marks2","0"));
var m3=parseInt(prompt("Enter Marks3","0"));
var avg=parseInt((m1+m2+m3)/3);
if(avg>70){
document.write("<h1>Distinction</h1>");
}
else if(avg<70&&avg>60){
document.write("<h1>First Class</h1>");
}
else if(avg<60&&avg>50){
document.write("<h1>Second class</h1>");
}
else{
document.write("<h1>Fail</h1>");
}
</script>
</body>
</html>
JavaScript Switch:
The JavaScript switch statement is used to execute one code from multiple expressions. The
signature of JavaScript switch statement is :
switch(expression){

102
WEB TecHnologies

case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
Example:
<html>
<head>
<title>Switch</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var a=parseInt(prompt("Enter a value"," "));
var b=parseInt(prompt("Enter b value"," "));
var ch=parseInt(prompt("Enter your choice"," "));
switch(ch){
case 1: document.write("<h1>Addition is:"+(a+b)+"<h1>");
break;
case 2: document.write("<h1>Subtraction is:"+(a-b)+"<h1>");
break;
case 3: document.write("<h1>Multiplication is:"+(a*b)+"<h1>");
break;
case 4: document.write("<h1>Division is:"+(a/b)+"<h1>");
break;

103
WEB TecHnologies

default: document.write("<h1>Invalid Choice</h1>");


}
</script>
</body>
</html>
Javascript Loops:
The JavaScript loops are used to iterate the piece of code. Various types of loops are:
1. for loop
2. while loop
3. do-while loop
JavaScript For loop:
The JavaScript for loop iterates the elements for the fixed number of times. Syntax is:
for (initialization; condition; increment)
{
code to be executed
}
JavaScript while loop:
The JavaScript while loop iterates the elements for the infinite number of times. Syntax is:
while (condition)
{
code to be executed
}
JavaScript do while loop:
The JavaScript do while loop iterates the elements for the infinite number of times like while loop.
But, code is executed at least once whether condition is true or false. Syntax is:
do{
code to be executed
}while (condition);

104
WEB TecHnologies

Example:
<html>
<head>
<title>Multiplication</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var n=parseInt(prompt("Enter a number",""));
var i;
for(i=1;i<=10;i++){
document.write("<b>"+n+"*"+i+"="+(n*i)+"<br>");
}
</script>
</body>
</html>
Javascript Events:
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page. When the page loads, it is called an event. When the user clicks a button,
that click too is an event. Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element contains a set of events which can trigger JavaScript Code.
Mouse events:

105
WEB TecHnologies

Keyboard events:

Form Events:

Window/Document events:

106
WEB TecHnologies

Javascript Functions:
A javascript function contains code that will be executed by an event or by a call to function.
We may call a function from anywhere within a page. Functions can be defined both in <head> and
<body> section of a document. Syntax to define a function is:
function function_name(var1, var2,…..,varn)
{
//Block of code
}
• A function with no parameters must include the parentheses () after function name.
• The keyword function must be written in lower case, otherwise javascript error occurs.
Example:
<html>
<head>
<title>functions</title>
<script language="javascript">
function displayMessage(){
alert("This is a function");
}
</script>
</head>

107
WEB TecHnologies

<body bgcolor="pink">
<form>
<input type="button" value="Click Me" onClick="displayMessage()">
</form>
</body>
</html>
Function with parameters:
<html>
<head>
<title>Function</title>
</head>
<body onLoad="pinfo('abc',30)">
<script language="javascript">
function pinfo(name,age){
document.write("<center><h1>User Information</h1><br>");
document.write("<h3>Name is:"+name+"</h3>");
document.write("<br><h3>Age is:"+age+"</h3>");
document.write("</center>");
document.close();
}
</script>
</body>
</html>
Objects in Javascript:
Window object:
Various properties & methods supported by window object are:
• open(): It is used to open a new window. Two arguments are provided. URL that specifies
the path of documents which should be loaded in the window and Name of window.
• close(): This method is used to close the current window.
• scroll(): By using this method contents of a given window can be easily scrolled.

108
WEB TecHnologies

Apart from above methods, window object may also have properties such as toolbar,
location, menubar, scrollbar, resizeable etc..
Examples:
Creating a new window and loading existing page:
<html>
<head>
<title>Window</title>
<script language="javascript">
function showNewPage(){
window.open("login.html");
}
</script>
</head>
<body bgcolor="pink">
<center>
<form>
<input type="button" value="SeeLogin" onClick="showNewPage()">
</form>
</center>
</body>
</html>
Creating a new window:
<html>
<head>
<title>Window</title>
<script language="javascript">
function showNewPage(){
var newWindow=window.open("window.html","height=200,width=450");
newWindow.document.write("<center><h1>This is a new Window</h1></center>");
}

109
WEB TecHnologies

</script>
</head>
<body bgcolor="pink">
<center>
<form>
<input type="button" value="Open page" onClick="showNewPage()">
</form>
</center>
</body>
</html>
Document object:
Document refers to page which will be displayed as soon as the browser window is opened. Various
methods/properties supported by the document object are:
• write()/writeln(): We can create HTML pages using javascript by using write()/writeln()
methods. Data can also be inserted.
• bgcolor/fgcolor: These are the same properties that can be set in the <body> tag. The only
difference here is that the values can be set from javascript.
• anchors: It is an array holding the names of anchor elements appearing on web page.
• links: It is an array holding all links appearing on web page.
• forms: It is an array that contains all of the HTML forms.
• close(): The document is not completely written until the close() method is called. The
browser keep waiting for more data if user do not call this method.
Form object:
Two aspects of form can be manipulated through javascript.
• Most commonly the data that is entered onto the form can be checked at submission.
• We can actually build forms through javascript.
Various form events are:
• onClick: This event is triggered when the user clicks on an element.
• onSubmit: This event can only be triggered when the form is submitted.
• onReset: This event is triggered when the form is reset by the user.

110
WEB TecHnologies

Simple form validation:


<html>
<head>
<title>Validation</title>
<script language="javascript">
function validate(){
var value=document.forms[0].elements[0].value;
if(value!="abc"){
document.forms[0].reset();
}
else{
alert("Hi abc");
}
}
</script>
</head>
<body bgcolor="pink">
<form>
Name:<input type="text" name="txt1" value=""><br>
<input type="submit" value="Submit" onClick="validate()">
</form>
</body>
</html>
Math object:
Methods supported by math object are:
• min(): Displays minimum of two numeric values entered. (min(45,65)).
• max(): Displays maximum of two numeric values entered. (min(45,65)).
• abs(): Displays the absolute value of numeric entity entered into it.
• ceil(): Displays the rounded value of the integer entered into it. (ceil(5.2)=6)
• round(): It rounds the value entered to its nearest integer. (round(5.2)=5)

111
WEB TecHnologies

• sqrt(): Displays the square root of the value entered into it.
• sin(): Displays the trigonometric sine value.
• cos(): Displays the trigonometric cosine value.
• tan(): Displays the trigonometric tangent value.
• log(): Displays the logarithmic equivalent value.
Browser object:
The browser object is also called as navigator object. Methods supported by browser
object are:
• navigator.appcodeName: The internal name for the browser.
• navigator.appName: This is the public name of the browser.
• navigator.appversion: The version number, platform on which the browser is running and
the version of navigator with which it is compatible.
• navigator.userAgent: The strings appcodeName and appVersion concatenated together.
• navigator.plugins: An array containing details of all installed plugins.
• navigator.mimeTypes: An array of all supported MIME types.
Date object:
Javascript Date provides functions to perform many different date manipulations. In
javascript dates and times represent the number of milliseconds since 01/01/1970 UTC.
Javascript like most programming systems has two separate notions of time:
• UTC is universal time, also known as Greenwich Mean Time, which is the standard time
throughout the world.
• Local time is the time on the machine which is executing the script.
Date object Methods:
1. Date(): Construct an empty date object.
2. Date(milliseconds): Construct a new date object based upon the number of milliseconds
which have elapsed since 00:00:00 hours on 01/01/1970.
3. Date(String): Create a date object based upon the contents of a text string.
4. Date(year,month,day[hour,minute,second]): Create a new date object based upon numeric
values for year, month and day. Optional time values may also be supplied.
5. Parse(string): Returns the number of milliseconds since midnight on 01/01/1970.

112
WEB TecHnologies

6. getDate(): Return the day of the month.


7. getDay(): Return the day of the week.
8. getHours(): Return the hours.
9. getMilliseconds(): Return the milliseconds.
10. getMinutes(): Return the minutes.
11. getSeconds(): Return the seconds.
12. getMonth(): Return the month.
13. getFullYear(): Return the year as a four digit number.
14. getTime(): Return the number of milliseconds since midnight on 01/01/1970.
15. setDate(day): Set the day value of the object. Accept values in the range 1 to 31.
16. setFullYear(year[,month,day]): sets the year value of the object.
17. setHours(hours[,mins,secs,ms]): Set the hours value of the object to an integer in the range
0 – 23.
18. setMilliseconds(ms): Set the milliseconds value of the object in the range 0 - 999.
19. setMinutes(min[,secs,ms]): Set the minutes value of the object in the range 0 - 59.
20. setSeconds(secs[,ms]): Set the seconds value of the object to an integer in the range 0 - 59.
21. setMonth(month[,day]): Set the month value of the object to an integer in the range 0 - 11.
Example:
<html>
<head>
<title>Date</title>
</head>
<body onLoad=“Dater()”>
<script language=“javascript”>
function Dater(){
var today=new Date();
var yesterday=new Date();
var diff=today.getDate()-1;
Yesterday.setDate(diff);
document.write(“<h3>The date is:”+today+”</h3>”);

113
WEB TecHnologies

document.write(“<h3>The date yesterday was:”+yesterday+”</h3>”);


document.close();
}
</script>
</body>
</html>
Javascript Arrays:
The basic array operations are:
• Creation of Arrays.
• Adding elements.
• Accessing individual elements.
• Removing elements.
Creating Arrays:
Javascript arrays can be created in three different ways:
1. The easiest way is simply to declare a variable and pass it some elements in array format.
var days=[“Monday”,”Tuesday”,”Wednesday”];
2. The second approach is to create an array object using the keyword new and a set of elements
to store:
var days=new Array(“Monday”,”Tuesday”,”Wednesday”);
3. Finally, an empty array object which has a space for a number of elements can be created:
var days=new Array(3);
Adding elements to Arrays:
Adding an element to an array can be done as shown below:
var days[4]=“Thursday”;
In javascript we have a benefit. If the array is full, then also we can add elements to array.
The interpreter simply extends the array and inserts new item. For example:
Accessing Array elements:
The elements in the array are accessed through their index. The same access method is
used to find elements and to change their values.
Length:

114
WEB TecHnologies

When accessing array elements we need to know how many elements have been stored
into the array. This is done through the length attribute. The index number runs from 0 – length-1.
Example:
<html>
<head>
<title>Arrays</title>
</head>
<body>
<script language=“javascript”>
document.write(“<h1> Looping through the Array</h1>”);
var data =[10,20,30,40];
var len=data.length;
for(var count=0;count<len;count++){
document.write(data[count]+”,”);
}
document.close();
</script>
</body>
</html>
Removing Array elements:
Javascript does not provide a built-in function to remove array members. To remove array elements
we use the following procedure:
1. Read each element in the array.
2. If the element is not the one which we want to delete, copy it to temporary array.
3. If the element is the one we want to delete, do nothing.
4. Increment loop counter.
5. Repeat the process and copy the array elements again into original array.
Example:
<html>
<head>

115
WEB TecHnologies

<title>Arrays</title>
</head>
<body>
<script language=“javascript”>
document.write(“<h1> Removing Array elements</h1>”);
var data =[10,20,30,40];
var len=data.length;
for(var count=0;count<len;count++){
document.write(data[count]+”,”);
}
var rem=prompt(“Enter item to remove”,””);
var tmp=new Array(data.length-1);
var count2=0;
for(count=0;count<len;count++){
if(data[count]==rem){
}
else{
tmp[count2]=data[count];
count2++;
}
}
data=tmp;
var len=data.length;
for(var count=0;count<len;count++){
document.write(data[count]+”,”);
}
document.close();
</script>
</body>
</html>

116
WEB TecHnologies

Dynamic HTML using Javascript:


In case of HTML dynamic means subject to change at any time. The DHTML is simply
HTML that has the ability to change after the browser has loaded the page. DHTML is also called
as “Animated HTML” i.e., anything that is written in HTML can be redone after the page loads.
This dynamic capability is achieved through a combination of several key DHTML
components that work in conjunction with HTML. DHTML can also be described as the combination
of HTML, stylesheets and scripts that allow documents to be animated. The features of dynamic
HTML are:
1. Changing tags and contents:
In this we deal with technology of changing the contents and tags of text using the concept
of DOM.
2. Live positioning of elements:
In this DHTML has introduced a concept of dynamically positioning tags in the
document.
3. Dynamic fonts:
We can increase the font of text dynamically.
4. Data Binding:
This enables page elements such as table cells to attach themselves to data records.
Changes to a record are updated on page, and user modification updated on data record.
Example:
<html>
<head>
<title>DHTML</title>
</head>
<body bgcolor="pink">
<center>
<h1 onMouseOver="this.style.color='red';" onMouseOut="this.style.color='blue';">
Text changes to red with the mouse
</h1>
</center>

117
WEB TecHnologies

</body>
</html>
Dynamic content – Changing web pages:
There are several methods that insert HTML in pages:
1. insertAdjacentHTML.
2. insertAdjacentText.
3. innerText.
4. outerText.
5. innerHTML.
6. outerHTML.
insertAdjacentHTML & insertAdjacentText:
The insertAdjacentHTML method lets us to insert HTML next to an element that already
exists and insertAdjacentText method lets us insert text in the same way.
We can determine where the new text or HTML will go with respect to existing element
by passing the constraints “BeforeBegin, AfterBegin, BeforeEnd or AfterEnd”.
innerText: Let us change the text between the start and end tags.
outerText: Let us change all the text including start and end tags.
innerHTML: Changes the contents of elements between start and end tags.
outerHTML: Changes contents of an element including the start and end tags.
createElement: It is used to create new web page elements and use methods like insertBefore() and
insertAfter() to insert those elements into web page.
Examples:
insertAdjacentHTML():
<html>
<head>
<title>InsertAdjacentHTML</title>
<script language="javascript">
function showMore(){
div1.insertAdjacentHTML('afterend','A New Textfield:<input type="text" value="Hello!">');
}

118
WEB TecHnologies

</script>
</head>
<body bgcolor="pink">
<div id="div1">
<input type="button" value="Click Me" onClick="showMore()">
</div>
</body>
</html>
Output:

innerText:
<html>
<head>
<title>InnerText</title>
<script language="javascript">
function changeHeader(){
header.innerText="This is new Header";
}
</script>
</head>

119
WEB TecHnologies

<body bgcolor="pink">
<center>
<h1 id="header" onClick="changeHeader()">Dynamic HTML</h1>
</center>
</body>
</html>
innerHTML:
<html>
<head>
<title>InnerText</title>
<script language="javascript">
function changeHeader(){
header.innerHTML="<marquee>This is new Header</marquee>";
}
</script>
</head>
<body bgcolor="pink">
<center>
<h1 id="header" onClick="changeHeader()">Dynamic HTML</h1>
</center>
</body>
</html>
outerHTML:
<html>
<head>
<title>InnerText</title>
<script language="javascript">
function changeHeader(){
header.outerHTML="<marquee style='font-size:50'>This is new Header</marquee>";
}

120
WEB TecHnologies

</script>
</head>
<body bgcolor="pink">
<center>
<h1 id="header" onClick="changeHeader()">Dynamic HTML</h1>
</center>
</body>
</html>
createElement() & createTextNode():
<html>
<head>
<title>createElement</title>
<script language="javascript">
function showMore(){
var newDiv,newTextfield,newText;
newDiv=document.createElement("DIV");
newDiv.id="div1";
newTextfield=document.createElement("INPUT");
newTextfield.type="text";
newTextfield.value="Hello!";
newText=document.createTextNode("A New Textfield");
newDiv.insertBefore(newText,null);
newDiv.insertBefore(newTextfield,null);
document.body.insertBefore(newDiv,null);
}
</script>
</head>
<body bgcolor="pink">
<h1 align="center">CreateElement Method</h1><br>
<input type="button" value="Click Me" onClick="showMore()">

121
WEB TecHnologies

</body>
</html>
Output:

Creating Dynamic Tables:


<html>
<head>
<title>Dynamic Tables</title>
<script language="javascript">
function addRow(){
var newRow=table1.insertRow(3);
var newCell=newRow.insertCell(0);
newCell.innerText="aaa";
var newCell=newRow.insertCell(1);
newCell.innerText="bbb";
var newCell=newRow.insertCell(2);
newCell.innerText="ccc";
}
</script>
</head>

122
WEB TecHnologies

<body bgcolor="pink">
<center>
<h1>Dynamic Tables</h1>
<table id="table1" border="2">
<tr>
<th>ABC</th>
<th>DEF</th>
<th>GHI</th>
</tr>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
</tr>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
</tr>
</table>
<input type="button" value="Add Row" onClick="addRow()">
</center>
</body>
</html>
Output:

123
WEB TecHnologies

Data Validation using Javascript:


Data validation is a process of verifying/validating the data entered by the user. Data
validation can be done in two ways:
1. Client-side data validation.
2. Server-side data validation.
Client-side data validation is a process of verifying the data entered by the user before it
is submitted to the server.
Server-side data validation is a process of verifying the data at server side with the
database data.
Example:
Registration Form Validation:
<html>
<head>
<title>JavaScript sample registration from validation</title>
<script type='text/javascript'>
function formValidation()

124
WEB TecHnologies

{
var uid = document.form1.userid;
var passid = document.form1.passid;
var uname = document.form1.username;
var uadd = document.form1.address;
var uzip = document.form1.zip;
var uemail = document.form1.email;
if(userid_validation(uid,5,12))
{
if(userid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
}
}
}
}
}
}
return false;
}
function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;

125
WEB TecHnologies

if (uid_len == 0 || uid_len >= my || uid_len < mx)


{
alert("It should not be empty / length be between "+mx+" to "+my);
uid.focus();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Please input alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
return true;
}
else

126
WEB TecHnologies

{
alert('Please input alphanumeric characters only');
uadd.focus();
return false;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('Please input numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");

127
WEB TecHnologies

uemail.focus();
return false;
}
}
</script>
</head>
<body>
<form name='form1' onsubmit='return formValidation()' >
<table width="500" cellpadding="3" style="border-collapse: collapse;">
<tr>
<td>User id </td>
<td><input type="text" name="userid" size="12" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="passid" size="12" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="username" size="50" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" size="50" /></td>
</tr>
<tr>
<td>ZIP Code </td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>

128
WEB TecHnologies

<td>Email</td>
<td><input type="text" name="email" size="50" /></td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="msex" value="Male" /> Male
<input type="radio" name="fsex" value="Female" /> Female</td>
</tr>
<tr>
<td>Language preference</td>
<td><input type="checkbox" name="en" value="en" checked />English
<input type="checkbox" name="nonen" value="noen" />Non English</td>
</tr>
<tr>
<td>Write about yourself<br>
(optional)</td>
<td><textarea name="desc" rows="4" cols="40"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" value="Submit" /></td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body>
</html>
Output:

129
WEB TecHnologies

130
WEB TecHnologies

UNIT – IV
XML
Introduction:
XML stands for “Extensible Markup Language”. XML is a text-based markup language. A
markup language is a set of instructions often called as tags which can be added to text files. When
the file is processed by a suitable application the tags are used to control the structure and
presentation of data contained in the file. Most commonly tags are used by application when
presenting data.
XML is more than HTML because, HTML only deals with presentation and carries no
information about the data, whereas XML deals with the representation of data and carries
information about the data. In XML, we create our own tags and also syntax for those tags that can
let the document structure follow the data structure. As we are defining our own tags and there are
no predefined tags, XML is defined to be “self-descriptive”. Using scripting languages like javascript
we can reach to various elements of an xml page and make use of data.
When compared with HTML, XML provides a way of structuring the data and store data
with focus on “What data is”, where HTML was designed to display data with focus on “How data
looks”.
XML is nothing special, it is just a plain text. Software that can handle plain text can
also handle XML. XML is a software/hardware independent tool for carrying information.
Advantages of XML:
• Readability:
XML document is plain text and human readable.
• Hierarchal:
XML document has a tree like structure which is enough to express complex data as
simple as possible.
• Language Independent:
XML documents are language neutral. For example, a java program can generate an
XML which can be parsed by a program written in C++ or perl.
• Platform Independent:
XML files are operating system independent.

131
WEB TecHnologies

Uses of XML:
• XML is used to describe the contents of a document.
• XML is used in messaging, where applications exchange data between them.
• The data can be extracted from the database, can be preserved with original information and
can be used in more than one application in different ways.
Important points about XML:
• XML is case sensitive.
• All the XML files are stored with .xml extension.
• Every XML document begin with <?xml version=“1.0”?>
Example: XML to store customer information of a supermarket.
<?xml version=”1.0”?>
<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>

132
WEB TecHnologies

</orders>
</customer>
</document>
Valid & Well-formed XML document:
An XML document is said to be valid only if it is associated with a “Document Type
Definition” or “XML schema”.
An XML document is said to be well-formed only if it satisfies the below constraints:
• All tags must have corresponding end tag.

• Must have no overlapping of tags.

Most of the XML parsers require XML documents to be well-formed, but not necessarily valid.
Document Type Definition(DTD):
• Document Type Definition specifies syntax for XML document i.e., it specifies rules that
apply to the data.
• The XML document contains data, whereas DTD contains rules that apply to the data.
• A DTD defines the document structure with a list of legal elements and attributes.

133
WEB TecHnologies

Syntax of DTD:
<!DOCTYPE ROOTELEMENT[
<!ELEMENT ELEMENT_NAME1(subelement1,subelement2….)>
<!ELEMENT ELEMENT_NAME2(subelement1,subelement2….)>
.
.
<!ELEMENT ELEMENT_NAMEn(subelement1,subelement2….)>
]>
There are two types of DTD:
1. Internal DTD.
2. External DTD.
Internal DTD is the one in which we specify the DTD within the XML document. The scope
of Internal DTD is limited to one document only.
Example:
<?xml version=”1.0”?>
<!DOCTYPE document[
<!ELEMENT document (customer)*>
<!ELEMENT customer (name,date,orders)>
<!ELEMENT name (firstname,lastname)>
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT orders (item)*>
<!ELEMENT item (product,number,price)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT number (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>

134
WEB TecHnologies

<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>
</orders>
</customer>
</document>
External DTD is the one where DTD is specified as a separate file and is saved with .dtd
extension and contains only set of rules. To import the DTD file into XML we include the below
statement in XML file:
<!DOCTYPE ROOT_ELEMENT SYSTEM “filename.dtd”>
Example:
Extern.dtd:
<!ELEMENT document (customer)*>
<!ELEMENT customer (name,date,orders)>
<!ELEMENT name (firstname,lastname)>

135
WEB TecHnologies

<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT orders (item)*>
<!ELEMENT item (product,number,price)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT number (#PCDATA)>
<!ELEMENT price (#PCDATA)>
Cust.xml:
<?xml version=”1.0”?>
<!DOCTYPE document SYSTEM “extern.dtd”>
<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>
</orders>

136
WEB TecHnologies

</customer>
</document>
Specifying attributes in a DTD:
We can specify the attributes of the elements in DTD by using <!ATTLIST> element. This
element holds a list of attributes for an element. We can specify default values for the attribute and
also can specify whether the attribute is necessary for an element or not. The format of defining an
attribute in DTD is:
<!ATTLIST ELEMENT_NAME ATTRIBUTE_NAME TYPE DEFAULT_VALUE>
The value supplied for attribute can be:
Value – The default value of an attribute.
#REQUIRED – The attribute is required.
#IMPLIED – The attribute is not required.
#FIXEDVALUE – The attribute value is fixed.
The default type used for attributes is unparsed character data.
Example:
<?xml version=”1.0”?>
<!DOCTYPE document[
<!ELEMENT document (customer)*>
<!ELEMENT customer (name,date,orders)>
<!ELEMENT name (firstname,lastname)>
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT orders (item)*>
<!ELEMENT item (product,number,price)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT number (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ATTLIST customer nationality CDATA “INDIAN”
Age CDATA #IMPLIED

137
WEB TecHnologies

Type CDATA #REQUIRED>


]>
<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>
</orders>
</customer>
</document>
XML Namespaces:
XML document allows us to create our own XML elements with our own element names.
This can result in naming collision i.e., different XML elements can have the same name in one
XML document. For example:
<?xml version=”1.0”>
<college>
<staff>

138
WEB TecHnologies

<name>aaa</name>
<dept>CSE</dept>
</staff>
<student>
<name>bbb</name>
<dept>CSE</dept>
</student>
</college>
In the above example the XML elements <name> and <dept> of both staff and student have
the common element names. This could provide naming collisions. To solve such problems in XML
documents, we use the “XML Namespaces”. The XML namespaces allows us to prevent collision
by differentiating the elements with same names by using namespace prefixes.
The xmlns attribute:
XML namespaces use the keyword xmlns to create namespace prefixes and assign
corresponding URI that uniquely identifies the namespace. For the above example we can define the
namespace prefixes to avoid naming collisions.
<?xml version=”1.0”>
<college xmlns:staff=”web technologies:staffInfo”
xmlns:student=”web technologies:studentInfo”>
<staff>
< staff:name>aaa</ staff:name>
< staff:dept>CSE</ staff:dept>
</staff>
<student>
< student:name>bbb</ student:name>
< student:dept>CSE</ student:dept>
</student>
</college>
XML Schema:
An XML schema describes the structure of an XML document. XML schema is an XML-

139
WEB TecHnologies

based alternative to DTD.

Limitations of DTD:
1. DTD’s do not have the angled bracket syntax.
2. We cannot use multiple DTD’s to validate one XML document.
3. DTD’s have very limited basic types.
4. DTD’s are not object oriented.
An XML schema language is also referred to as “XML Schema Definition(XSD)”. An XML
schema begins by declaring the XML schema namespace as follows:
<xsd:schema xmlns:xsd=http://www.w3.org/2001/XMLSchema>
Defining an Element:
There are two types of elements defined in an XML schema. They are:
1. Simple elements.
2. Complex elements.
1. Simple Elements:
Simple elements can contain only data and they cannot have sub elements or attributes.
The text they contain can be of various data types. The format for defining a simple element
is:
<xsd:element name=”element_name” type=”xsd:type”/>
2. Complex Elements:
Complex elements can contain sub elements or attributes. The complex elements are
made up of simple elements. The format of defining a complex element is:
<xsd:complexType name=”element_name”>
<xsd:sequence>
<xsd:element name=”element_name” type=”xsd:type”/>
<xsd:element name=”element_name” type=”xsd:type”/>
</xsd:sequence>
</xsd:complexType>

140
WEB TecHnologies

Defining an Attribute:
An attribute provides additional information used by an element besides the element’s
content. The format for defining an attribute in XML schema is:
<xsd:complexType name=”element_name”>
<xsd:complexContent>
<xsd:extension>
<xsd:attribute name=”attribute_name” type=”xsd:type”/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
Example:
<xsd:complexType name=”employee”>
<xsd:complexContent>
<xsd:extension>
<xsd:attribute name=”gender” type=”xsd:string”/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
An XML schema is a file that we can create using any text editor. The file must be saved
with .xsd extension and the contents of the file must confirm to the XML schema language.
Referencing an XML schema:
We link an XML schema by referencing the XML schema file in the <root> tag of the XML
document. The format of <root> is:
<root xmlns:xsi=http://www.w3.org/2000.10.XMLSchema-instance xsi:schemalocation=”URI”>
Example of XML schema:
St.xsd:
<?xml version=”1.0”?>
<xsd:schema xmlns:xsd=http://www.w3.org/2001/XMLSchema>

141
WEB TecHnologies

<xsd:complexType name=”student”>
<xsd:sequence>
<xsd:complexType name=”studentType”>
<xsd:sequence>
<xsd:element name=”rollnumber” type=”xsd:string”/>
<xsd:element name=”name” type=”xsd:string”/>
<xsd:element name=”marks” type=”xsd:integer”/>
<xsd:element name=”result” type=”xsd:string”/>
</xsd:sequence>
</xsd:complexType>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
studentInfo.xml:
<?xml version=”1.0”?>
<root xmlns:xsi=http://www.w3.org/2000.10.XMLSchema-instance xsi:schemalocation=”st.xsd”>
<student>
<studentType>
<rollno>95A0</rollno>
<name>aaa</name>
<marks>500</marks>
<result>Firstclass</result>
</studentType>
<studentType>
<rollno>95A1</rollno>
<name>bbb</name>
<marks>450</marks>
<result>Firstclass</result>
</studentType>
</student>

142
WEB TecHnologies

Presenting XML:
In order to present the data in XML documents we use web presentation technologies.
Presenting data is again dependent to a specific technology. It is better to separate the data from the
presentation technology and stored in XML document and the extensible stylesheet language (XSL)
is used to present the data.
Extensible stylesheet language (XSL):
The extensible stylesheet is a language used to express stylesheets which are then used to
present XML documents. XSL stylesheets are not same as HTML stylesheets. Rather than creating
a style for a particular XML element or class of elements with XSL, a template is created. This
template is used to format XML elements which match a specific pattern.
The XSL transformation language (XSLT) is used to transform one XML document from
one form to another. The result of applying XSLT to an XML document could be another XML,
HTML text or any other document.
Example:
People.xml:
<?xml version=”1.0”?>
<?xml-stylesheet type=”text/xsl” href=”people.xsl”?>
<people>
<person born=”1993”>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<profession>Software Engineer</profession>
</person>
<person born=”1982”>
<name>
<firstname>ccc</firstname>

143
WEB TecHnologies

<lastname>ddd</lastname>
</name>
<profession>Project Manager</profession>
</person>
</people>
People.xsl:
<?xml version=”1.0”?>
<xsl:stylesheet version=”1.0” xmlns:xsl=http://www.w3.org/1999/XSL/Transform>
<xsl:output method=”html” omit-xml-declaration=”no”/>
<xsl:template match=”/”>
<html>
<head>
<title>XSLT</title>
</head>
<body>
<table border=”2”>
<tr>
<th>Born</th>
<th>FirstName</th>
<th>LastName</th>
<th>Profession</th>
</tr>
<xsl:for-each select=”people/person”>
<tr>
<td><xsl:value-of select=”@born”/></td>
<td><xsl:value-of select=”name/firstname”/></td>
<td><xsl:value-of select=”name/lastname”/></td>
<td><xsl:value-of select=”profession”/></td>
</tr>
</xsl:for-each>

144
WEB TecHnologies

</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The XSL stylesheet begins with a tag called stylesheet which binds with namespace prefix
xsl to the URI http://www.w3.org/1999/XSL/Transform which uniquely identifies the XSL
namespace.
The <xsl:output> is used to write a XHTML document type declaration to the result tree.
Attribute omit-xml-declaration specifies whether the transformation should write the XML
declaration to the result tree. <xsl:template> element describes how to transform a particular node
from the source tree into the result tree. The match is used to select the document root of the source
document.
The element <xsl:for-each> is used to iterate through the source XML document and search
for person element. The attribute select specifies the node on which the <xsl:for-each> operates. The
element <xsl:value-of>is used to retrieve value of the attribute and elements. The @ symbol specifies
that we need to retrieve an attributes value.
Document Object Model (DOM):
There are two models that are commonly used for XML parsers:
1. SAX (Simple API for XML).
2. DOM (Document Object Model).
SAX parser is mainly used when we are dealing with streams of data i.e., the data the XML
is passing from one place to another with parser acting as an intermediate way point. Typically this
model is used when passing XML data across a network between applications and is widely used by
java programmers. SAX based parsers does not have to build any static models of the document in
memory and are intended to run quickly.
The SAX parser is not suitable to use in websites where repeated querying and updating of
XML document is required. Here it is sensible to build some sort of representation which can be held
in memory for the duration of the use of application. In such cases the DOM based parser is a better
choice.

145
WEB TecHnologies

DOM stands for Document Object Model and is an API for XML documents. Basically an
API is a set of data items and operations which can be used by the developers of application
programs. For example, the Microsoft windows environment has a very rich API which is used by
the developers when creating windows programs.
The DOM API specifies the logical structure of XML documents and the ways in which they
can be accessed and manipulated. The DOM API is just a specification. There isn’t a single reference
piece of software associated with it which everyone must use. DOM complaint applications include
all of the functionality that is needed to handle XML documents. They can build static documents,
navigate and search through them, add new elements, delete elements and modify the content of
existing elements.
DOM views XML document as a tree, but this is very much logical view of the document.
Each XML element is modelled as an object. This means that the node encompass both data and
behaviour and that the whole document can be seen as a single complex object. Object oriented
theory lets each object have a unique identity. If each node has a unique identity then the tree can be
searched for individual nodes. DOM exposes the whole document to application so that the
application can manipulate individual nodes.
Accessing XML data using DOM object:
School.xml:
<?xml version="1.0"?>
<school>
<class>
<title>XML</title>
<students>
<student>
<first_name>aaa</first_name>
<last_name>bbb</last_name>
</student>
<student>
<first_name>aaa</first_name>
<last_name>bbb</last_name>

146
WEB TecHnologies

</student>
</students>
</class>
</school>
School.html:
<html>
<head>
<title>Accessing XML data</title>
<script type="text/javascript">
function getStudentData()
{
var xmldoc;
xmldoc=new ActiveXObject("Microsoft.XMLDOM");
xmldoc.load("school.xml");
nodeSchool=xmldoc.documentElement;
nodeClass=nodeSchool.firstChild;
nodeStudents=nodeClass.lastChild;
nodeStudent=nodeStudents.lastChild;
nodeFirstname=nodeStudent.firstChild;
nodeLastname=nodeFirstname.nextSibling;
outputMessage="Name:"+nodeFirstname.firstChild.nodeValue+'
'+nodeLastname.firstChild.nodeValue;
message.innerHTML=outputMessage;
}
</script>
</head>
<body bgcolor="pink">
<center>
<h1>Accessing XML Data</h1>
<div id="message"></div>

147
WEB TecHnologies

<input type="button" value="GET DATA" onClick="getStudentData()">


</center>
</body>
</html>
Using XML processors: DOM & SAX:
Parsing is a process of reading and validating a program written in one format and converting
it to the desired format. XML documents are organized as hierarchal structure similar to a tree. They
are well-formed and valid documents. Thus if we have something equivalent to a compiler for XML
that can read, validate and convert it. So we can make use of parser for XML documents.
The program that do the process of reading, validating and convert an XML document into
the desired format is called as a parser or processor. The parser has to access the XML file and bring
it into the memory. Then the parser converts the file into an object, where the object is accessed by
an application program.
When an XML document is presented to a program as an object there are two possibilities:
a) Present the document in bits and pieces as we encounter a certain selection or portions of the
document. This approach where it goes through the XML document item by item till the end
of XML file is called “Simple API for XML (SAX)”.
b) To present the entire document tree at once where the program has access to the XML
document as a single object. This approach of presenting entire document as a single object
is done by “Document Object Model (DOM)”.

148
WEB TecHnologies

Introduction:

149

You might also like