You are on page 1of 47

VISHNU INSTITUTE OF TECHNOLOGY :: BHIMAVARAM

Department Of Computer Science and Engineering

Advanced Java & Web Technologies

Unit – I
HTML : HTML tags, Lists, Tables, Images, forms, Frames.
Cascading style sheets.
JavaScript : Introduction to Java script, Objects in Java Script, Dynamic HTML
with Java Script.

Concentrate on learning web technologies, results will


automatically come on their way.
Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Hyper Text Markup Language

HTML stands for Hyper Text Markup Language. It is the primary language used to encode
documents containing hyperlinks. HTML is a markup language for describing web documents
(web pages). HTML is defined with the use of the Standard Generalized Markup Language
(SGML), which is an ISO standard notation for describing text-formatting languages.HTML file is
text file containing small markup tags. Its markup tags tell the web browser how to display the
page.

HTML History
Since the early days of the web, there have been many versions of HTML:
Initially work on HTML was started in 1989 by Tim Berners Lee.
In 1995, HTML 2.0 was published by IETF (Internet Engineering Task Force). HTML 2.0 is
the first standard HTML specification.
In 1997, HTML 3.2 was published by W3C (World Wide Web Consortium).
In 1997, HTML 4.0 was published by W3C. It provides three variations: strict, transitional
and frameset.
In 1999, HTML 4.01 was published by W3C.

HTML Elements, tags and attributes

A markup language is a set of markup tags. HTML documents are described by HTML tags. The
fundamental syntactic units of HTML are called tags. Each HTML tag describes different
document content. HTML tags are keywords (tag names) surrounded by angular brackets:

<tagname> content </tagname>

HTML tags normally come in pairs like <p> and </p>.

The first tag in a pair is the opening tag; the second tag is the closing tag. The end tag is written
like the opening tag, but with a slash before the tag name. Whatever appears between a tag and
its closing tag is the content of the tag. Not all tags can have content. The opening tag and its
closing tag together specify a container for the content they enclose. The container and its content
together are called an element.

For example, consider the following element:

<p> Computer Science and Engineering </p>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 1


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
The paragraph tag, <p>, marks the beginning of the content; the </p> tag marks the end of the
content of the paragraph element.

HTML elements can be nested (elements can contain elements). All HTML documents consist of
nested HTML elements. This example contains 4 HTML elements:
Eg:
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

Attributes : HTML elements can have attributes. Attributes specify alternative meanings of a tag.
They can be written between an opening tag‟s name and its right angle bracket. They are
specified in keyword form, which means that the attribute‟s name is followed by an equals sign
and the attribute‟s value i.e., attributes come in name/value pairs like: name="value". Attribute
names, like tag names, are written in lowercase letters. Attribute values must be delimited by
double quotes.

<p title="VIT">Vishnu Institute of Technology</p>

Comments : to increase the readability of the program. In HTML comments are enclosed between
<!—- and -->
<!—-This is a comment -->

Core Elements and Attributes


The four main elements that form the basic structure of every HTML document are
<html> <head> <title> <body>
In general, Every html document has a head and body sections, which are enclosed in between
<html> tags.

The <html> Element


The <html> element is the containing element for the whole HTML document. Every html
document should have and opening <html> tag and end with </html> tag. Only two elements
can appear as direct children of an <html> element. They are <head> and <body>. <html>
element carry the following attributes.
Attribute Value Description
id Any valid string Used to identify uniquely any element within a page.
Syntax : id=”string”
Example to distinguish between two paragraphs
<p id=”para1”>This is first paragraph</p>
<p id=”para2”>This is second paragraph</p>
dir ltr (default value) Allows indicating direction of text flow in the browser. It can
rtl take two values either left to right or right to left.
lang ar-arabic, en- Allows to indicate the main language used in a document
English, en-us-US

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 2


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
English, zh-
Chineese
xmlns http://www.w3. Specifies the XML namespace attribute (If you need your
org/1999/xhtml content to conform to XHTML)

The <head> element


<head> element is the container for all header elements. It should be the first thing to appear
after opening the <html> tag. Each <head> element should contain a <title> element indicating
the title of the document, although it may also contain any combination of the following
elements.
<base> - to specify base paths for relative URLs
<object> - to include images, JavaScript objects, Flash animations, MP3 files etc.
<link> - to link to an external file
<style> - to include CSS rules inside the document
<script> - for including script in the document.
<meta> - includes information about the documents such as keywords and a description
which are particularly helpful for search applications.
Attributes are : id, dir, lang.
The <title> element
<title> element is used to specify a title for every page. It lives inside <head> element. It is used
in several ways
At the very top of the browser window.
As the default name for a bookmark in browsers.
By search engines that use its content to help index pages.
Attributes are : id, dir, lang.

The <body> element


The <body> element appears after <head> and contains the part of the web page that is actually
visible in the main browser windows, referred to as body content. Body can contain anything like
paragraphs, images, lists, links etc. Body element carries the following attributes
Attribute Value Description
background URL Specifies a background image for a document
bgcolor color Specifies the background color of a document
alink color Specifies the color of an active link in a document
link Color Specifies the color of unvisited links in a document
vlink Color Specifies the color of visited links in a document
text color Specifies the color of the text in a document
class Class name Used to specify that element belongs to class of element. It is
commonly used with CSS.
Syntax : class=”classname”
Style Css styles Specifies an inline CSS style for an element
Title Title name Gives a suggested title for an element.
Syntax : title=”string”
It is often displayed as a tooltip while the element is loading.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 3


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Apart from above it can carry id, lang, dir, title attributes and browser specific attributes like
topmargin, bottommargin, rightmargin, leftmargin, scroll, bgproperties, marginheight, marginwidth.

A body section can contain comments, block and inline elements, character entities, tables,
forms, hyperlinks, images, lists etc.
Block elements are displayed like blocks of text. Browsers display block elements as text
followed with a line break and some padding automatically. Some of the block elements are
paragraphs, headings, preformatted text, lists etc. Inline elements have no automatic line break or
padding like block elements. Examples for inline elements are bold, big text, small text, strong
text etc.

Basic Text Formatting


Basic text formatting elements are h1, h2, h3, h4, h5, h6, p, br, pre etc.

Headings : <hn> elements


A heading on a form tells the purpose of the form. They can be used to help structure a
document. HTML offers six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>,
<h5>, <h6>. <h1> elements is the largest of the six and <h6> is smallest. The levels of heading are
shown with the following example.
<!DOCTYPE html>
<html>
<head>
<title>Heading Example</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>

Heading elements can carry the following attributes : align, class, id, style, title, dir, lang
Attribute Value Description
align left, center, Indicates the alignment of the heading.
right

Paragraphs <p> Element

The paragraph tags, <p> and </p> provides the most basic block formatting for web page text.
Their use is straightforward. Place the opening tag (<p>) at the start of the paragraph and the
ending tag (</p>) at the end of the paragraph. The user agent (browser) will render the text in

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 4


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
between the paragraph tags as a paragraph. Usually the browser displays a blank line in between
two paragraphs. Consider the below example:

Example :
<p>This is first paragraph</p>
<p>This is second paragraph</p>
Paragraph <p> element can carry the following attributes : align, class, id, style, title, dir, lang

Line Breaks : <br /> element


The break tage <br /> used to break the current lines and inserts a blank line. The slash indicates
that the tag is both an opening and closing tag. The space before the slash represents the absent
content.

For example
<p>Web Technologies <br /> HTML</p>
Displays
Web Technologies
HTML

Centering Content : <center> element


You can use <center> tag to put any content in the center of the page or any table cell.
Eg: <center>This text appears in the middle</center>

Preformatted Text : <pre> element


Multiple spaces are suppressed using browsers. Sometimes browsers need to preserve
formatting. Any text between <pre>….</pre> will preserve the formatting of the source
document

Presentational Elements
Bold Text : Anything that appears within <b>...</b> element, is displayed in bold.
Italic Text : Anything that appears within <i>...</i> element is displayed in italicized.
Underlined Text : Anything that appears within <u>...</u> element, is displayed with underline.
Strike Text : Anything that appears within <strike>...</strike> element is displayed with
strikethrough, which is a thin line through the text.
Superscript Text : The content of a <sup>...</sup> element is written in superscript; the font size
used is the same size as the characters surrounding it but is displayed half a character's height
above the other characters.
Subscript Text : The content of a <sub>...</sub> element is written in subscript; the font size
used is the same as the characters surrounding it, but is displayed half a character's height
beneath the other characters.
Larger Text: The content of the <big>...</big> element is displayed one font size larger than the
rest of the text surrounding it.
Smaller Text : The content of the <small>...</small> element is displayed one font size smaller
than the rest of the text surrounding it.
Horizontal Lines : <hr /> element

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 5


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Horizontal lines are used to visually break up sections of a document. The <hr> tag creates a line
from the current position in the document to the right margin and breaks the line accordingly.
Eg: <hr />
Monospaced Text : The content of <tt> element is written in monospaced font

Example :
<!DOCTYPE html>
<html>
<head>
<title>Text Formatting</title>
</head>
<body>
<p><b>Bold Text </b></p>
<p><i>Italicized Text </i></p>
<p><i>Underlined Text </i></p>
<p><strike>Strikethrough</strike>text </p>
<p>Superscript text : (a+b)<sup>2</sup> </p>
<p>Subscript text : log<sub>2</sub> </p>
<p>Larger text : <big>Big</big> </p>
<p>Smaller text : <small>Small</small> </p>
</body>
</html>
Grouping Content
The <div> and <span> elements allow you to group together several elements to create sections
or subsections of a page.
For example, you might want to put all of the footnotes on a page within a <div> element to
indicate that all of the elements within that <div> element relate to the footnotes. You might then
attach a style to this <div> element so that they appear using a special set of style rules.
The <span> element, on the other hand, can be used to group inline elements only. So, if you
have a part of a sentence or paragraph which you want to group together, you could use the
<span> element as follows.
<!DOCTYPE html>
<html>
<head>
<title>Div Tag Example</title>
</head>
<body>
<div id="menu" align="middle" >
<a href="/index.htm">HOME</a> |
<a href="/about/contact_us.htm">CONTACT</a>
<a href="/about/index.htm">ABOUT</a>
</div>
<p>This is the example of <span
style="color:green">span tag</span> and the <span
style="color:red">div tag</span> alongwith CSS</p>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 6


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Character Entities
Character entities are used for special characters which cannot be keyed in directly from the
keyboard or that may cause ambiguity. These special characters can be referred in a web
document using special coded characters known as character entities. All the character entities
are written like &entity-name; or &entity-number;
Some of the useful character entities are &gt; &lt; &copy;&nbsp etc.

Lists
Lists are used to display list of items in the webpage. It is possible to create three types of lists in
HTML
Unordered lists - they are like lists of bullet points
Ordered lists - uses sequence of numbers or letters instead of bullets
Definition lists - allows to specify a term and its definition

Unordered Lists:
<ul> element is used to create unordered lists. Each bullet point or the text is enclosed in between
<li>…</li> tags, stands for list item. A list item can contain any html element like images, links
etc.
Attributes of <ol> tag are
Attribute Value Description
Compact Compact Specifies that the list should render smaller than normal
Type Disc | square Specifies the kind of marker to use in the list
| circle

Example:
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Ordered Lists:
These are used to display the items, for those the order is mandatory. The list items can be
prefixed with numbers (1, 2, 3…), upper case letters(A, B, C…), lower case letters(a, b, c….),
roman numeral both upper and lower case(I, II, III…i, ii,iii..).
An ordered list is contained inside <ol> tag.
Each list item is enclosed between <li>…</li>
Apart from compact and type attributes, it has an additional start attribute.

Attribute Value Description


Start Number Specifies the start value of an ordered list
Type 1|A|a|I|i Specifies the kind of marker to use in the list

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 7


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Examples
<ol> <ol start="50" type=”I”>
<li>HTML</li> <li>ASP</li>
<li>CSS</li> <li>PHP</li>
<li>JavaScript</li> <li>JSP</li>
</ol> </ol>

Definition Lists
The definition lists are special kind of lists for providing terms followed by a short text definition
or description for them. These lists are contained inside <dl> element.
<dl> element contains alternating <dt> and <dd> elements.
<dt> element contains the term of definition.
<dd> element contains the description for the definition.
Following example describes different kinds of lists using definition lists.
<dl>
<dt>Unordered List</dt>
<dd>A list of bullet points</dd>
<dt>Ordered List</dt>
<dd>A numbered list</dd>
<dt>Definition List</dt>
<dd>A list of terms and definitions</dd>
</dl>

Nested Lists
It is possible to nest one list inside another list. For example a numbered list with separate points
corresponding to one of the list items.
<ol type=”I”>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
<li>Item Four
<ol type=”i”>
<li>Item 4.1 </li>
<li>Item 4.2 </li>
<li>Item 4.3 </li>
</ol>
</li>
<li>Item Five</li>
</ol>

Links
A webpage can contain various links that take you directly to other pages and even
specific parts of a given page. These links are known as hyperlinks. Hyperlinks allow visitors to
navigate between Web sites by clicking on words, phrases, and images.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 8


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
A link is specified using HTML tag <a>. This tag is called anchor tag and anything
between the opening <a> tag and the closing </a> tag becomes part of the link and a user can
click that part to reach to the linked document. Following is the simple syntax to use <a> tag.
<a href="Document URL" ... attributes-list>Link Text</a>
Example : <a href=www.vishnu.edu.in>vit</a>

Attributes of anchor tag are


Attribute Value Description
href URL Specifies the URL of the page the link goes to
target _blank to specify the location where linked document is opened. _blank
_self opens the linked document in a new window or tab. _self Opens
_parent the linked document in the same frame._parent Opens the linked
_top document in the parent frame. _top Opens the linked document
targetframe in the full body of the window. Targetframe Opens the linked
document in a named targetframe.
Download Filename Specifies that the target will be downloaded when a user clicks on
the hyperlink

Internal navigation
The id attribute can be used to create bookmarks inside HTML documents. Anchor tag can be
used to provide internal navigation by using id attribute. The target location within the web
document is marked by using id attribute.
Eg. <h1 id=”top”> main heading</h1>
The anchor tag which is used to reach that particular heading is
<a href=”#top”>heading</a>
For internal navigation using anchor tag, href is specified as elements id preceded by „#‟ sign.

Example :
<html>
<head><title>Internal Navigation</title> </head>
<body>
<ul>
<li><a href="#one">HTML</a></li>
<li><a href="#two">CSS</a></li>
<li><a href="#three">JavaScript</a></li>
</ul>

<h1 id="one">Hyper Text Markup Language</h1>


<h1 id="two">Cascading Style Sheets</h1>
<h1 id="three">JavaScript</h1>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 9


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Tables
Tables are commonly used to display all manner of data, such as timetables, financial reports and
sports results. Tables are the common way to organize data in web documents. A table organizes
data in the form of rows and columns. The basic table elements are
<table> - to specify a table
<tr> - to specify a table row
<td>,<th> - to specify a table cell in a row
The relationship between these basic elements is shown in the following figure.

<table> Element
The <table> element is the containing element for all tables.
An HTML table consists of the <table> element and one or
more <tr>, <th>, and <td> elements. The table tag carry all
universal attributes like align, bgcolor, border, cellpadding,
cellspacing, dir, frame, rules, summary, width
Attribute Value Description
Border 0 – default Specifies the width of the table border in pixels.
Any numeral
Cellpadding Amount of space Used to create a gap between the edges of a cell and its
or padding in contents
pixels Eg: cellpadding=”5”
Cellspacing Amount of space Used to create space between the borders of adjacent cells.
in pixels Eg: cellspacing = “6”
Summary Text Specifies a summary of the content of a table
Width Pixels | % Specifies the width of a table

<tr> element
The <tr> element is used to contain each row in a
table. Anything appearing within a <tr> element
should appear on the same row. It can carry align,
bgcolor, valign attributes.

Attribute Value Description


Valign Top Specifies the vertical alignment of the contents of each cell in
Middle the row.
Bottom Syntax: valign=”vertical position”
baseline
<td> and <th> elements
<td> and <th> elements are used to represent a cell in the table. <th> element is mainly used for
the cells containing table headings. By default the contents of <th> element are displayed in bold
font, horizontally aligned in the center of the cell. Both of these elements carry same set of
attributes, each of which applies just to that cell. <th> <td> elements carry the following

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 10


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
attributes : abbr, align, axis, bgcolor, char, charoff, colspan, headers, height, nowrap, rowspan,
valign etc.
Attribute Value Description
Abbr Text Specifies an abbreviated version of the content in a cell
Nowrap Nowrap Specifies that the content inside a cell should not wrap
Colspan Number Used to specify how many columns of the table a cell will
span across. The value of the colspanattribute is the number of
columns the cell stretches across.
Eg: colspan=”2”
Rowspan Number Specifies the number of the table a cell will span across, the
value of the attribute being the number of rows the cell
stretches across.
Eg: rowspan=”2”
The three elements for separating the head, body, and foot of a table are
<thead> to create a separate table header
<tbody> to indicate the main body of the table
<tfoot> to create a separate table footer.

<caption> attribute
<caption> element is used to add caption to a table. <caption> element is used after the opening
<table> tag and before the first row or header
Example :
<html>
<body>
<table align="center" border="1">
<caption>Courses - Intake</caption>
<tr>
<th rowspan="2">Course</th>
<th colspan="2">Details</th>
</tr>
<tr>
<th>Branch name</th>
<th>Intake</th>
</tr>
<tr>
<td rowspan=3>B.Tech.</td>
<td>CSE</td><td>180</td>
</tr>
<tr>
<td>ECE</td>
<td>180</td>
</tr>
<tr>
<td>EEE</td>
<td>120</td>
</tr>
</table>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 11


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Images
<img> element is used to add images to a HTML document. It carries a source attribute
indicating the source of the image and alt attribute whose value is an alternate description for the
image in case it does not load.
Example : <img src=”logo.gif” alt=”VIT logo />

<img> tag carries the following attributes : src, alt, align, border, height, width, hspace, vspace, ismap,
usemap name.

Attribute Value Description


src url To specify the URL of the image to load.URL can be absolute
or relative.
Alt Text To specify the text alternative for the image in case the user
cannot see the image.
align Top | middle | Used to align the image within the page or the element that
bottom | left | contains the image
right
Border Numeral Specfies the width of the border around the image in pixels.
Height Pixels Specifies the height of the image.
Width Pixels Specifies the width of an image.
Hspace Pixels Specifies the whitespace on left and right side of an image
Vspace Pixels Specifies the whitespace on top and bottom of an image

Forms
A form is used to collect information from the visitor of a site. It is a mechanism supported by
HTML which allows data to be sent from client to the server for processing. A form is created by
combining form controls, such as text boxes, checkboxes, select boxes and radio buttons and so
on. When a user fills in a form, the data is sent to the server in name/value pairs. The name
corresponds to the name of the form control, and the value is what the user has entered

<form> element
A form can be created in a web document by using <form> tags. Any form live inside an element
called <form>. Form controls are placed in between <form> ….</form>. A <form> element can
also contain other HTML markups such as paragraphs, headings, and so on. A <form> element
must not contain another <form> element.
Every <form> element should carry at least two attributes: action method
This element may also carry enctype, accept, accept-charset, onsubmit, onreset attributes.

Attribute Value Description


Action URL Indicates what happens to the data when the form is submitted.
Usually the value of the action attribute is a pagre or program on
a web server that will receive the information from this form
when a user presses the submit button
Eg: <form action=”process.php”>
Method Get | post Form data can be sent to the server in two ways, each
corresponding to an HTTP method
The get method, which sends the data as part of the URL

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 12


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
The post method, which hides data in the HTTP headers
Id Text To uniquely identify a form element within a page
Name Text Specifies the name of the form

Form Controls
Different types of form controls that are used to collect data from a visitor are
Text input controls Select boxes
Buttons File select boxes
Checkboxes and radio buttons Hidden controls

<input> element
The <input> tag specifies an input field where the user can enter data. <input> elements are used
within a <form> element to declare input controls that allow users to input data. An input field
can vary in many ways, depending on the type attribute.

Text Inputs
These are used to take text input and are created using <input> and <textarea> elements.

There are three types of text input used on forms


Single-line text input controls : used for items that require only one line of user input,
such as search boxes or e-mail addresses
Eg: <input type=”text” name=”txtSearch” value=”Search for” size=”20” maxlength=”64” />
Password input controls : These are just like single-line text input, except they mask the
characters a user enters.
Eg: <input type=”password” name=”pwd” size=”20” maxlength=”8” />
Multi-line text input controls : these are used when a user is required to give details that
may be longer than a single sentence. Multiline input controls are created with the
<textarea> element.
Eg: <textarea name=”txtFeedback” rows=”20” cols=”50”> </textarea>

The attribute of <input> element are


Attribute Value Description
size Number Characters to be shown
Maxlength Number Max Characters allowed
Name Text Name of the field
Value Text Initial value in the filed
Align Left, right, Alignment of the filed
center
Tabindex Number Tab order of the field
Type Text, Password, Specifies the type of <input> element
Checkbox,
Radio, Submit,
Reset, Button,
Hidden, File,
Image
Checked Checked Specifies element should be preselected (for type =

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 13


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
“checkbox” or “radio”)
Disabled Disabled Element should be disabled
Readonly Readonly Element is uneditable

The <textarea> element can take the attributes shown below


Attribute Value Description
Rows Number Rows in the field
Cols Number Columns in the field
Name Text Name of the field
Tabindex number Tab order of the field
wrap Turns of line breaking

Buttons
Buttons are most commonly used to submit a form, although they are sometimes used to
clear or reset form and even to trigger client-side scripts. To create buttons using <input> element
, type attribute can take the following values.
Submit, which creates a button that automatically submits a form
Reset, which creates a button that automatically resets form controls to their initial values.
Button, which creates a button that is used to trigger a client-side script when the user
clicks that button. Examples are shown below.

<input type=”submit” name=”votecse” value=”Vote for CSE” />


<input type=”reset” value=”clear form” />
<input type=”button” value=”calculate” />

Checkboxes
As with light switches, checkboxes can be either on or off. When they are checked they are
on and the user can simply toggle between on and off positions by clicking the checkbox.
Checkboxes can appear individually, with each having its own name, or they can appear as a
group of checkboxes that share a control name and allow users to select several values for the
same property.
A checkbox is created using the <input> element whose type attribute has a value of checkbox.
Following is an example of some checkboxes that use the same control name.
<input type=”checkbox” name=”skills” value=”html” /> HTML
<input type=”checkbox” name=”skills” value=”css” /> CSS
<input type=”checkbox” name=”skills” value=”js” /> Java Script

Radio Buttons
Radio buttons are similar to checkboxes in that they can be either on or off, but the key difference
is - When you have a group of radio buttons that share the same name, only one of them can be
selected. Once one radio button has been selected, if the user clicks another option, the new
option is selected and the old one deselected. The <input> element is used to create radio buttons
with type attribute set to “radio”
<input type=”radio” name=”skills” value=”html” /> HTML
<input type=”radio” name=”skills” value=”css” /> CSS
<input type=” radio” name=”skills” value=”js” /> Java Script

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 14


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Select boxes
A drop-down select box allows users to select one item from a drop-down menu. Drop-down
select boxes can also provide an alternative to single-line text input controls where you want to
limit the options that a user can enter. For example, you can use a select box to allow users to
indicate which country or state they live in. A drop-down select box is contained by a <select>
element, while each individual option within that list is contained within an <option> element,
the following form creates a drop-down select box for the user to select a color.
<select name=”colorselection”>
<option select=”selected” value=””>Select color</option>
<option value=”red”>Red</option>
<option value=”green”>Green</option>
<option value=”blue”>Blue</option>
</select>
The text between <option> tags is used to display options to the user.
Attributes of <select> element are
Attribute Value Description
name Text The name for the control
Size number Used to present a scrolling list box.
Multiple Multiple Allows the user to select multiple items from the menu

Attributes of <option> element are


Attribute Value Description
Value Value The value that is sent to the server if the option is selected
Selected Selected Specifies that this option is initially selected value

Frames
Frames divide a browser window into several separate pieces or panes, each pane containing a
separate HTML page. One of the key advantages offered by frames is, loading and reloading of
single panes without having to reload the entire contents of the browser window. A collection of
frames in the browser window is known as a frameset.
The window is divided into frames much as tables are organized: into rows and columns.

The <frameset> element


The <frameset> element replaces the <body> element in frameset documents. It is the attributes
of the element that specify how the browser window will be divided up into rows and columns.
These attributes are as follows:
cols specifies how many columns are in the frameset.
rows specifies how many rows are in the frameset.
The <frameset> element contains a <frame> element for each frame of the document.
In addition to the rows and cols attributes, the frameset element can also take the following
attributes: class, id, onload, onunload, rows, style, title.
Attribute Value Description
Rows pixels Specifies the number and size of columns in a frameset.
%
*
cols pixels Specifies the number and size of rows in a frameset. Rows and

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 15


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
% column width can be specified in four ways.
* Absolute values in pixels, A percentage of the browser
window, Using a wildcard symbol, As relative widths of the
browser window.

<frame> element
The <frame> element indicates what goes in each frame of the frameset. The <frame> element is
always an empty element, and therefore should not have any content, although each <frame>
element should always carry one attribute, src, to indicate the page that should represent that
frame.
The element can carry any of the universal attributes, and the following attributes: frameborder
marginwidth marginheight noresize scrolling longdesc src name
Attribute Value Description
Frameborde Number Specifies whether or not to display a border around a frame
r • „0‟ means no border
• Any numerical value other than „0‟ shows the border
Border Number Specifies the width of the border in pixels / percentages
Noresize Noresize Specifies that a frame is not resizable.
scrolling Yes, no, auto Specifies whether or not to display scrollbars in a frame

Example:
<frameset cols="25%,*,25%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>

Cascading Style Sheets

Cascading Style Sheets (CSS) allows you to define how you want your html document to
look. They allow webpage designers to improve and change the appearance of their webpages
very efficiently. This concerns features such as typeface, background, link colors, margins, and
placement of objects on a page. CSS Level 1 (or version 1) became a World Wide Web
Consortium (W3C) recommendation in 1996. The CSS Level 2 specification or version came into
effect in 1998.

Why style sheets?


A style sheet is a document that contains style information about one or more documents
written in markup languages. It is composed of a set of style rules written in a specified format.
CSS is a style sheet language that specifies how to incorporate style information in a style sheet.
The term “cascading” indicates that several style sheets can blended to present a document on
the browser‟s screen.

In the early days of HTML, one could define the various parts of a document (such as
headings, body text, bold, etc.), but it was up to the browser to interpret what that was supposed

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 16


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
to look like. Internet Explorer would display an <h1> heading tag with a particular font, size,
color, etc., and Netscape would choose a different combination, and so on. What this meant was
that you could make your page look great in one browser, then look at it in another browser and
everything would change.

There were certain display features, such as margins, that were not possible to create
unless you created strange workarounds with the available tags, such as tables. These
workarounds resulted in problems such as longer download times and very messy coding. Then,
whenever there was a change to a website, such as your boss saying, “let‟s change our website
color scheme”, this meant editing many, many pages. The W3C decided to tackle these problems
by developing the CSS standard and urging all browser companies to comply with the standards.

Advantages
1. Style sheets make managing the look of multiple web pages MUCH easier by separating
CONTENT from DISPLAY information.
2. They make web pages faster to download, very important when you are trying to reach
people with older computers.
3. The W3C is slowly phasing out old ways of coding HTML in its standards, for example the
use of the <font> tag. This translates into: professional standards are moving toward style
sheets.
4. Complexity of webpages increases significantly by writing presentation information
within webpages and changing the presentation on demand required considerable
overhead – style sheets solve these problems easily by separating document presentation
from document content written in markup languages.
5. A style sheet can be applied to different documents.
6. CSS provides many more style attributes for defining the look and feel of a webpage than
plain HTML.
Benefits
 More powerful formatting than using presentation tags
 Your pages load faster, because browsers cache the .css files
 Increased accessibility, because rules can be defined according given media
 Pages are easier to maintain and update

Style Rules:
The display instructions are called “style rules” in CSS. Style rules are simply a way of telling
anyone‟s browser how to make your web page look.

Anatomy of a style rule


There are two parts to a style rule.
The selector determines what you are styling, i.e, the HTML elements affected by this style
rule. A selector can be a single or a set of HTML elements.
the declaration is made up of one or more property:value pairs, ending in a semi-colon and
enclosed in curly brackets. It specfies the effect on HTML.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 17


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

Example :
h1 {color: red;} - means “I want my <h1> headers‟ text color to be red.”

You can have more than one declaration, or rule, for each selector. Just separate them with semi-
colons. It is to recommend to put each new rule on a new line, for easy reading. Put the ending
curly bracket after the last one.
h1 {color: red;
background: yellow;}
The above declaration means “I want all my <h1> headers‟ text color to be red and set in a
background that is yellow.” This is the pattern that you will use to compose ALL of your style
rules:

Selectors are basic building blocks of style rules. – They determine elements on which
rules are to be applied. Selector having common declarations are grouped into a comma
separated list.

h1 {color: red; } h2 {color: red; }h3 {color: red; }


can be specified as
h1, h2, h3 {color: red; }

Universal selector applies its style to all elements in the document, it is denoted by ( * )
Eg: * { color : red; }
Makes all elements in the document red.
Descendent selector, allow us to determine the elements depending upon their hierarchical
relationship.
Eg: p b { color:red; }
<b>Hello </b> <p> <b> World! </b> </p>
Output is : Hello World!

Style rules can be coded in three ways


1. Inline styles
2. Internal Style sheets
3. External Style Sheets

Inline Styles
Style information is incorporated directly into the HTML opening tags and apply only to
the content of that tag.
This is least flexible styling method.
Styles for an HTML element is specified using style attribute.
General form of style attribute is
Style = “ property-1:value1; property-2:value2;………; property-n:valuen;”

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 18


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Eg: <h1 style=”color:red;”> This is header </h1>
It is recommended that the property value pairs are followed by semicolon

<html>
<body>

<h1 style="color:blue; margin-left:50px;">This is a


heading.</h1>
<p>This is a paragraph.</p>

</body>
</html>

Internal Style Sheets (Embedded Style Sheets)


In this case, style specifications are placed as the content of style element within the header
of a document.
The general form of the content of a style element is
<style type=”text/css”> Eg: <style>
rule list P { color : green }
</style> </style>
Type is the attribute for <style> element. Type specifies MIME type of the <style> element
content values can be “text/css”
An Internal style sheet is a set of styles, created inside an HTML document.
These styles are useful when you want to apply similar styles to all the elements present
on a webpage.
<html>
<head>
<style>
body {
background-color: #d0e4fe;
color: #006600;
}
h1 {
color: orange;
text-align: center;
}
p{
font-family: "Times New Roman";
font-size: 20px; color: #330099;
}
</style>
</head>
<body>

<h1>My First CSS Example</h1>


<p>This is a paragraph.</p>
<h2>This heading has no style defined for it </h2>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 19


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
External Style Sheets :
The main purpose of external style sheets is to apply styles to more than one document.
External style sheets are stored separately with an extension .css, and they are referenced
in all the documents that use them.
These sheets are written as text files with the MIME type text/css.
To make global changes to a website, only css file is edited.
<link> tag is used to include style sheets in html documents. Link to external style sheet
must appear in the head of the document.
<head>
<link rel=“stylesheet” type=“text/css” href=“style.css” />
</head>

Attributes of link tag.


rel – to specify the relationship of the linked to the document.
type – MIME type , text/css
href – specifys the URL of the style sheet document.

Example: myStyle.css
<html> body {
<head> background-color: #d0e4fe;
<link rel="stylesheet" type="text/css" color: #006600;
href="mystyle.css" /> }
</head>
<body> h1 {
color: orange;
<h1>My First CSS Example</h1> text-align: center;
<p>This is a paragraph.</p> }
<h2>This heading has no style defined for it
</h2> p{
font-family: "Times New Roman";
</body> font-size: 20px;
</html> color: #330099;
}

Importing Style Sheets


Style sheets can be imported. It is an alternative way to use style specifications from other files.
Its general form is
@import url(filename); / @import “filename”;
Differences between import and link are
@import can appear only at the beginning of the content of a style element.
The imported file can contain markup, as well as style rules
<style> tag may contain arbitrary number of import statements.
Eg: <style>
@import url(“style1.css”);
@import url(“style2.css”);
P {color:green; }
</style>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 20


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

If more number of styles are specified in a HTML document, following order is followed to
resolve the conflicting styles. Top style is having highest importance and last one is having least
importantce.
Inline Style
Internal Styles
External Styles
Browsers default style

Class selectors
To allow different occurrences of the same tage to use different style specifications class selectors
are used. CSS class allows you to style items within the same HTML element differently. A class
selector begins with a ( . ) period . A style class name is attached to a tag name with a period.

e.g: <style>
p.normal { property-value list}
p.warning { property-value list}
</style>

The class is specified in the document body with the class attribute of the affected tag

<p class=”normal”> . . . . . . . . .</p>


<p class=”warning”>. . . . . . . . </p>

Generic class
Generic classes provide the convenience of applying class of style specifications to the content of
more than one kind of tag. This is defined without a tag name in its name.
Eg: < style>
.sale { property-value list }
</style>
Usage in the body of the document
<h3 class=”sale”> . . . . . . . .</h3>
<p class=”sale”>. . . . . . . . .</p>

Id selector
An id selector allows the application of a style to one specific element.
 CSS IDs are similar to the classes, except that once a specific ID has been declared, it
cannot be used again within the same HTML file.
 IDs are used to style the layout elements of a page that are required only once.
 Classes are used to style text such that they may be declared multiple times.

The general form of id selector is as follows:


#specific-id { property-value list }
It applies to element with that particular id
#section14 {font-size: 20}
<h2 id=”section14”>this is one section</h2>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 21


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Pseudo classes
Pseudo classes are the elements that apply when something happens rather than because the
target element simply exists.
Pseudo classes for anchor tag
 Sets the color of a link
a:link {color: #009900; }
 Changes the color of a link on mouse over
a:hover {color: #333333; }
 Sets the link color on click
a.active { color: #009900; }
 Changes the color of a visited link
a:visited {color: #999999; }

CSS Properties

Font
When you style font, the most typical thing to change is the size. For HTML nowadays,
font size is not measured in “points” but in “ems.” An em is the size of the capital letter “M” in
the default font and font size which was set by the user‟s browser, which means that it could be
anything! However, this flexibility is very important. If you remember from the Accessibility
lecture, different people need different sized fonts: a visually-impaired person might have their
computer set for large size font, whereas someone else might like very small size font. You the
designer shouldn‟t force an exact size on the user, but should build in flexibility to your design to
accommodate users‟ needs. So, using an em as a unit of measurement provides web designers
with some amount of control and precision in their fonts and widths, while allowing for
flexibility on the viewer‟s part.
Font size, therefore, is relative: 1em is the size of a capital M at 100%, if you want it
smaller, you could put 0.8em which would make your font 80% of the size of the default M; if
you want it larger you can make it 1.2em which would be 120% the size of a default M, and so on.

Colors
There are sixteen pre-defined colors in HTML: aqua, black, blue, fuchsia, gray, green, lime,
maroon, navy, olive, purple, red, silver, teal, white, and yellow. That means, you can just type the
word “blue” into your code, and the browser will give you the default color for blue. If you want
more variety or nuance, there are also 216 “web safe colors” that all browsers should be able to
read accurately. You can use these colors by using the “HEX” color code system (a combination
of A-F and 0-9 to six places). The HEX system works on the RGB principle: each color is a
combination of Red Green and Blue, and the code is divided in three parts, with the first two
spaces representing Red, the second two Green, and the third two Blue. F is the highest, and 0 is
the lowest; so here are some basic patterns:

#000000 = black (total absence of color, all zeros) #FFFFFF = white (presence of all colors, all Fs)
#FF0000 = red (the red section at full level) #00FF00 = green (the green section at full level)
#FF8800 = a shade of orange (red plus green) What do you think the code would be for blue?

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 22


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Spacing
You can control the spacing of your page with margins, padding, width, and height. This
will be more important in the next session (and frankly, is a little complicated), so for now just
remember that spacing is set in pixels. A pixel is a standard size that all browsers recognize –
though it can still be somewhat flexible, depending on the size of the computer screen on which
your page is being viewed.
You will get the feel for how large pixels are after you play around with your page. Pixels
are written px, and some typical commands might include things like:

margin-left: 10px; width: 100px; height: 252px; padding: 5px 5px 5px 5px;

Background properties lowercase


property name values uppercase
background-color colorname letter-spacing number
hex value
rgb() text-indent number
background-image url(„path‟) percentage
line-height number
background-repeat repeat (default) percentage
repeat-x word-spacing number
repeat-y percentage
no-repeat
background- fixed Font Properties
attachment scroll (default) property name values
background-position center top
font-family family-name (arial)
bottom left
generic-name (arial narrow
right xy
font-size xx-large x-large
larger large
Text Properties medium small
property name values smaller x-small
color colorname xx-small length
hex value % (percentage)
rgb() font-style normal
text-align left italic
right oblique
center font-weight normal
justify higher
text-decoration underline multiples of 100 up to 900
line-through bolder
overline
blink List- Style properties
white-space number property name values
normal list-style-image url(“path”)
pre
nowrap list-style-position inside
text-transform none outside
capitalize

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 23


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
list-style-type disc border-style dashed dotted
circle double groove
square hidden inset
decimal none outset
lower-roman ridge solid
upper-roman border-width length
lower-alpha thin
upper-alpha medium
none thick
Border properties
property name values
border-color color name
hexadecimal codes
rgb color code

 We can use the following properties in any combination

 For example
border: #FF00FF 15px dotted; (for all borders)
border-color: #FF00F; (for all borders color is red)
border-left: #FF00FF 15px dotted; (only left border)
border-bottom-style: dashed; (only bottom border style is dashed)

JavaScript
Overview
JavaScript is a programming language for use in HTML pages. Invented in
1995 at Netscape Corporation. JavaScript is not Java, or even related to Java. The original
name for JavaScript was “LiveScript”. The name was changed when Java became
popular. Statements in JavaScript resemble statements in Java, because both languages
borrowed heavily from the C language. JavaScript is a complete, full-featured, complex
language.

Java Vs. JavaScript


JavaScript is different from Java. They are similar only in syntax and object orientation
concepts. Differences between Java and JavaScript are
1. Java is pure object-oriented language while javascirpt is not.
2. Object is in Java are static i.e, members of an object cannot be changed at
runtime. Objects in JavaScript are dynamic.
3. Java is strongly typed whereas JavaScript is loosely typed.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 24


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

4. Java is loaded from compiled byte code whereas JavaScript is loaded as human
readable source code.
5. Java supports block based scoping whereas JavaScript supports function based
scoping.
6. Objects in Java are class based whereas objects in JavaScript are prototype based.

JavaScript is seldom used to write complete “programs”. Instead, small bits of


JavaScript are used to add functionality to HTML pages. JavaScript is often used in
conjunction with HTML “forms”. It is mostly used to manipulate the pieces of the
document object model. JavaScripts are interpreted, and platform independent and can
be run everywhere. It is possible to see JavaScript as a general purpose language, but it
was designed for, and is used in, the specific environment of a web page inside a
browser. It is little use without interaction with this environment - which includes
buttons and frames and such-like on the page. Hence it only becomes useful when
treated together with 3 other standards, all defined by the W3C -
HTML - hyper-text markup language
CSS - cascading style sheets
DOM - the document object model

Where to put JavaScript


JavaScript is reasonably platform-independent. JavaScript code is included within
<script> tags. The script(s) can be placed in the
The head section or
the body section or
<script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
The type attribute is to allow you to use other scripting languages (but JavaScript
is the default). This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document. The semicolon at the
end of the JavaScript statement is optional. You need semicolons if you put two
or more statements on the same line. It‟s probably a good idea to keep using
semicolons

The script can be kept in a separate file so you have two files, one HTML and the
other JavaScript, and the HTML file uses the SRC attribute in the SCRIPT
element to specify the name of the JavaScript file. An external .js file lets you use
the same JavaScript on multiple HTML pages. The external .js file cannot itself
contain a <script> tag.
<head>
<script src="myJavaScriptFile.js"></script>
</head>

Placing JavaScripts in external files has some advantages:


o It separates HTML and code.
o It makes HTML and JavaScript easier to read and maintain
o Cached JavaScript files can speed up page loads.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 25


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

JavaScript can be put in an HTML form object, such as a button. This JavaScript
will be executed when the form object is used.
JavaScript code is executed during the page loading or when the browser fires an
event
o All statements are executed at page loading
o Some statements just define functions that can be called later
Function calls or code can be attached as "event handlers" via tag attributes
o Executed when the event is fired by the browser
Benefits of JavaScript
JavaScript has a number of big benefits to make webpage dynamic.
It is widely supported in webbrowsers.
Gives easy access to the document objects and can manipulate most of them.
It can give interesting animations (without long downloading times)
No need of special plug-in to use scripts.
JavaScript is relatively secure (it neither reads from local drive not writes to it)
Provides HTML designers a programming tool.
Can react to events.
JavaScript allows interactivity such as:
o Implementing form validation
o React to user actions, e.g. handle keys
o Changing an image on moving mouse over it
o Sections of a page appearing and disappearing
o Content loading and changing dynamically
o Performing complex calculations
o Custom HTML controls, e.g. scrollable table
o Implementing AJAX functionality

Problems with JavaScript


Most scripts rely upon manipulating the elements of DOM.
Webpage is useless, if the script does not work.
Because of the problems of broken scripts, many users disable JS support in their
browser.
Complex scripts take a long time to start up.

Fundamentals
Variables : variables are the dataitems that can be manipulated as the program runs. A
variable is a named value that are used in programs. Before you use a variable, you
must declare it, using the reserved word var. For example if you want to use a variable
called price, you would include
var price;
in your script. After that you could give a value to that variable by saying
price=2.50;
There is no need to delete or set it to null, if we have finished with a variable. Browser
will automatically delete when different webpage is loaded.
Rules for constructing variable names:

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 26


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

You should choose variable names that make sense to you, the programmer.
Choose names like incomeTax or rateOfPay or priceOfFish, not x or i
Variable names are case-sensitive.
Variable names must begin with a letter, digit or an underscore.
Do not use reserverd words

Scope : The scope of a variable is the region of your program in which it is defined.
o Global variables : has local scope which means it can be accessed
anywhere in a JavaScript code.
o Local variables : will be visible only within a function where it is defined
Function parameters are always local to that function

Reserved Words
 Reserved words have some special meaning.
 They cannot be used as variables, function names, methods, loop labels etc.
break else new var
case finally return void
catch for switch while
continue function this with
default if throw
delete in try
do instanceof typeof

Datatypes
Javascript provides primitive datatypes, composite datatypes and special datatypes

Primitive datatypes
o String : Consists of a sequence of zero or more unicode characters
Eg: var s = “Hello word”;
o Number : to hold an integer or a real number
Eg: var x=123; y=45.9;
o Boolean : can have only two values , either true or false.

JavaScript is a loosely typed language, the declaration for a string variable, a number
and a boolean is same. But is differentiates a string variable, a number and a boolean
from the literal value assigned to it and the context of its use.

Composite Data types


o Object: a named collection of data
o Array: a sequence of values (an array is actually a predefined object)

Special Data types


o Null: the only value is "null" – to represent nothing.
o Undefined: the only value is "undefined" – to represent the value of an
unintialized variable

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 27


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

Operators
An operator is a symbol used to perform an operation. Generally work on variables or
on constants. JavaScript supports
o Arithmetic Operators
o Comparison Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Miscellaneous Operators
Arithmetic Operators if yes then condition becomes true.
Operator Description
Logical Operators
+ Adds two operands
Operator Description
- Subtracts second operand from the first
&& Called Logical AND operator. If both the
* Multiply both operands operands are non zero then then condition
becomes true.
/ Divide numerator by denumerator
|| Called Logical OR Operator. If any of the
% Modulus Operator and remainder of after two operands are non zero then then
an integer division condition becomes true.
++ Increment operator, increases integer
value by one ! Called Logical NOT Operator. Use to
reverses the logical state of its operand. If a
-- Decrement operator, decreases integer condition is true then Logical NOT
value by one operator will make false.

Comparison Operators Bitwise Operators


Operator Description Operator Description
== Checks if the value of two operands are & Called Bitwise AND operator.
equal or not, if yes then condition becomes
true. | Called Bitwise OR Operator.
!= Checks if the value of two operands are ^ Called Bitwise XOR Operator.
equal or not, if values are not equal then
condition becomes true. ~ Called Bitwise NOT Operator.

> Checks if the value of left operand is << Called Bitwise Shift Left Operator.
greater than the value of right operand, if
yes then condition becomes true. >> Called Bitwise Shift Right with Sign
Operator.
< Checks if the value of left operand is less
than the value of right operand, if yes then >>> Called Bitwise Shift Right with Zero
condition becomes true. Operator.

>= Checks if the value of left operand is Assignment Opertors


greater than or equal to the value of right
Operator Description
operand, if yes then condition becomes
true. = Simple assignment operator, Assigns
<= Checks if the value of left operand is less values from right side operands to left
than or equal to the value of right operand, side operand

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 28


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

+= Add AND assignment operator, It adds *= Multiply AND assignment operator


right operand to the left operand and
assign the result to left operand /= Divide AND assignment operator

-= Subtract AND assignment operator %= Modulus AND assignment operator

Conditional Operators :
 evaluates an expression for a true or false value and then execute one of the two given
statements depending upon the result of the evaluation. The conditional operator has this
syntax
 Condition ? Value if true : value if false

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

String Cancatenation Operator


Strings in java can be concatenated using „+‟ operator
Eg : alert(“Hello” + “ “ + “World!”);

Displaying Content
JavaScript can "display" data in different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.

Conditional Statements

if statement - use this statement to execute some code only if a specified condition is true
Syntax:
 if (condition) {
block of code to be executed if the condition is true
}
Example :
 if (time < 20) {
greeting = "Good day";
}

if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false.
Syntax:
 if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
Example

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 29


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
 if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

if...else if....else statement - use this statement to select one of many blocks of code to be executed
Syntax:
 if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Example
 if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

switch statement - use this statement to select one of many blocks of code to be executed. Switch
selects between number of choices depending upon the value of the expression. Choices are
identified by case statements, each has a label which equals one of potential values of expression.
Optional default may be used, if none of the cases matches the expression. Every case includes one
or more statements and is terminated by a break.
Syntax: Example
 switch(expression) {  switch (new Date().getDay()) {
case n: case 0:
code block day = "Sunday";
break;
break; case 1:
case n: day = "Monday";
code block break;
break; case 2:
default: day = "Tuesday";
default code block break;
} case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 30


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Control Structures
Used for executing the same statements multiple number of times as long as the condition is true.

While loop - loops through a block of code while a specified condition is true.
Syntax:
while (condition) {
code block to be executed
}

do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and
then it will repeat the loop as long as the specified condition is true.
Syntax:
do {
code block to be executed
} while (condition);

for - loops through a block of code a specified number of times. It is the most compact form of
looping and includes the following three important parts:
o The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
o The test statement which will test if the given condition is true or not. If condition is true
then code given inside the loop will be executed otherwise loop will come out.
o The iteration statement where you can increase or decrease your counter.
Syntax
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true }
Break and continue
The break statement can be used to jump out of a loop. It breaks the loop and continues
executing the code after the loop (if any):
for (i = 0; i < 10; i++) {
if (i == 3) break;
text += "The number is " + i + "<br>";
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
for (i = 0; i <= 10; i++) {
if (i == 3) continue;
text += "The number is " + i + "<br>";
}
Functions
A function is a group of reusable code which can be called anywhere in your program. The most
common way to define a function in JavaScript is by using the function keyword, followed by a
unique function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax:
<script type="text/javascript">
function functionname(parameter-list) {
statements
}
</script>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 31


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

Example : Calculate the product of two numbers, and return the result:

function myFunction(a, b) {
return a * b;
}
Function calling
var x = myFunction(4, 3);
function name can be any combination of digits, letters, and underscore but cannot contain a
space.
Parameter Passing
When a function receives a value as a parameter, that value is given a name and can be accessed
using that name by a function.
Ex: following function takes 3 parameters name, age, shoesize.
function about_you(name, age, shoe_size)
{
document.write(“<p>Your name is “ + name);
document.write(“<p>You are“ + age + “years old”);
document.write(“<p>Your shoe size is “ + shoe_size);
}
To call this function when the page is loaded, write the body tag like this
<body onLoad=”about_you(“sai”,7,8)”>
Or simply call this like below.
about_you(“sai”,7,8)
complete javascript on to pass variables to a function, and use these variable values in the
function.
<html>
<head>
<script type="text/javascript">
function myfunction(txt) {
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction('Good Morning')" value="In the Morning">
<input type="button" onclick="myfunction('Good Evening')" value="In the Evening">
</form>
<p>By pressing a button, a function will be called. The function will alert using the argument
passed to it.
</body>
</html>

Examining the function call


In JavaScript parameters are passed as Arrays. Every function has two parameters to find
information about parameters.
function.arguments – this is the array of parameters that have been passed.
function.arguments.length – gives the number of parameters that have been passed into the
function.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 32


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

Example
<html>
<head>
<script type="text/javascript">
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
</script>
</head>
</html>
Returning values
To return values from a function return statement is used.
var reset = my_func(32);
function my_func(number)
{
var answer = Math.sin(number);
retrun answer;
}
Scoping Rules
Scoping determine how a variable can be accessed. In JS, variables can be either local/global.
Global scoping means that a variable is available to all parts of the program. They are declared
outside of any function.
Local Scoping means variables are declared inside a function. They can only be used by that
function.

Pop-up boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
prompt( ) : The prompt() method displays a dialog box that prompts the visitor for input. A
prompt box is often used if you want the user to input a value before entering a page. The
prompt() method returns the input value if the user clicks "OK". If the user clicks "cancel" the
method returns null.
Syntax: window.prompt("sometext","defaultText");
Example: var person = prompt("Enter the price", "10.00");

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 33


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
alert( ) : The alert() method displays an alert box with a specified
message and an OK button. An alert box is often used if you want
to make sure information comes through to the user. The alert
box takes the focus away from the current window, and forces the
browser to read the message.
Syntax : window.alert("sometext");
Example: alert("The price is "+price);

confirm( ) : A confirm box is often used if you want the user to verify or accept something. When
a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user
clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax : window.confirm("sometext");
Example:
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}

Objects in JavaScript
JavaScript is not a true Object-oriented language. It tries to be an Object-oriented language.
It diverges from traditional OO in its treatment of user defined objects. An object is a collection of
related methods and properties. Properties represent features and methods represent actions
performed upon those objects.
An object can be created easily by using object literal. An object literal is a comma
separated list of property-value pairs written within a pair of curly braces. The name and its
value are separated by “:”. Once an object is created its properties can be accessed using dot ( . )
operator. Javascript allows us to access the property of an object using array notation also like
objectname[„propertyname‟].

The general syntax is as follows:


objectName = {property1 : value1, property2 : value2, ….. , propertyn : valuen;}
example : p = {x:2, y:3}
It creates object p with properties x and y which have values 2 and 3.
They are accessed using p.x and p.y
for/in
for / in construct provided by JS is used to iterate through the array elements or through the
properties of an object. The general syntax is
for ( loopvariable in object) {
code to execute
}
The loop variable assume the value of each property of the object specified.
Example:
<script type="text/javascript">
var origin=new Object();
origin.x = 0;
origin.y = 0;
for(i in origin)
document.writeln(i + " = " + origin[i]);

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 34


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
origin.y = 2;
for(i in origin)
document.writeln(i + " = " + origin[i]);
</script>
Output:
x=0y=0x=0y=2

A class in javascript is defined by a function, which acts as constructor definition for class.
Objects are created with the help of this constructor function and the new operator. Class
definition for class point is given below.
function Point( ){
}
To create an object
Origin = new Point( );

Built-in Objects

JavaScript provides the following built-in objects

It is possible to use some of the built-in JavaScript objects directly in your code
– document.write(“The value of PI is “ + Math.PI);
Other objects require you to instantiate a new object
– var studentList = new Array()
Garbage collection : When a new object is instantiated, some memory is reserved. JavaScript
Automatically cleans up the memory, when a program no longer needs a variable or object
Arrays
An array is an ordered set of data elements which can be accessed through a single
variable name. data elements in an array can be accessed sequentially by reading from beginning,
or by their index. The index is the position of the element in the array. Array is a special type of
object in JavaScript. Its main function is to hold data until the script requires it.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 35


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Here arrays can be created in three ways.
1. Declare a variable and pass it some elements in array format.
var days = [“mon”, “tue”, “wed”,”thur”,”fri”,”sat”,”son”];
2. Create array object using the new keyword and set of elements to store.
var days = new Array(“mon”, “tue”, “wed”,”thur”,”fri”,”sat”,”son”);
3. Finally an empty array object which has space for a number of elements an be created.
var days = new Array(7);
JS arrays can hold mixed datatypes.
var data = [“mon”,34, 76.34];

to used the array method, specify the name of the array, which we want to operate on, followed
by a dot, then the name of the function and specify the parameters if any
arrayname.function(parameter1, parameter2, ……)

The real strength of JavaScript arrays are the built-in array properties and methods:
Properties and methods
length - The length property of an array returns the length of an array

Example:
<script>
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var an =alpha.concat(numeric);
document.write("after concatenation : " + an);
an.pop();
an.push(4);
document.write("<br \>after push and pop : " + an);
an.reverse();
document.write("<br \>after reversing : " + an);
an.sort();
document.write("<br \>after reversing : " + an);
</script>
Output :
after concatenation : a,b,c,1,2,3
after push and pop : a,b,c,1,2,4
after reversing : 4,2,1,c,b,a
after reversing : 1,2,4,a,b,c

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 36


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

String Object
Javascript automatically converts between string primitives and String objects. Creating
a String object:
var s1 = new String(“…string …. “);
The string parameter is series of characters that has been properly encoded.

Length property returns the length of the string.


Method Description
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of the character at the given
index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of the
specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence of the
specified value, or -1 if not found.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search() Executes the search for a match between a regular expression and a specified
string.
slice() Extracts a section of a string and returns a new string.
split() Splits a String object into an array of strings by separating the string into
substrings.
substr() Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring() Returns the characters in a string between two indexes into the string.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
valueOf() Returns the primitive value of the specified object.

Example :
<script type="text/javascript">
var s1 = new String("Hello World!");
document.write("character at 3 : " + s1.charAt(3));
document.write("<br \>character code at 3 : " + s1.charCodeAt(3));
document.write("<br \>length : " + s1.length);
document.write("<br \>index of World : " + s1.indexOf("World"));
document.write("<br \>last index of character l is : " + s1.lastIndexOf("l"));
document.write("<br \>uppercase : " + s1.toUpperCase());
document.write("<br \>lowercase : " + s1.toLowerCase());
</script>
Output :
character at 3 : l
character code at 3 : 108
length : 12
index of World : 6
last index of character l is : 9
uppercase : HELLO WORLD!
lowercase : hello world!

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 37


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Math Object
The Math object provides properties and methods for mathematical constants and functions.
Unlike the other global objects, Math is not a constructor. All properties and methods of Math are
static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where
x is the method's argument.

Math Properties:
Property Description
E Euler's constant and the base of natural logarithms, approximately 2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.
SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.

Math Methods
Method Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the
natural logarithm.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
sin() Returns the sine of a number.
sqrt() Returns the square root of a number.
tan() Returns the tangent of a number.

Date Object

The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
different variant of Date() constructor:
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 38


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Here is a list of each method and its description.
Method Description
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date according to local time.
getDay() Returns the day of the week for the specified date according to local time.
getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
getMilliseconds() Returns the milliseconds in the specified date according to local time.
getMinutes() Returns the minutes in the specified date according to local time.
getMonth() Returns the month in the specified date according to local time.
getSeconds() Returns the seconds in the specified date according to local time.
getTime() Returns the numeric value of the specified date as the number of milliseconds
since January 1, 1970, 00:00:00 UTC.

Example :
<script type="text/javascript">
var dt = new Date();
document.write("Date and Time : " + dt );
document.write("<br\> getFullYear() : " + dt.getFullYear() );
document.write("<br\> getDay() : " + dt.getDay() );
document.write("<br\> getHours() : " + dt.getHours() );
</script>
Output :
Date and Time : Thu Feb 05 2015 10:32:35 GMT+0530 (India Standard Time)
getFullYear() : 2015
getDay() : 4
getHours() : 10

Program to display a clock :


<head>
<script>
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}

function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 39


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

Document Object Model


The DOM is an API that defines interface between HTML documents and application
programs. Each language that interfaces with DOM must define a DOM binding to that interface.
Document in DOM have tree like structure. HTML DOM tree corresponding to an HTML
documents consists of a set of nodes, each of which represents some part of HTML document. All
elements, attributes, content may be accessed through this DOM tree, using the interfaces
provided by it. The content of an HTML document may be edited. Browsers render the document
on the screen by traversing the DOM tree.
An element is represented as element type node.
The content is represented as separate text type node.
Attributes are represented as attribute nodes.

The DOM API is used to access, traverse and manipulate HTML and XML documents. A basic
and simplified outline of typical DOM hierarchy is shown below.

Here's a few noteworthy things about the DOM:


The window object serves as the global object, you access it by just typing "window". It's
within this object that all of your JavaScript code is executed. Like all objects it has
properties and methods.
The DOM creates a hierarchy corresponding to the structure of each web document. This
hierarchy is made up of nodes. There are several different types of DOM nodes, the most
important are 'Element', 'Text' and 'Document'.
o An 'Element' node represents an element within a page. So if you have a paragraph
element ('<p>') then it can be accessed through the DOM as a node.
o A 'Text' node represents all text (within elements) within a page. So if your
paragraph has a bit of text in it can be directly accessed through the DOM.
o The 'Document' node represents the entire document.
o Also note that element attributes are DOM nodes themselves.
Representing HTML document as a DOM tree:
html element is the root of the tree.
<html>
<head>
<title> Blank Page</title>
</head>
<body>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 40


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Window object
The window object is the top-level object in the object hierarchy. It represents the entire
browser window. This object has many useful properties that may be used to get information
about the window.

properties
closed, defaultStatus , name, document, history, location, frames, navigator, screen, screenLeft,
screenTop.
methods of window object
Method Description
alert(msg) Displays a dialog box with a specified message and an OK button
blur( ) Removes focus from the window
clearInterval( ) Cancels a timeout that was set using the setInterval( ) method
close( ) Closes the window
confirm(msg) Displays a dialog box with the specified message and OK and cancel
buttons
focus() Gives focus to this window
moveBy(dx, dy) Moves this window by the specified number of pixels.
moveTo(x,y) Moves the top left corner of the window to the specified screen
coordinates.
print( ) Prints the contents of the window or frame
open( ) Opens a new browser window
prompt(msg) Displays a dialog box with a message and an input field.
stop( ) Stops the current download

Location object
This object encapsulates the current URL that is displayed in the visitor‟s browser. It has several
useful properties and methos
Property Description
Href The entire URL
Hostname URL hostname
Host Hostname and port section
Port Port section
Protocol URL protocol name including “:”
Method Description
Reload( ) Current URL is reloaded
Replace(URL) Loads the specified URL by replacing the current one

History Object
This object stores information about URLs already visited from the browser‟s window.
Property Description
current Current document URL
length Number of entries of the history object
next Next URL in the history object
previous Previous URL in the history object.
Method Description
back( ) Loads previous URL in the history list
forward( ) Loads the next URL in the history list.

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 41


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Navigator object
It contains information about the client‟s browser such as its name and version.
Property Description
appCodeName Code name of the browser
appName Name of the browser
appMinorVersion Minor version number of the browser
cpuClass Type of CPU
Platform, appVersion, userAgent, online, plugins etc.
Method Description
javaEnabled( ) Indicates whether the browser is java enabled or not

Document object
JavaScript document object has many properties that are considerably useful to web application
developers. Some properties of document object are
alinkcolor, anchors, applets, bgcolor, fgcolor, cookie, domain, forms, images, lastModified, linkcolor, links,
title, URL, vlinkcolor.

Dynamic content properties :


InnerText : the complete textual content of an element.
innerHTML:The complete content of element

Method Description
document.write() Writes HTML expressions or JavaScript code to a document
document.writeln()
document.getElementById() Returns the element that has the ID attribute with the specified
value
document.getElementsByClassName() Returns a NodeList containing all elements with the specified
class name
document.getElementsByName() Returns a NodeList containing all elements with a specified name
document.getElementsByTagName() Returns a NodeList containing all elements with the specified tag
name

Events and Event Handling


The programming which allows computations based on the activities in a browser or by
the activities performed by the user on the elements in a document is known as event-driven
programming.
An event is a specification of something significant has occurred. Examples of events are click,
submit, keyup etc. In javascript all events are specified in lowercase. An event handler is a set of
statements that handles the event. Commonly used events and their associated tag attributes are
listed below
blur - onblur load - onload
change - onchange unload - onunload
click - onclick mousedown - onmousedown
dblclick - ondblclick mouseup - onmouseup
focus - onfocus mouseout - onmouseout
keydown - onkeydown reset - onreset
keypress - onkeypress select - onselect
keyup - onkeyup submit - onsubmit

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 42


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript

The process of linking an event handler with an event is known as registration. There are two
ways to register an event handler in DOM 0 event model. First way is by assigning the event
handler script to an event tag attribute as shown below:

<input type=”button” value=”Click Me” onclick=”func( );” />


In the above code, the event handler func1 is assigned to the event attribute onclick of a button.
The following code adds two numbers on a button click
<html>

<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 = parseInt(document.myForm.textBox1.value);
value2 = parseInt(document.myForm.textBox2.value);
sum = value1 + value2;
document.myForm.textBoxSum.value = sum;
}
</script>
</head>
<body>
<form name="myForm">
First Number : <input type="text" name="textBox1" /> <br/> <br/>
Second Number : <input type="text" name="textBox2" /> <br/> <br/>
<input type="button" value="Process" onClick="calcSum()" />
<input type="text" name="textBoxSum" readonly="readonly"/>
</form>
</body>
</html>

Form validation
It would be nice to validate data that is entered into your forms at the client. Validation is simply
the process of ensuring that some data might be correct for a particular application. Two of the
form aspects can be manipulated using Javascript.
1. The data entered onto the form can be checked at submission.
2. One can actually build forms using JS.
The elements of form are held in an array. The events which are used to trigger validation
routines are onclick, onsubmit and onreset. By performing validations at client side, load on the
server reduces there by causes saving in network bandwidth and provides quick response.
Following example illustrates form validation.
<html>
<head>
<script type="text/javascript">
function validate() {
var uname = document.getElementById('uname').value;
var upwd = document.getElementById('upwd').value;
if (uname==""){
alert("Enter User name");
return false;
}

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 43


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
else if (upwd=="") {
alert("Enter password");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="loginfrm" onsubmit="validate()" action="toppage.html">
<table align="center" cellspacing="10">
<tr>
<td colspan=2 align="center" > <h1>Login Form </h1></td>
</tr>
<tr>
<td> User Name </td>
<td> <input type="text" id="uname" size=20 /> </td>
</tr>
<tr>
<td> Password </td>
<td> <input type="password" id="upwd" size=20 /> </td>
</tr>
<tr>
<td align="center"> <input type="submit" value="Submit" /> </td>
<td align="center"> <input type="reset" value="Reset" /> </td>
</tr>
</table>
</form>
</body>
</html>

Data validation is the process of ensuring that users submit only the set of characters which you
require. It is not the process of ensuring that the data is anyway accurate.

DHTML

HTML is based on thinking of a web page like a printed page: a document that is rendered
once and that is static once rendered. The idea behind Dynamic HTML (DHTML), however, is to
make every element of a page interactively controllable, before, during, and after the page is
rendered. This means you can make things move, appear and disappear, overlap, change styles,
and interact with the user to your heart‟s content. Through DHTML, users get a more engaging
and interactive web experience without constant calls to a web server or the overhead of loading
new pages, plug-ins, or large applets.
DHTML is not a language itself, but is a combination of:
 HTML 4.0 (or XHTML 1.0)
 JavaScript – the Web‟s standard scripting language
 Cascading Style Sheets (CSS) – styles dictated outside a document‟s content
 Document Object Model (DOM) – a means of accessing a document‟s individual
elements
The web page here uses simple DHTML to change the style of links to be red and underlined
when the mouse is rolled over them

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 44


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
<html>
<head>
<title>Rollover Style Changes</title>
<style>
a {text-decoration: none;}
</style>
<script>
function turnOn(currentLink) {
currentLink.style.color = “#990000”;
currentLink.style.textDecoration = “underline”;
}
function turnOff(currentLink) {
currentLink.style.color = “#0000FF”;
currentLink.style.textDecoration = “none”;
}
</script>
</head>
<body bgcolor=“#FFFFFF”>
<a href=“#home” onMouseOver=“turnOn(this);”
onMouseOut=“turnOff(this);”>Home</a>
<br>
<a href=“#contact” onMouseOver=“turnOn(this);”
onMouseOut=“turnOff(this);”>Contact</a>
<br>
<a href=“#links” onMouseOver=“turnOn(this);”
onMouseOut=“turnOff(this);”>Links</a>
<br>
</body>
</html>

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 45


Advanced Java & Web Technologies Unit I : HTML, CSS and JavaScript
Question Bank

1. What is HTML? What is its use? Explain HTML markup.


2. What are the basic or fundamental HTML tags? Create a HTML page using the basic HTML tags.
3. Explain any 10 tags in HTML/ common HTML tags with example.
4. What is HTML <TABLE> tag? Explain <TABLE> sub-tags with an example.
5. Create a webpage which displays a simple resume. Use the following elements in the webpage:
image, lists, and tables.
6. Create a webpage containing two frames. Left frame contains a hyperlink to the login page. When
the user clicks on the login hyperlink, login form should be displayed in the right frame.
7. Explain how frames are created with an example.
8. Explain how forms are created with an example.
9. Discuss clearly about tags, lists, table and images in HTML.
10. Discuss about CSS in HTML.
11. What is CSS? What is its use? Explain about CSS rules.
12. What are the different ways of specifying CSS or what are the different types of CSS?
13. Create a webpage using HTML and CSS to display your personal details. Apply CSS font
properties, text properties, border properties and background properties.
14. Write about types of CSS.
15. Write about internal CSS with an example.
16. Write about external CSS with an example.
17. Write about Inline CSS with an example.
18. What is JavaScript? What is its use? What are the different operators available in JavaScript?
19. How to create functions in Javascript? Write a small script to demonstrate functions in JavaScript.
20. What is a function? Explain how parameters are passed to function in javascript.
21. What is DOM? Explain any three objects in the DOM hierarchy.
22. Discuss DHTML with JS and write a script to generate dynamic HTML using JavaScript.
23. Explain Java Script Date Object functions with an example.
24. Write about Java Script Objects.
25. Compare HTML and Java Script
26. Explain why javascript is called as an object-based programming language.
27. Write a script which simulates the string method – indexOf( )

B Sridevi, Dept., of CSE, Vishnu Institute of Technology 46

You might also like