You are on page 1of 192

H

T
M
L
5
ANKIT SINGH

ANKIT SINGH

HTML Introduction
What is HTML?
HTML is a markup language for describing web documents (web pages).

HTML stands for Hyper Text Markup Language

A markup language is a set of markup tags

HTML documents are described by HTML tags

Each HTML tag describes different document content

Access to information: The Internet provides access to information on


various topics, such as sports, news, and education.

Communication: The Internet enables easy and rapid communication across


the world through a number of services, such as emails, chats, and social
networks.
Data transfer: The Internet helps in transferring a large amount of data, such as
files and Images.
Electronic-commerce (e-commerce): The Internet is also used as a medium of
trade by buyers and sellers, Increasing their reach and reducing tune and
geographical gaps. This is known as e-commerce, which IS defined as the process
of buying and selling of goods and services electronically.

A Small HTML Document


Example:<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

ANKIT SINGH

Example Explained:

The <!DOCTYPE html> declaration defines this document to be HTML5

The text between <html> and </html> describes an HTML document

The text between <head> and </head> provides information about the
document

The text between <title> and </title> provides a title for the document

The text between <body> and </body> describes the visible page
content

The text between <h1> and </h1> describes a heading

The text between <p> and </p> describes a paragraph

The <!DOCTYPE> Declaration


The <!DOCTYPE> declaration represents the document type, and helps the
browser to display a web page correctly.There are different document types. To
display a web page correctly, the browser must know both type and version.
The doctype declaration is not case sensitive. All cases are acceptable:
Like
<!DOCTYPE html>
<!doctype HTML>

ANKIT SINGH

The <HTML> Declaration


The Hypertext Markup Language (HTML), the standard programming language for
describing the contents and appearance of Web pages. an HTML document. The opening
HTML tag, and the closing HTML tag, < 'HTML),

The <HEAD> Declaration


The <head> element is a container for metadata (data about data) and is placed between the <html>
tag and the <body> tag.

The elements can go inside the <head> element:

<TITLE>

<MEAT>
<BASE>
<STYLE>
<LINK>
<SCRIPT>
<NOSCRIPT>

The <TITLE> Declaration


The <title> element:

Only one title of the html page

defines a title in the browser toolbar

provides a title for the page when it is added to favorites

displays a title for the html page in search-engine

ANKIT SINGH

The <META> Declaration


The <Meta> tag use to specify some keywords for your website so that
they can be easily searched by search engines. To implement such functionality. you can
use the <META> tag. The <META> tag provides additional information about the current
document in the form of name and value pairs
(META name="keywords" content="hote1, online, booking ">
(META name=author" content="Harry Anem")

The <BASE> Declaration


The <Base> tag is used to URL (Uniform Resource Locator) or address for all the
related links on a page. The hosting Images in a website located in a particular
directory. To access these Images, you can specify path of the directory by using the
href attribute of the <Base> tag.

Example:<! DOCTYPE HTML>


<HTML>
<HEAD>
<TITLE>The Base Tag Example</TITLE>
<BASE href=D:\Images\>
</HEAD>
<BODY>
<IMG src=img1.jpg></IMG><BR>Best Book For HTML
</BODY>
</HTML>

The <STYLE> Declaration


The Style is used to Making a webpage attractive colors and styles in the browser you
can used style tag.

Example:<! DOCTYPE HTML>


<HTML>

ANKIT SINGH

<HEAD>
<TITLE>The Style Tag Example</TITLE>
<style>
h1 {
color: red;
font-size: 14px;
}
P{
Font-style:italic;
}
</style>
</HEAD>
<BODY>
<h1>The Style using for style Tag</h1>
<p>Its Provides Online Booking</p>
</BODY>
</HTML>

The <LINK> Declaration


The < LINK>tag is used to establish the relationship current document to other
document and you create a best look and feel than you use the style sheet connect on
link tag

<link href=StyleHome.css rel=stylesheet>

ANKIT SINGH

The <SCRIPT> Declaration


The <script>tag use for client-side script, such as JavaScript, associated with the
document. to add Interactivity to Web pages. This tag contains various attributes that
help you add scripts in a Web page.
Example:<! DOCTYPE HTML>
<HTML>
<BODY>
<SCRIPT type="text/javascript">
var name=prompt("Please Enter Your Name","like John");
alert("Welcome "+name);
</SCRIPT></BODY>
</HTML>
prompts users to enter name by using the prompt() function and displays this name
in a message box by using the alert() function.

Please Enter Your Name

The alert ( ) function code displays the message, Welcome John when the OK
button in the prompt is clicked.

ANKIT SINGH

The <NOSCRIPT> Declaration


The <NOSCRIPT> tag display an alternate content on the browsers on which the script
have been disable or on the browsers that do not support client side scripting.
<! DOCTYPE HTML>
<HTML>
<BODY>
<SCRIPT type=text/javascript>
Document.write(Welcome To the Ankit Singh Website!)
<SCRIPT>
<NOSCRIPT>Your browser does not support script</NOSCRIPT>
</BODY>
</HTML>
The <Noscript> tag code display the text Your browser does not support scripts
If the script are not supported by the browser.

Applying Headings
The HTML allows SIX levels of headings, ranging from <H1> to <H6> The <H1> tag
is used to define the topmost heading, whereas the <H6> tag is used to define the
lowest-level heading

Example:<HTML>
<HEAD></HEAD>
<BODY>
<H1>This Example is Heading 1 </H1>
<H2> This Example is Heading 2 </H2>
<H6> This Example is Heading 3 </H6>
</BODY>
</HTML>

ANKIT SINGH

Adding paragraphs
You can use the new paragraphs in a HTML

<p>
<DETAILS>
<SUMMARY>
<P>
The <p> tag add a new paragrphs in the HTML Document.the <p>
Tag is a container the browsers automatically add one line space before and after
the content.
Example:<BODY>
<P>Welcome to the first website </P>
<p>Created by Mr. Ankit singh</P>
</BODY>

<DETAILS>
The additional content that a user can view or hide as per requirement to be
used details tag in your HTML document.
<BODY>

ANKIT SINGH

10

<DETAILS>
<P> We provide Computer Education for all type </P>
</DETAILS>
</BODY>

<SUMMARY>
A heading for the <DETAILS> TAG Users can click this heading to view or hide
the details.
Example:<BODY>
<DETAILS>
<SUMMARY>Categories of Computer Education</SUMMARY>
<P>ADCA,DCA,BASIC,TALLY,HTML,JAVA,C,C++,C#,COREL DROW,PHOTO
SHOP</P>
</DETAILS>
</BODY>

ANKIT SINGH

11

Defining a Layout
The layout of a Web page and separate individual elements or content should be
displayed on the Web page.

<DIV>
<SPAN>

<DIV>
The <DIV>tag is used to define a section in a document. It is used to group of
sections as blocks

<SPAN>
The <span> tag enables you to group and apply styles to inline elements. The tag is
dependent on the style attribute on a particular word and line.
<BODY>
<p>The demo of the <span style=color:blue;font-size:16px;> sapn </span>
tag</p>
</BODY>

ANKIT SINGH

12

Formatting a Web Page


The content on a Web page needs to be attractive content of the Web page by
using formatting tags.

<B>
<I>
<U>
<LI>
<BR>
<HR>

<B>
The <B> tag is used to bold font face.
<BODY>
<B>You can Read online HTML Code</B>
</BODY>

<I>
The <I> tag is used to Italic font face.
<BODY>
<I> You can Read online HTML Code </I>
</BODY>

ANKIT SINGH

13

<U>
The <U> tag is used to underline the text
<BODY>
<U> You can Read online HTML Code </U>
</BODY>

<LI>
The <LI> tag is used to create a lists. In HTML Document represented with special set
of tags.

Ordered or Numbered list


Unordered or Bulleted list
Definition list

Ordered or Numbered list


The ordered or a number list represents a set of items in a sequence or an order.
<BODY>
<P>Our ranking in the computer classes industry</p>
<ol><li>Ranked 1st for best teacher</li>
<li>Ranked 2nd for best education </li>
<li>Ranked 3rd for we provide high education</li><ol>
</BODY>

Unordered Or Bulleted List


Unordered or bulleted list represents a set of related items that do note follow a
specific order.

ANKIT SINGH

14

<BODY>
<ul><li>HTML </li>
<li>JAVA</li>
<li>C#</li></ul>
</BODY>

Definition list
The definition tag used one or more terms definition are to be included in an
HTML document. Its represent by the <DL> tag. And this tag to comprises two
other tags <DT> and <DD>
<BODY>
<DL>
<DT>Title1</DT><DD>This is a first definition</DD>
<DT>Title2</DT><DD>This is a second definition </DD>
</DL>
</BODY>

<BR>
The <BR> tag is used to break of the line code.
<BODY>
Welcome to the HTML<br> Book To Create by Ankit singh
</BODY>

ANKIT SINGH

15

<HR>
The <HR> tag is used to create a horizontal line
<BODY>
Welcome to the HTML<br><hr>
Book To Create by Ankit singh
</BODY>

Adding Images
The images are used to create more interesting as ideas are well communication
with images and graphics.

GIF:-

The Graphic Interchange Format The most commonly-use image format on


the web.

JPEG:ANKIT SINGH

16

Joint Photographic Experts Group The format is used when the image is a
photograph medical image or complex photographic

PNG:-

Portable Network Graphics The format is used an alternative to GIF the


PNG format a defines a portable well-compressed and well-specified
standard for bitmapped image files.
<BODY>
<IMG src=ankit.jpg></IMG>
</BODY>

Attributes for <image>


ANKIT SINGH

17

Alt

The alt attribute is use to alternate text for an image this

attribute work only your image cannot display a browser.

Height
Width

the attribute display a height your image in a browser.

the attribute display a width your image in a browser.

<IMG src=D:\image\ankit.jpg alt=ankit height=400


width=300>

Adding Navigation Links


The navigation links tag is using to link one page to another page using <A> tag
and attribute href or frame this attribute link image multimedia files to each
other.

href the href attribute specifies the URL to connect the document

using hyperlink

<A href=Honepage.html>Book Your course</A>

target the target attribute is use a browser windows you can

refer to another windows by using the target attribute

<A href=Aboutus.html target=frame1>About Us</A>

Adding Multimedia Components


The multimedia Element is used to adding audio video sound in a website and
improve visual effect of the website.

<AUDIO>
<VIDEO>

<AUDIO>
The <audio>tag provide adding a audio in a web page.
<AUDIO controls=controls src=audio1.mp3>Your browser does not
support this audio format.</AUDIO>

<VIDEO>
The <video> tag is provide displaying a video on a web page.

ANKIT SINGH

18

<VIDEO width=320 height=240 controls=controls


autoplay=autoplay src=D:\video\video2.mp4> Your browser does
not support this video format.</VIDEO>

Measuring Data and Displaying a Progress


Bar
The progress bar is use to display a progress for downloading and uploading file
such as image video audio in disk space.

<METER>
<PROGRESS>

<METER>
The <meter> tag a scalar measurement within a used to display disk usage.
<P>Display a meter</p>
<METER value=4 min=0 max=10></METER>

ANKIT SINGH

19

<PROGRESS>
The <progress> tag is used to display the progress of the task.
Progress of a task:
<PROGRESS value=12 max=100></PROGRESS>

Semantic tags

<HGROUP>
<ARTICLE>
<ASIDE>
<HEADER>
<FOOTER>

<NAV>
<FIGURE>

<hgroup>
You need to group related heading and sub heading than you used to<hgroup>
tag.
<HDROUP><H1>Book your course</H1>
<H2>Rating of the course</H2>
<H6>shot Course</H6></HGROUP>

ANKIT SINGH

20

<ARTICLE>
The <ARTICLE> tag an independent or a self-contained content
<ARTICLE><H1>Book your course</H1>
<p>This Course is specifically designed to provide details about your
course</p></ARTICLE>

<ASIDE>
the <aside> tag is used the write a note or a tip
<ASIDE><P>Get discounts on book course today</P></ASIDE>

<HEADER>
The <HEADER> tag is used to defined website heading you can used multiple
<HEADER> tag.
<HEADER><H1>Book Your course </H1>
<p>An easy way of booking your course</p> </HEADER>

<FOOTER>
The <FOOTER> tag is used to add a footer in your web page.
<FOOTER>Author: Ankit singh</FOOETR>

ANKIT SINGH

21

<NAV>
The <Nav> tag is used to group of link created by using <A> tag.
<NAV>
<A href=Course>Course</A>|
<A href=About>About Your Course</A>|
<A href=Booking>Booking</A></NAV>

<FIGURE>
The <FIGURE> tag is used to self-contained such as images diagrams photo.
<FIGURE><FIGCAPTION>HD Image</FIGCAPTION><IMG
src=localimg.jpg alt=image width300 height=400></FIGURE>

ANKIT SINGH

22

Working With Style


The style of the web page depends upon look and feel of the HTML element use same
look and feel for all web pages you used to Cascading Style Sheet (CSS)

Different ways for Apply Style sheet

Inline style
Internal style sheet
External style sheet

Inline Style
Inline style is use to particular paragraph tags the Inline style are attached directly with
the HTML tag.
<HTML>
<BODY><P style=font-size: 24px; color: red;>Course book of 2nd July
</p><p>Compare the course from other course</p></BODY>
</HTML>

Internal Style Sheet


The internal sheet is used to multiple element in a same style using inline style

ANKIT SINGH

23

<html>
<head>
<style type=text/css>
P{color:red; font-size:20px; font-style:italic;}
</style>
</head>
<body>
<p>Welcome to the first internal style created by Ankit singh</p>
<p>compare to the other book</p>
</body>
</html>

External Style Sheet


The external style sheet is used to multiple webpages with same and equal styles in the
page using External style sheet with CSS formatting.

P
{
color:red; font-size:20px; font-style:italic;
}
H1
{
color:blue;
}
Save the code mystyle.css
<html>
<head>
</head>
<link rel="stylesheet" type="text/css" href="mystyle.css">

ANKIT SINGH

24

<body>
<h1>Welcome to the first internal style created by Ankit singh</h1>
<p>compare to the other book</p>
</body>
</html>

CSS SELECTORS
To use a style any tag and you uniquely identified one than you can used CSS Selector
user defined CSS selectors ID and Class selector

Implementing the ID selector


An ID selector is used to deferent type of style than used to ID selector an ID selector
is defined by using hash symbol (#)
<HTML>
<HEAD>
<STYLE>
P
{
color:red;
}
#pname
{
color:green;font-size:20px;font-weight:bold;

ANKIT SINGH

25

}
</STYLE>
</HEAD>
<BODY>
<p id=pname>Welcome to the HTML Book</p>
<p>Book Reading facility </p>
</BODY>
</HTML>

Implementing the CLASS selector


The class selector is used to apply the same style on different types of elements in the
HTML document the class selector is defined by (.) dot symbol.
<html>
<head>
<style>
h1
{
Font-size:20px;
color:red;
font-weight:bolt;
}
h2
{
Font-size:20px;
color:red;
font-weight:bolt;
}
P
{
Font-size:20px;

ANKIT SINGH

26

color:red;
font-weight:bolt;
}
</style>
</head>
<body>
<h1>Welcome to the Ankit singh website</h1>
<h2>this site is very user friendly</h2>
<p>this site is gives information of all the HTML tag</p>
</body>
</html>

Using class selector


<html>
<head>
<style>
.name{
Font-size:20px;
color:red;
font-weight:bolt;
}

ANKIT SINGH

27

</style>
</head>
<body>
<h1 class=name>Welcome to the Ankit singh website</h1>
<h2 class=name>this site is very user friendly</h2>
<p class=name>this site is gives information of all the HTML tag</p>
</body>
</html>

Font
Text
Link
List
Background

Font
Font properties is used to customize the text is display
P
{
Font-family: Haettenschweiler;
Font-size:20px;
}
h1
{
Font-variant:small-caps;
ANKIT SINGH

28

Font-style:italic;
}

Valid Values
PROPERTY

Definition

Sample Usage

Font-Family

Is used to set the


font type for a text.

Different font
types,such as times
new roman, courier,
verdana, Helvetica,
arial, and san serif

{font-family: arial,
times roman; }

Font-Size

Is used to set the


size of a text.

Font size may be


specified in px,
percent, or in
absolute units (large
or small)

Font-Style

Is used to set the


style for a text.

Normal, italic, or
oblique

{font-size:12px: }
{ font- size: 100% ; }
{ font- size:xsmall; }
{ font -size:xlarge; }
{ font style :
italic ; }

Font-Variant

Is used to specify
whether a text
should be displayed
in small copy font or
in a normal font.

Normal or smallcaps

{ font -variant :
small- caps : }

Font-Weight

Specifies how the


characters in a text
should be displayed.

Normal or bolder
decimal values from
100 to 900

{ font weight :
bold ;}
{ font- weight :
600 ; }

Font

Is used to set all


properties in one
declaration.

Font-style||
font variant||
font weight||
font size|| fontfamily

Font : italic bold


15px arial ;

Text
Text properties Is used to change the colour alignment of text element.
P
{
letter-spacing:2px;
line-height:12px;
}
h1
{

ANKIT SINGH

29

color: red;
text-align: center;
}
Property

Definition

Valid Values

Sample Usage

text-align

Is used to set the horizontal


Alignment of the HTML
Element.

Left | right |
Center | Justify

{text align : center;


}

Text-indent

is used to the set the


indentation of the first line
in a block of text.

Length in pixels |
Percentage

{text
intent:25px; }
{text indent:5#;

Is used to specily the height


of a line

normal | number
length
in pixels
|
percentage

Is used to specify the text


direction i.e. left to right or
Right to left
Is used to set the vertical
alignment of the Html
Element.

ltr | rtl

line-height

Direction

VerticalAlign

Property

(sub | super
| baseline) ||
Length in pixels ||
percentage

{line-hight:10pt; }
{lineheight:100#; }
{line height:
normal;
}
{direction: rtl; }

{vertical-align: sub ;
}
{vertical-align:50#;
}
{vertical-align: 30px; }
{vertical-align:20px; }

Definition

Valid Values

Color

is used to set the


color of text.

text-decoration

Is used to specify the


decorations that can
be added to a text

A HEX value, on rgb


Value, of a color
name.
none | underline |
over line | linethrough

{color: red ; }
{color: # 00ff00;}
color:rgb(0,0,255 ) ;
{textDecoration:
underline;
}

texttransform

Is used to control the


capitalization of text

Capitalize |
Uppercase |
lowercase | none

{text- .
Transform:
uppercase;
}

letter-

is used to set the

normal | length

{letter-spacing:4pt;

ANKIT SINGH

Sample Usage

30

spacing

word spacing

spacing between the


characters in text

Is used to set the


spacing between the
words in a text.

where, length
specifies
an extra space
between
Characters. Negative
Values are also
allowed.
normal | length

}
{letter-spacing:-2pt;
}`

{vord-spacing:3px ;
}

Link
Link properties is used to customize the link in the HTML document.
Link: An unvisited link
Visited: A visited link
hover: this is work mouse is placed or moved over
active: A link as it appears it is clicked

<style>
a: link
{
color:blue;
}
a:visited
{
color:red;
}
a: hover
{
color:pink;
}
a:active
{
color:green;
}
</style>

List
list properties is used to look of the order and unordered HTML lists.
Ul
{
list-style-type:square;
list-style-position: inside;

ANKIT SINGH

31

Property

its--style-position

Definition

Valid Values

Sample
usage

is used to specify
the position of listitem markers
according to the
content flow:

inside outside

(List-styleposition:
inside :)

Disk I circle I
square I decimal
I
Lower-roman |
Upper-roman |
Lower-roman |
Upper-alpha |
Lower-Latin |
Upper-lain |none|
urn | none

{ list
styletype: upperalpha. }

its-style-type
is used to specify
the type of the listitem markers.

ist-style-image

is used to specify an
image on list item
markers.

ist style

Sets all the


properties in one
declaration

type || position ||
image

( list style_
image : urn
(plus.gif ) :
)
{ list style
:
Square
outside
url (plus . gif
);}

Background
Background properties is used to specify the background color image of the HTML
element.
<style>
Body
{
Background-color:lavender;
}
</style>
Property

Definition

Valid Values

ANKIT SINGH

Sample Usage

32

Background color

Is used to set
background color of
an HTML element.

Color \ transparent

(background
color : yellow ; )

Background - image

Is used to set
background image
of an HTML element.

None \ url

(background
image : url ( img .
gif ) ; )

Background

Sets all the


properties in one
declaration.

Background color \
background - image

(background : green
url ( img . gif ) } ;

Grouping Style
Style are uses to apply same style more than one selector by combining them.
H1,p
{
color:red;
}

Nesting Style
Nesting style used to style element inside the other element style this style used to
better look and feel.by using the class and ID selector.

Selector
Element1>element2

Examp
le

Description

Div>p

Select all the <p> elements, where <Div> is their


immediate Parent element.

Div p

Select all the <p> elements inside the <Div>


element.

Element1 +
element

Div+p

Select the <p> element that is placed immediately


after the <Div> element.

element 1 +
element 2

div+p

Selects the
<p> element that is
placed immediately after the <DIV>
element.

element 1 element
2

div p

Selects all
the <p> elements that follow the

Element1 element2

ANKIT SINGH

33

<DIV>
Element

hidden: hide the element form a web page.


visible: show the element on a web page.

Positioning HTML Element


If you can change the default position of HTML document than you used to the
placement of element

Position

Float

Position
The position property is used to set the position an element on a web page.

Positioning Method

Description

Static

In static positioning elements are positioned according to


the normal flow of the page.

Fixed

In fixed positioning, elements are positioned relative to


the browser window. They will not change their position
even if the browser window is scrolled.

Relative

In relative positioning, an HTML elements is positioned


relative to its normal position.

Absolute

In absolute positioning, an element can be placed at a


fixed position on the Web page. Its position will not be
affected by the flow of other elements.

Property

Definition

Valid values

Sample Usage

Auto | length|

(Bottom: 5px ;)

Bottom

Is used to set the


bottom margin for the
positioned element

Top

Is used to set the top margin


for the positioned element.

Auto| length|
percentage

(Top: 5px ;)

Left

Is used to set the


for the positioned
Is used to set the
for the positioned

Auto | length|
percentage
Auto | length|
percentage

(Left: 5px ;)

Static |
absolute | fixed
| relative

(Position:
static ;)

Right

Position

left margin
element.
right margin
element.

Is used to specify the


positioning method to be used
for on element.

ANKIT SINGH

(Right:
5px ;)

34

Float
the float property is used to place the HTML element to left or right margin.
float: left | right | none

left: set the element to the left.


right: set the element to the right.
none: the element does not float it is default value of float.

<html>
<head>
<style>
img
{
float:left;
}
.auto
{
clear:both;
}
</style>
</head>
<body>
<img src=hotel1.jpg height=300 width=500></img>

<p> Description and Services


Located on the hills of Nice, a short distance from the famousPromenade des
Anglais, Hotel Anis is one of the hotels in theCosta Azzurra (or Blue Coast) able
to satisfy the different needs of its guests with comfort and first rate services. It
is only 2 km from the airport and from highway exits. The hotel has a large
parking area , a real luxury in a city like Nice.</p>
<p class=auto>At Hotel Anis you will be welcomed amongst olive trees,
citron trees and magnolias, in gardens that hide exotic plants and in a wonderful
outdoor pool with deck chairs; protected against the suns rays by big umbrellas
you can enjoy a drink amongst thewisteria bushes, and find peace and
tranquillity enjoying Costa Azzurras mild climate.
The spacious rooms of this beautiful Mediterranean residenceoffer the possibility
of enjoying a rich breakfast buffet on thesplendid outdoor terrace where guests
may continue to enjoy frequent sunny days and mild temperature, even during
the winter months.
If you are looking for peace and tranquillity after days spent walking amongst
the city streets or under the sun, the Hotel Anis ofNice offers refreshments in its
refined indoor rooms. The lounge bar, open 24 hours a day and
the restaurant, available for grandwedding events are all in elegant air
conditioned rooms. The restaurant service is also available on the terrace.

ANKIT SINGH

35

The hotels reception is open 24 hours a day and offers bookingservices for
guided tours to Monte Carlo, Saint Paul de Venceand excursions by
boat towards Antibes and Cannes or to the nearby Isola 2000 ski resorts.
</p>
</body>
</html>

Clear
The clear property is used to turn off the float effect on HTML element.

both: Clears float from either direction.

left: Clears float from the left direction.

right: clears float from the right direction.

Applying Transitions
You want to change the color of the HTML element from red to black in the event is
mouse hover event the CSS transition provide a way to moderately change the HTML
element from one position to another.
<html>
<head>
<style>
Div
{
width:200px;

ANKIT SINGH

36

height:200px;
background:red;
-webkit-transition:width 4s;
-o-transition:width 4s;
}
div:hover
{
width:400px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

Before mouse hover

After mouse hover

ANKIT SINGH

37

Applying Animations
To apply animation effects on HTML elements. You can create an animation that will
increase the size of the element when user clicks.
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
-webkit-animation-name: example; /* Chrome, Safari, Opera */
-webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 4s;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* Standard syntax */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
</style>
</head>
<body>

ANKIT SINGH

38

<p><b>Note:</b> This example does not work in Internet Explorer 9 and


earlier versions.</p>
<div></div>
<p><b>Note:</b> When an animation is finished, it changes back to its
original style.</p>
</body>
</html>

Applying transformations
You want to rotate a cube having different pictures on its curves. CSS provides the
functionality of transformations to modify the HTML element.

2D transforms
2d transforms you can apply various transformations such as rotations or translations on
HTML element.
<html>
<head>
<style>
div
{
width:200px;
height:100px;
background-color:red;
transform:rotate(60deg);
-webkit-transform:rotate(60deg);
}
</style>
</head>
<body>
<div></div>
</body>
</html>

ANKIT SINGH

39

3D
HTML element by using 3D transforms. The using transform methods
RotateX() Rotate element at given degree around X-axis.
RotateY() Rotate element at given degree around Y-axis.

Project Time
Home style

h3{color: darkgreen; font-family: algerian;


position:absolute; right: 130px; top: 320px;}
aside p{text-align: center; background-color:
darkgreen; color: white; font-size: 15px; }
body{background-color:#D51165; backgound-image:
src("D:\ankit\3D\70.jpg"); background-repeat: repeat-x;}
details{color: darkgreen; font-family: algerian; fontsize:15px;}

ANKIT SINGH

40

h1{font-family: algerian; color: darkgreen; fontsize:20px; position: absolute; top: 0px;right:50px;}


article p{color: black: font-size: 15px; font-family: arial;
width: 550px; }
h5{font-family:arial; color: white; font-size: 16px;
float:right;}
h2{color: darkgreen; font-family:relative; top: 0px;left:
500px;}
details ul{color: #D51165; font-size: 15px;}
h4{color: darkgreen; font-family: algerian;}
video{position: absolute; right:50px top:380:}
#mainDivContainer H4{color: darkgreen; fontsize:24px;}
#callus{float: right; right:500px;}
#call{float: right; right:5px; position: absolute; top:
370px; right: 130px;}
NAV a:hover{color:pink;}
NAV A{text-decoration: none; color: white;}

Home.Html
<html>
<head>
<title>
UpComingMovies
</title>
<link rel="shortcut icon" href="movie_run.png">

ANKIT SINGH

41

<link type="text/css" rel="stylesheet" href="homestyle.css"/>


<link type="text/css" rel="stylesheet" href="ucm.css"/>
</head>
<body><div style="position:
relative;width:150px;height:auto;padding-top:100px; float:left;">
</div>
<div id="mainDivContainer" style="position: relative; width:
100%;margin-top: 0px; margin-bottom: 0px;">

<div style="width: 960px; margin-top: 5px; margin-left: auto;


margin-right: auto;">
<div style="width: 960px; height: 80px;">
<img id="logo" src="movie.png" width="100" height="100">
<h5>For Enquiry<br>Call Us 8802136955</h5>
<img id="callus" src="hi.jpg" height="50" width="50">
</div>
<div style="width:500px; height:20px; padding-left:100px textalign:center; ">
<span class="auto-style1"><b><marquee>The Ultimate Way For
Booking Movie Tickets</marquee></b></span></div>

<div id="topnav" style="float:left; width:960px; height: 20px;


word-spacing: 15px; font-size: 90%; padding-top: 6px; whitespace: nowrap; text-align:left; background-color: black;">
<nav>
<A href="homepage.html">Home</A>|
<A href="aboutus.html">AboutUs</A>|
<A href="contactus.html">ContactUS</A>|
<A href="UpComingMovie.html">UpcomingMovies</A>|

ANKIT SINGH

42

<A href="Onlinebooking.html">OnlineBooking</A>
</nav>
</div>

<div style="width: 960px height: auto; position: relative; margin:


0px; padding: 29px; overflow: hidden; background-color: white;">

<h4>Currently, showing...</h4>
<img src="207.jpg" width="222" height="200">
<img src="206.jpg" width="222" height="200">
<img src="204.jpg" width="222" height="200">
<img src="203.jpg" width="222" height="200">

<img id="call" src="202.jpg" width="222" height="200" >


<h3>Latest Hot offer</h3>
<article>
<p>ShowOnWheels is an emerging enterainment Company in the
fied of the booking online movie tickets in INDIA.
We pioneered cinema halls in INDIA by establishing the first
multiplex cinema in 2001 and the largest 9-screen multiplex
cinema in 2007.
With its head office in Los Angeles, ShowOnWheels is now
serving the viewers of major us cities.</p>
<p>Waiting in queues to book tickets for your favorite movie in
now a matter of post.
ShowOnWheels empowers you by offering a platform to book
movie tickets anyware , anytime.Whether shopping in a mall,

ANKIT SINGH

43

enjoying a vacation at a Miami beach,partying in a discotheque,


attending a confernce , or taking Your pet for a walk,
ShowOnWheels is there to reserve Your hot seat in your favorite
cinema.</p>
<aricle><br><br><br><br><br>
<details>
<summary><b>Currently, operating in:</b></summary>
<ul>
<li>Los Angeles<li>Chicago<li>Houston</li><ul>
With an annual turnover of INDIA $12 million ShowOnWheels is
expending its wings. We are lanunching three new screens in
South Africa, shortly.
The area most in flux in relation to the new media elements has
to do with synchronized
media playback, multiple audio, video, and text tracks, and media
element accessibility.
As to be expected, these areas also have the least
implementation support.
A new addition to the HTML5 media elements is the new media
controller object. This
object provides for synchronized playback among multiple audio
and video elements
in a web page. When implemented, we should be able to play
video and/or audio files
in multiple elements in the web page via one controller user
interface.
Another new addition is support for multiple audio and video
tracks within the media
resource. When this functionality is implemented, we should be
able to pick from

ANKIT SINGH

44

among a list of audio tracks in different languages, play director


commentary along
with the video, or enjoy picture-in-picture support.
Theres also browser support for multiple text tracks, too.
Currently, browsers parse
the track element and it becomes part of the Document Object
Model (DOM), but no
browser yet processes the track elements contents and provides
the caption or subtitle
text. Happily, though, there are JavaScript libraries that can
process the captions or
subtitles within the track elements, giving us at least some
interim functionality, as well
see at the end of the chapter.
</details>
<h1><br>Hurry Heavy Discounts on weekend...</h1>
<aside>
<p>
<i><b>ShowOnWheels values its customers. We keep you
updated with our new discounts and offers.We appreciate your
association!</b></i></p></aside>

<video width="380" height="268" controls autoplay="autoplay"


loop>
<source src="" type="video/mp4"/>
your browser does not support this video format.</video>
</div>
</div>
</div>
</body>

ANKIT SINGH

45

</html>

ANKIT SINGH

46

Working with Tables and


Frames
Table are used for structuring and displaying complex information in a structuring format
on a web page.
Frames provide a mechanism for positioning and displaying several web pages in
different section of a single browser window.

Creating Tables
If you want to show the result information on your website than you need to creating a
well structured of table on a webpage using tables. Tables represent complex information
in a simple and easy to understand manner. By using tables

The Basic Structure of a Table


The user for preparing different certification exams of MySQL. Once registered for an
online exam a user is provided a login ID and password the test result of the candidates.

ANKIT SINGH

47

Specifying Table Body


the table body contain data arranged in row further comprise one or multiple columns
the body of the table can be group by using the <tbody> tag.

Creating Row
The Adding rows in the table using <tr> tag. The contents place between <tr>and </tr>
tag

Creating Columns
The adding the columns to the <td> tag the <td> tags are uses within <tr>
and </tr> tags.
<html>
<body>
<table border="2">
<tbody>
<tr><th>Name</th>
<th><ul>Login Id</th>
<th>Course Name</th>
<th>Marks</th></tr>
<tr class="alt"><td>steve</td>
<td>01234</td>
<td>My sql 5 Developer certified professional Exam,part I </td>
<td>92</td></td>
<tr><td>John</td>
<td>01235</td>
<td>Mysql 5 Developer Certified Professional Exam, part II</td>
<td>85</td>
<tr class="alt"><td>Joseph</td>
<td>01236</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, Part
I</td>
<td>98</td>
<tr ><td>Michel</td>
<td>01237</td>

ANKIT SINGH

48

<td>Mysql 5 Database Administrator Certified Professional Exam, part


II</td>
<td>25</td>
</tr>
</tbody>
</body>
</html>

Combining Multiple Rows and Columns into a Single cell


That only the column of the first row should extend to four columns and display
the heading Top Three performers. The remaining rows of the table should
have four separate columns.
Using the rowspan and colspan attribute
<html>
<body>
<table border="2">
<tbody>
<tr><th colspan="4"><center>Top Three
Performers</center></th></tr>
<tr><th>Name</th>
<th><ul>Login Id</th>
<th>Coutse Name</th>
<th>Marks</th></tr>
<tr class="alt"><td>steve</td>
<td>01234</td>

ANKIT SINGH

49

<td>My sql 5 Developer certified professional Exam,part I </td>


<td>92</td></td>
<tr><td>John</td>
<td>01235</td>
<td>Mysql 5 Developer Certified Professional Exam, part II</td>
<td>85</td>
<tr class="alt"><td>Joseph</td>
<td>01236</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, Part
I</td>
<td>98</td>
<tr ><td>Michel</td>
<td>01237</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, part
II</td>
<td>25</td>
</tr>
</tbody>
</body>
</html>

Rowspan Example:
<html>

ANKIT SINGH

50

<body>
<table border="2">
<tbody>
<tr><th rowspan="6"><center>Top Three
Performers</center></th></tr>
<tr><th>Name</th>
<th><ul>Login Id</th>
<th>Coutse Name</th>
<th>Marks</th></tr>
<tr class="alt"><td>steve</td>
<td>01234</td>
<td>My sql 5 Developer certified professional Exam,part I </td>
<td>92</td></td>
<tr><td>John</td>
<td>01235</td>
<td>Mysql 5 Developer Certified Professional Exam, part II</td>
<td>85</td>
<tr class="alt"><td>Joseph</td>
<td>01236</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, Part
I</td>
<td>98</td>
<tr ><td>Michel</td>
<td>01237</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, part
II</td>
<td>25</td>
</tr>
</tbody>
</body>
</html>

ANKIT SINGH

51

The Table Caption


The users to understand the information that the table display for creating a
table title the using the <caption> closing tag </caption
<html>
<body>
<table border="2">
<caption>Test Results</caption>
<tr><th rowspan="6"><center>Top Three
Performers</center></th></tr>
<tr><th>Name</th>
<th><ul>Login Id</th>
<th>Coutse Name</th>
<th>Marks</th></tr>
<tr class="alt"><td>steve</td>
<td>01234</td>
<td>My sql 5 Developer certified professional Exam,part I </td>
<td>92</td></td>
<tr><td>John</td>
<td>01235</td>
<td>Mysql 5 Developer Certified Professional Exam, part II</td>
<td>85</td>
<tr class="alt"><td>Joseph</td>

ANKIT SINGH

52

<td>01236</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, Part
I</td>
<td>98</td>
<tr ><td>Michel</td>
<td>01237</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, part
II</td>
<td>25</td>
</tr>
</body>
</html>

<html>
<head>
<style>
th
{
font-size:18px;
text-align:center;
padding-top:3px;
background-color:#BDB76B;
color:#006400;

ANKIT SINGH

53

}
caption
{
font-size:35px;
color:black;
}
td
{
font-size:15px;
border:1px solid #008B8B;
padding:3px;
background-color:khaki;
}
tr.alt td
{
color:#F0E68C;
background-color:#B22222;
}
</style>
</head>
<body>
<table border="2">
<caption>Test Results</caption>
<tr><th colspan="4"><center>Top Three
Performers</center></th></tr>
<tr><th>Name</th>
<th><ul>Login Id</th>
<th>Coutse Name</th>
<th>Marks</th></tr>
<tr class="alt"><td>steve</td>
<td>01234</td>
<td>My sql 5 Developer certified professional Exam,part I </td>
<td>92</td></td>
ANKIT SINGH

54

<tr><td>John</td>
<td>01235</td>
<td>Mysql 5 Developer Certified Professional Exam, part II</td>
<td>85</td>
<tr class="alt"><td>Joseph</td>
<td>01236</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, Part
I</td>
<td>98</td>
<tr ><td>Michel</td>
<td>01237</td>
<td>Mysql 5 Database Administrator Certified Professional Exam, part
II</td>
<td>25</td>
</tr>
</body>
</html>

ANKIT SINGH

55

ANKIT SINGH

56

ANKIT SINGH

57

Accessing Multiple Web Page Using Frames


Which makes it look like a single page. This is made possible by using the
concept of frames. A frame is a rectangular region in a browser window.
The first frame that is named as HeaderFrame display the name of the website.
The second frame that is named as NavigationFrame contains the links to the
various MySQL courses. The third frame that is named as ContentFrame display
the web page.

The <IFRAME> Tag


the HTML <iframe> tag is used to specify an inline frame. It allows you to divide
a web page into sections or frames.

src is used to the location or the URL of the web page.


name is used assign a name of the frame
seamless is a Boolean attribute
srcdoc is used to an HTML code that defines the content to be display
inside the frame.

Height is used to set the height of the frame


Width is used to set the width of the frame

Home.HTML page
<html>
<body>

ANKIT SINGH

58

<iframe src="head nav.html" name="headerframe"


width="100%"height="135"></iframe>
<iframe src="nav.html" name="navigationframe"
width="25%"height="500"></iframe>
<iframe align="right"
name="contentFrame"width="74%"height="500"></iframe>
</body>
</html>

NAV.HTML
<html>
<head>
<style>
body
{background-color:#00C0F3;}
ul {margin:0; padding:0;list-style:none width:350px}
ul li a{display:block; text-decoration:none; color Black; background:
#B3ECFC; padding: 5px border:1px solid #ccc; border-bottom:0;}
ul{margin:0;padding:0;list-style:none;width:320px;}
li:hover ul{display: block;}
a:hover{background-color:#5E9DC9;}
</style>
</head>
<body>
<ul><li><A href="E:\book niit\new folder\HTML5 Media.pdf"
target="contentFrame">HTML</A></li>
<li><A href="E:\book niit\new folder\"
target="contantFrame">SQL</A></li>
<li><a href="">ASP.NET</a></li><ul>
</body>

ANKIT SINGH

59

</html>

HEAD NAV.HTML
<html>
<head>
<style>
body
{background-color:#00C0F3;}
h1{color:white;font-size:45;}
</style>
</head>
<body>
<center>
<h1 >Learn HTML</h1>
</body>
</html>

ANKIT SINGH

60

ANKIT SINGH

61

Project Time
Home style

h3{color: darkgreen; font-family: algerian; position:absolute; right:


130px; top: 320px;}

ANKIT SINGH

62

aside p{text-align: center; background-color: darkgreen; color: white;


font-size: 15px; }

body{background-color:#D51165; backgound-image:
src("D:\ankit\3D\70.jpg"); background-repeat: repeat-x;}

details{color: darkgreen; font-family: algerian; font-size:15px;}

h1{font-family: algerian; color: darkgreen; font-size:20px; position:


absolute; top: 0px;right:50px;}

article p{color: black: font-size: 15px; font-family: arial; width: 550px; }

h5{font-family:arial; color: white; font-size: 16px; float:right;}

h2{color: darkgreen; font-family:relative; top: 0px;left: 500px;}

details ul{color: #D51165; font-size: 15px;}

h4{color: darkgreen; font-family: algerian;}

video{position: absolute; right:50px top:380:}

#mainDivContainer H4{color: darkgreen; font-size:24px;}


#callus{float: right; right:500px;}
#call{float: right; right:5px; position: absolute; top: 370px; right:
130px;}
NAV a:hover{color:pink;}

ANKIT SINGH

63

NAV A{text-decoration: none; color: white;}

Ucm style
<style>
table{position:absolute; top:140px; left:10px; right:120px; border:solid
4px green;}
td{text-align:center;border:solid 1px green; padding:3px;}
th{background-color:green; color:white;border:solid 1px green;}
tr{color:green}
</style>

Ucm.HTML
<html>
<head>

<title>
UpComingMovies
</title>
<link rel="shortcut icon" href="movie_run.png">
<link type="text/css" rel="stylesheet" href="homestyle.css"/>
<link type="text/css" rel="stylesheet" href="ucm.css"/>
<script type="text/javascript">
function onlinebooking()
{

ANKIT SINGH

64

alert("The Bookings for the Upcoming Movies are not Currently


Available");
}</script>
</head>
<body><body><div style="position:
relative;width:150px;height:auto;padding-top:100px; float:left;">
</div>
<div id="mainDivContainer" style="position: relative; width:
100%;margin-top: 0px; margin-bottom: 0px;">
<div style="width: 960px; margin-top: 5px; margin-left: auto; marginright: auto;">
<div style="width: 960px; height: 80px;">
<img id="logo" src="movie.png" width="100" height="100">
<h5>For Enquiry<br>Call Us 9225648543</h5>
<img id="callus" src="hi.jpg" height="50" width="50">
</div>
<div style="width:500px; height:20px; float: left; text-align:center;">
<span class="auto-style1"><b>The Ultimate Way For Booking Movie
Tickets</b></span></div>

<div id="topnav" style="float:left; width:960px; height: 20px; wordspacing: 15px; font-size: 90%; pading-left:60px; padding-top: 6px;
white-space: nowrap; text-align:left; background-color: black;">
<nav>
<A href="homepage.html">Home</A>|
<A href="aboutus.html">AboutUs</A>|
<A href="contactus.html">ContactUS</A>|
<A href="UpComingMovie.html">UpcomingMovies</A>|
<A href="Onlinebooking.html">OnlineBooking</A>
</nav>

ANKIT SINGH

65

</div>

<div style="width: 960px height: AUTO; position: relative; margin: 0px;


padding: 29px; overflow: hidden; background-color: white;">
<h4><b><i><center>UpcomingMovies</center></i></b><h4>
<table><tr><th>Movie Category</th>
<th>Movie Title</th>
<th colspan="3">starring</th>
<th>Director</th>
<th>Release Date</th>
<th>Certificate</th>
<th>Online Bookings</th></tr>
<tr>
<td rowspan="2">Thriller</td>
<td>A Dame to kill for</td>
<td>Jennifer Lawrence</td>
<td>Patrick</td>
<td>Evan</td>
<td>Freddie Highmoree</td>
<td>12 Jan,2015</td>
<td>INDIA</td>
<td><a onclick="onlinebooking();" >BookYourShow</a></td></tr>
<tr><td>prisoners</td>
<td>Evan Rachel Wood</td>
<td>Rachel Wood</td>
<td></td>
<td>Victoria A.</td>

ANKIT SINGH

66

<td>19 Jan,2015</td>
<td>INDIA</td>
<td><a href="">BookYourShow</a></td></tr>
<tr><td rowspan="3">Romantic</td>
<td>A Walk to remember-II</td>
<td>Ellen page</td>
<td>Rechel Wood</td>
<td>Victoria</td>
<td>Freddie Highmoree</td>
<td>27 Feb, 2013</td>
<td>india</td>
<td><a href="">BookYourShow</a></td></tr>
<tr><td>Twilight Saga</td>
<td>patrick</td>
<td>Wood A.Han</td>
<td>Victoria</td>
<td>Victoria A.</td>
<td>17 May,2015</td>
<td>india</td>
<td><a href="">bookyourshow</a></td></tr>
<tr><td>if only_ii</td>
<td>Ellina smith</td>
<td>Rachel Wood</td>
<td></td>
<td>Robert vann</td>
<td>23 june, 2015</td>
<td>a</td>

ANKIT SINGH

67

<td><a href="">bookyourshow</a></td></tr>
<tr><td rowspan="4">Action</td>
<td>star wars</td>
<td>robert</td>
<td>logan lerman</td>
<td></td>
<td>ariana grande</td>
<td>23 june, 2015</td>
<td>india</td>
<td><a href="">bookyourshow</a></td></tr>
<tr><td>man of steel</td>
<td>patrick</td>
<td>rachel wood</td>
<td></td>
<td>victoria</td>
<td>17 may,2015</td>
<td>india</td>
<td><a href="">bookyourshow<a></td></tr>
<tr><td>area 52</td>
<td>dianna</td>
<td>alice</td>
<td></td>
<td>robert s. vann</td>
<td>28 sep, 2015</td>
<td>a</td>
<td><a href="">bookyourshow</a></td></tr>
<tr><td>2 guns</td>

ANKIT SINGH

68

<td>illiana</td>
<td>john park</td>
<td>ankit</td>
<td>josh hutcherson</td>
<td>23 oct, 2015</td>
<td>india</td>
<td><a href="">bookyourshow</a></td></tr></table></div>
</body>
</html>

ANKIT SINGH

69

ANKIT SINGH

70

Scripting
Types of Scripting
Create a dynamic and interactive web page you need to incorporate a block of code the
script can be executed either by the web browser. The requests is send to a computer
that is placed at a different location on the World Wide Web. Computer on which the
browser is running is known as the client.

Client-side scripting
Server-side scripting

Client-side Scripting
Client side scripting refers to the scripts that are executed at the client side by the web
browser running on the users computer some of the languages used for creating client
side scripts are client side JavaScript (CSJS)

Server-side Scripting
Server-side scripting refers to the scripts that are executed by the web server on the
basis of the users request. Some of the languages used for creating server-side scripting
are server-side JavaScript (SSJS)

ANKIT SINGH

71

Benefits of javaScript

Handle events java Script can be used to execute functions whenever an event
is triggered
Gather browser information java script can be used to gather browser
information such as the browser name and version.
Manipulate cookies java script can be used to access and store user information
such as client preferences and authentication information of a client computer in
the form of cookies.

Implementing JavaScript
JavaScript is one of the most popular scripting languages. It can be used to provide
functionality to a web page.
Two type of implement scripting in a web page
A script can be embedded directly into a web page by writing the javaScript code inside
the <script> tag. Or writing the JavaScript code in an external JavaScript (.js) file.

Embedding a script tag


<html>
<body>
<SCRIPT type=text/javascript>
alert(Welcome to JavaScript);
</SCRIPT>
</body>
</html>

Creating an External file


The external JavaScript file is saved with the .js extension.
alert(Welcome products on sale :\n+1.
Cmera\n+3. RED shoes\n+4. KP Watch);

LEO

Mobile\n+2.

LEO

save the file as sale.js


<html>
<body>

ANKIT SINGH

72

<h1>By Products</h1>
<SCRIPT type=text/javascript src=sale.js>
</SCRIPT>
</body>
</html>
Save the file as home.html
Rules and Conventions Used in JavaScript

Semicolons: JavaScript does not compulsorily require a semicolon to indicate the


end of the statement.
Quotes: JavaScript allows you to use either double-quotation marks( ) or single
quotation marks( ) to enclose string of characters.
Case sensitivity: JavaScript is a case-sensitive scripting language.
Comments: Comments are statements that are not executed by the interpreter
single line comment are indicated by using // and multi-line comment are indicate
by using the symbols /* and*/.

Defining Variables
A variables is a named location in memory that is used to store a value.
Quantity=5
Price=250
Declaring a variable
The using a variable in your program you should declare it first. JavaScript allow to
declare a variable by using the var keyword.
var var_name;
var employeeName ;

Assigning a value to a variable

Assigning a value to a variable after its declaration


Initializing a variable while declaring it
Initializing a variable without declaring it

Assigning a value to a variable after its declaration


var employeeName;

ANKIT SINGH

73

employeeName=Peter;

initializing a variable while declaring it


var employeeName=peter;

initializing a variable without declaring it Explicitly


employeeName=peter;

using Operators
<html>
<body>
<SCRIPT type=text/javascript>
var employeeName;
var basicSalary;
var othersAllowance;
var TotalSalary;
employeeName=peter;
basicSalary=20000;
otherallowance=1000;
TotalSalary=basicSalary+otherAllowance;
</SCRIPT>
</body>
</html>

Operator Categories

Arithmetic Operators
Assignment Operator
Arithmetic Assignment Operators
Comparison Operators
Logical Operators

ANKIT SINGH

74

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variable and literals.

Assignment Operator
An assignment operator (=) is used to assign a value or a result of an expression to a
variable.
Arithmetic Assignment Operators
Arithmetic assignment operators are used to perform arithmetic operations and assign
the value to the variable a the left side of the operator

ANKIT SINGH

75

Comparison Operators
Comparison operators are used to compare two value and perform an action on the basis
of the comparison.

ANKIT SINGH

76

Logical Operators
Logical operators are used to evaluate complex expressions in which there is a need to
evaluate a single expression or multiple expressions to assess the result.

Conditional Constructs

The ifelse Construct


The switchcase Construct

The ifelse Construct

ANKIT SINGH

77

The if statement in the ifelse conditional construct is followed by a logical expression in


parenthesis.
Syntax of the if else construct
If(exp.)
{
//statements;
}
Else
{
//statements;
}

Example
var age=5;
if(age<12)
{
alert(Sorry ! this game is for children above 12 years);
}
Else
{
alert(Play the Game);
}

Switch case Construct


Syntax for switch case
switch(variableName)
{
case ConstantExpression_1 :
//statement;
break;

ANKIT SINGH

78

case ConstantExpression_2 :
//statements;
break;
case ConstantExpression_n:
//statements;
break;
default:
//statements;
break;
}

Loop Constructs

The while loop


The do while loop
The for loop

The while loop


Syntax for while loop
while(expression)
{
statements;
}

Example
<SCRIPT type=text/javascript>
var num=0;
while(num<20)
{num=num+1; alert (num);
}
</SCRIPT>

ANKIT SINGH

79

The do while Loop


The do while loop is similar to the while loop but do while loop execute at least one time
Syntax for do while loop
do
{ statements;}
while(condition);

Example
<SCRIPT type=text/javascript>
var num=0;
do
{num=num+1;
alert (num);
}
while(num<20)
</SCRIPT>

The for Loop

ANKIT SINGH

80

The for loop allow the execution of a block of code depending on the result of the
evaluation of the text condition.

Syntax for Loop


for (initializa variavle ; text condition ;step value)
{
//code block
}

Initialize variable : Intializes the loop variable to a value


Text Condition: the condition to be checked before execution statement in the
code block.
Step value : the increment or decrement to be performed for every iteration the
execution of the for loop starts.

<SCRIPT type=text/javascript>
var num;
var sum=0;
for(num=100;num<200;num++)

ANKIT SINGH

81

{
Sum=sum+num;
}
alert(sum);
</SCRIPT>

Break and Continue Statements


Break
The break statement is used to exit the loop
while(test condition)
{
//statement1;
if(test condition1)
{
break;
}
//statement2;
//statement3;
}

Continue
The continue statement is used to skip all the subsequent instruction and take the
control back to the beginning of the loop.
while(test condition)
{
//statement1;
if(test condition1)
{
continue;
}

ANKIT SINGH

82

//statement2;
//statement3;
}

Function

Built-in functions
User-defined functions

Built-in Functions
Built-in function are ready to use as they are already coded the built-in functions
supported by JavaScript.

isNaN ()
parseInt ()
parseFloat ()
evel ()
prompt ()
confirm ()

isNaN ()
the isNaN function determines whether a parameter is not a number. The function return
true if the parameter is not a number
<html>
<body>
<SCRIPT type="text/javascript">
num1="Two thousant";num2=8000;
Result=isNaN(num1);alert(Result);
res=isNaN(num2); alert(res);
</SCRIPT>
</body>
</html>

parseInt ()
the parseInt () function parse the string parameter and return the corresponding integer.
X=5;

ANKIT SINGH

83

Y=parseInt(x);

parseFloat ()

the parseFloat () function takes a string parameter and returns a floating point number.
X=6.5;
y=parseFloat(x);

eval()
the evel () function is used to evaluate or execute a parameter if the is a expression.
<SCRIPT type=text/javascript>
var res1=0; res1=evel(5+100;
alert(res1);
</SCRIPT>

prompt ()
the prompt () function is used to display a prompt dialog box allow a user to input value.
<html>
<body>
<script>
var a,b,c;
a=parseInt(prompt("Enter number :1"));
b=parseInt(prompt("Enter number :2"));
c=a+b;
document.write(c);
</script>
</body>
</html>

ANKIT SINGH

84

confirm ()
the confirm () function is used to display a dialog box that will enable a user to verify or
accept a task. If user clicks the ok button the confirm () function return true. If the user
clicks the cancel button the confirm () function return false.
<html>
<body>
<SCRIPT type="text/javascript">
var response;
response=confirm("Do you wish to continue");
if(response==true)
{
alert("you can proceed further");
}
else
{
alert("you cannot proceed further");
}
</SCRIPT>
</body>
</html>

User-defined Functions
The user-defined function you to define your own function according to your needs.
Creating Functions
Create by function keyword
function functionName (variable1,variable2)
{
//function statement
}
A user-defined function can optionally accept a list of parameters.

ANKIT SINGH

85

Calling a Function
A function is called by using the function name .
functionName ();

Returning values from a Function


A function can return a value through the return statement.
Function functionName()
{
var variable=10;
return variable;
}

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

ANKIT SINGH

86

Creating Forms

The data entered using these form elements needs to be processed further upon
submission. Every web page should respond to end user actions such as clicking
a submit button.
Designing an HTML Form
Customers to place online order with various details such as the name contact
number and address in an online form named as Order Food Online.

Create Form
If you create a form on a web page you need to <form> tag. The <form>
Tag is define a form has on opening <form> tag and closing </form> tag.

The <form>tag supports the attribute.

Name
Id
Action
Method
Autocomplete
Novalidate
Target

Name
The name attribute is used to specify a unique name uniquely identify a

ID

form in the get or post methods


<form name=user defined name></form>
ID
ANKIT SINGH

87

The ID attribute is used to uniquely identify a form element on a web page.


<form ID=user defined Id></form>

Action
The action attribute is used to the URL of the document assumed as the location
for the form submission.
<form action=filename or URL>
Method
The method attribute is used to be submitted to the file or the URL action
attribute.

Get
Post

Get
The get value form data to the URL of the form submission. The size of data that
can be submitted using the get method.
Post
The post value dose not append the form data to the URL of the form submitted.
A large amount of data can be sent using the post method.
Autocomplete
The autocomplete attribute is used to a form should have the autocomplete on
or off.
<form Id=fileId autocomplete=on>
Novalidate
The novalidate attribute that the date in the form should not be validate by the
browser.
<form ID=fileID novalidate>
Target
the target attribute is used to the name of thee frame or the window in which
response after submission.
<form target=_blank | _self | _parent | _top | frame_name >

ANKIT SINGH

88

_blank: the response should be displayed in a new frame or windows.


_self: the response the same frame
_parent: the response the parent frame or window.
_top: the response in the full body of the window.
Frame_name: the response in the specified frame.

<form name=OrderFoodOnline ID=Order_food method=post>


</form>

Form Elements

<INPUT>
<SELECT>
<LABEL>
<FIELDSET>
<TEXTAREA>
<DATALIST>
<KEYGEN>
<OUTPUT>
<BUTTON

<INPUT>
The <INPUT> tag. Is used to input inside A form the input fields are various type
such as text box radio button or check box. Some important attributes type
value name ID autocomplete autofocus form required pattern and placeholder.
Type
The type attribute is defined the type of input field to be added on the form.

Text creates a single line text field. Type attribute is text two additional
attribute size and maxlength, the size attribute is used for limiting the

ANKIT SINGH

89

character. The maxlength attribute is defined the maximum number of


characters.

First Name:<input type=text Name=fname size=20


maxlength=20>

Password
The password field which will not display the characters being typed by the user.
Actual show the values for each character ****.
<input type=password name=accountpassword>

Radio
A radio button used to select one of the options from a set of given options.
<input type=radio name=rating of Hotel checked >5-start<br>
<input type=radio name=rating of hotel>budgeted

Checkbox
A checkbox is used to select one or more option from a set of given options.

ANKIT SINGH

90

<input type=checkbox name=Cuisine1 value=Continental Cuisine>


Continental Cuisine <input type=checkbox name=Cuisine2 value=Chinese
Cuisine> Chinese Cuisine

Submit
A submit button is used to the form data submit to the specified location using
action attribute of the form.

Formaction
It is used to a URL the form data would be submitted the submit button is
clicked.

Formmethod
It is used to the method such as get and post the form data will be sent to the
file or URL in the action attribute of the form

Reset
A reset button clears the values entered by a user in the form fields.
<input type=reset name=reset>

URL
That is used to enter a URL of a website the value in this field is automatically
validated the form is submitted.
<input type=URL name=locator>

Email

ANKIT SINGH

91

A field in an HTML form to accept the email address from the users.
<input type=email name=email_id>

Range
Creates a slider control to enter a numeric value within a range.
<input type=range max=50 min=10 step=5 value=10>

Date
Is used to define a date field in a HTML form.
<input type=date name=bday>

Time
Is used to define a time field in an HTML form.
<input type=time name=user_time>

Number

ANKIT SINGH

92

Is used to create an input field for entering a numeric value.


<input type=number name=quantity min=0 max=50>

Tel
is used to accept a telephone number form the user.
<input type=tel name=usrtel>

Image
Is used an image to be used as a submit button. The value of the type attribute
is image
<input type=image src=img_submit.gif alt=submit width=48
height=48>

Required attribute
The required attribute is used an input field must not be left empty while
submitting the form.
<input type=text name=username required>

Placeholder
Is used to a simple value for the input filed that will be displayed until the user
enters a value
<input type=text placeholder=type your name name=fname>

ANKIT SINGH

93

Select Tag
The select tag is a container tag it create a drop-down list in the form.
Option Tag
It is always used within the <select> tag. Option tag is used to create a list of
option in the drop-down list.

Selected is used that a particular option comes pre-selected.


Value is used to value of the option to be sent on the form submission.
Disabled that an option should be disabled when the page load.

Optgroup Tag
Group the related options in one group.

Disabled is used to the option group should be shown disables whan the
page load.

Label used to a label for the option group.

Label
Is used to define a label for the input fields.

For is used to bind the <label> tag with the input field same value as the
Id attribute

Form is used to the name of one or more forms.

Textarea

ANKIT SINGH

94

Text area tag is used the user can enter a large amount of text.

Rows set the number of row of text that will be visible without scrolling
up or down in the field

Cols set the number of columns of text that will be visible without
scrolling right or left in the field.

Datalist
The datalist tag is used to create a pre-defined options for an input fields.
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>

<html>
<head>
<style>

ANKIT SINGH

95

body
{
background-color:#FFEBCD;
}
.autostyle
{
color:red;
font-size:20px;
text-align:center;
}
</style>
</head>
<body>
<form action ="registration.html">
<table>
<tr class="autostyle">
<td colspan="2">OrderFoodOnline</td></tr>
<tr><td width="100%" colspan="2"></td></tr>
<tr><td><label for="name">Name:</lable></td>
<td><input type="text" name="username" Id="name"
placeholder="Enter Your Name" required></td></tr>
<tr>
<td><label for="date">Date:</label></td>
<td> <input type="date" name="date" Id="date"
required></td></tr>
<tr><td><label for="email" >Email ID: </lable></td>
<td><input type="email" name="useremail" Id="email"
placeholder="Enter Your Email Id"

ANKIT SINGH

96

Required></td></tr>
<tr>
<td><label for="Number">Contact Number</label></td>
<td><input type="tel" name="usrtel" ID="number"
placeholder="Enter Youe phone Number"

required></td></tr>
<tr><td><label for="Food">Select Food:</label></td>
<td><label for="nonveg">Non-vegetarian</label> <input
type="radio" name="food" id="nonveg">
<label for="veg">Vegetarian</label>
<input type="radio" name="food" id="veg"></td></tr>
<tr>
<td><label for="restro">Selec Restaurant:</label></td>
<td><select>
<option value="opt1">Select Your Restaurants</option>
<option value="opt2">La Figa</option>
<option value="opt3">Benihana</option>
<option value="opt4">Gallipoli</option>
<option value="opt5">Kings Road
SteakHouse</option></select></td></tr>
<tr><td><label for="drinks">Drinks:</label></td><td>
<select>
<option value="opt6">Select Your Drink</option>
<option value="opt7">Caffelatte</option>
<option value="opt8">Cappuccino</option>
</select></td></tr>
<tr><td><label for="soups">Soups:</label></td>

ANKIT SINGH

97

<td><select><option value="opt9">Select Your Soup of Your


Choice</option>
<option value="opt10">Minestrone</option>
<option value="opt11">Fonduta</option>
<option value="opt12">pasta e fagioli</option></select></td></tr>
<tr><td><label for="dishes">Dishes:</label></td><td>
<select><option value="opt13">Select the dishes of Your
choice</option>
<optgroup label="Italian">
<option value="opt14">Pasta</option>
<option value="opt15">Fish</option>
<option value="opt16">Rice</option>
</optgroup>
<optgroup label="Chinese">
<option value="opt17">Chowmin</option>
<option value="opt18">Manchurian</option>
<option value="opt19">Water chessnut
cake</option></optgroup></select></td></tr>
<tr><td><label for="orderFor">Order For:</label></td><td>
<label for="pickup">Take Away</label>
<input type="radio" name="picku" id="pickup"> <label
for="home">Home Delivery</label><input

type="radio" name="pickup" id="home"></td></tr>


<tr><td><label for="orderfor">Address:</label></td>
<td><textarea rows="3" cols"16" id="orderfor">Enter Your Address
Hera</textarea></td></tr>
<tr><td><label for="State">State:</label>
</td><td>

ANKIT SINGH

98

<input list="state" name="stat" id="state">


<datalist id="state">
<option value="Alabama">
<option value="California">
<option value="Delaware">
<option value="Florida">
<option value="Hawaii"></datalist><br>
</td></tr>
</table>
</form>
</body>
</html>

Output
Is used to represent the result of a calculation.

ANKIT SINGH

99

For is used to the relationship between input fields useds and the result
generated for the calculation.

Form the name of one or more forms to which the output tag belongs.
Name a name for the output tag.

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">
<input type="number" id="a" value="50">
+<input type="number" id="b" value="50">
=<output name="x" for="a b"></output>
</form>

Button
Is used to create a button input type submit.

Type is used to accept the value such as button submit and reset

<html>
<head>
<style>
#button{margin-left:50px;}
...</style>
</head>
<body>
...</tr>
<tr><td>

ANKIT SINGH

100

<button id="button
type="submit"><p>Submit</p></button></td><td><button
type="reset"><p>Reset</p></button></td></tr>
</body>
</html>

ANKIT SINGH

101

Working with Browser Object

A web page is displayed in a browser a user can access information not only
about the current page but also additional details such as information about
window and screen the pages the user has visited in the past or the version the
browser begin used to view the document.

Window
Document
Navigator
Screen
History
Location

Browser object represent the browser environment and provide properties and
methods for its access and manipulation.

Using the window Object


The window object is one of the highest level objects in the javaScript Object
hierarchy. It represents a browser window which display the document.

ANKIT SINGH

102

ANKIT SINGH

103

A new window displaying the hotel booking form click the hotel image:
Function open_win()
{

ANKIT SINGH

104

Windows.open
(hotelBooking.html,height=100 ,width=200)
}

Create a clock on web page


<html>
<head>
<SCRIPT type="text/javascript">
function clockTime()
{var todayDate=new Date();
var hrs=todayDate.getHours();
var mns=todayDate.getMinutes();
var scs=todayDate.getSeconds();
mns=check(mns);
scs=check(scs);
document.getElementById('displayTime').innerHTML=hrs+":"+mns+":"
+scs;
t=setTimeout('clockTime()',1000);
}
function check(t)
{
if(t<10)
{
t="0"+t;
}
return t;
}

ANKIT SINGH

105

</SCRIPT>
</head>
<BODY onload="clockTime()">
<DIV ID="displayTime"></DIV>
</BODY>
</html>

Using the document object


The document object model hierarchy. The document object provides the
properties and methods to work with many aspects of the current document
including information about forms links title current location and URL.

ANKIT SINGH

106

The used method of the document object

Write()
Writeln()
getElementsByName()
getElementsByTagName()
getElenmentsById()

ANKIT SINGH

107

write()
the document.write() method enables users to write text on a web page.
Document.write(Hello);
<html>
<head>
<style>
Body
{
Background-color:#DAA520;
}
</style>
</head>
<body>
<SCRIPT type="text/javascript">
{
var name=prompt("please enter your

name","");
document.write("<p>");
document.write("<i>");
document.write("<b>");
document.write("Welcome "+name);
document.write("</p>");
document.write("</i>");
document.write("</b>");
}

ANKIT SINGH

108

</SCRIPT>
</body>
</html>

Writeln
The writeln() method also writes text on a web page. The only difference is that
the writeln() method appends a new line character at the end of the text.
<html>
<body>
<PRE>
<SCRIPT type="text/javascript">
document.writeln("Hi !");
document.writeln("Welcome to our site!");
document.write("Have a ");
document.write("great day");
</SCRIPT>
</PRE>
</body>
</html>

ANKIT SINGH

109

getElementsByName
the webpage should be specified by a unique name. however multiple element
can also share the same name in a web page the
document.getElementsByName() method
document.getElementsByName(name_of_the_element);
<html>
<SCRIPT type=text/javascript>
function count()
{
var x=document.getElementsByName(link);
alert (x.length + Hyperlinks);
}
</SCRIPT>
<body>
<A name=link href= >Link 1</A><br>
<A name=link href= >Link 2</A><br>
<A name=link href= >Link 3</A><br>
<input type=button value=Count onclick=Count()/>
</body>
</html>

getElementsByTagName
A user can customize the background color of all text boxes on a web page a
drop down list is used to choose the background color. If the user selects the
green color from a drop down list the background color of all the text boxes in
the document changes to green.
document.getElementsByTagName(tag_name);
var x=document.getElementsByTagName(a);

ANKIT SINGH

110

alert(x.length + Hyperlinks);

getElementsById
HTML element used on a web page has an optional attribute ID which uniquely
identifies the element the document.getElementById() method
document.getElementById(id_of_the_element);
<html>
<SCRITP type=text/javascript>
function replacetext()
{
document.getElementById(para1).innerHTML=changes the content
by using the inner HTML property of getElementById() method;
}</SCRIPT>
<body>
<p ID=para1>A simple paragraph</p>
<input type=button value=change text onclick=replacetext()/>
</body>
</html>

Handling Events

ANKIT SINGH

111

ANKIT SINGH

112

ANKIT SINGH

113

ANKIT SINGH

114

<html>
<head>
<title>registration details</title>
<style>
h1,h3{
color:black;
font-size:40px;
text-align:center;
}
table{
margin-left:550px;
border:2px solid white;
background-color:gray;
}
td{
padding:10px;
border:2px solid white;}
#button{
margin-left:670px;}

ANKIT SINGH

115

</style>
<SCRIPT>
function show()
{
var fname=document.getElementById
("textbox1").value;
var lname=document.getElementById
("textbox2").value;
var age=document.getElementById
("age").value;
var address=document.getElementById
("address").value;
var gender=document.getElementById
("gender").value;
confirm("you have entered:"+ "\n name:"+fname + "" +lname+"\n
age:"+ age+"\n address:"+address+"\n gender: "+ gender + "\n\n do
you want to confirm dese details?");
}
function changecolor(val)
{
if ((val.value=="")||(val.value==null))
{
val.style.background="pink";
}
else
{
val.style.background="yellow";
}

ANKIT SINGH

116

}
</SCRIPT>
</head>
<body>
<h1>user registrartion details<hr/></h1>
<h3>plz fill the following details and get registered!!</h3><br/><br/>
<table>
<tr>
<td> first name:</td>
<td> <input type="text" name="name1" id="textbox1"
onblur="changecolor(this)"/> </td>
</tr><tr>
<td>last name:</td>
<td> <input type="text" name="name2" id="textbox2"
onblur="changecolor(this)"/> </td>
</tr><tr>
<td>age:</td>
<td> <input type="text" name="age_box" id="age"
onblur="changecolor(this)"/> </td>
</tr><tr>
<td>address:</td><td> <textarea rows="5" name="address_box"
id="address" onblur="changecolor(this)"/></textarea> </td>
</tr><tr>
<td>gender:</td><td> <select name="gender" id="gender"> <option
value="male">male</option> <option
value="female">female</option> </td>
</tr><tr>
</tr></table>
<br/><input id="button" type="button" value="register me"
onclick="show();"/>

ANKIT SINGH

117

</body>
</html>

ANKIT SINGH

118

Event Listeners
You can handle user actions or event handlers. To handle each and vary user
action or event a listener is notified.
addEventListener()
addEventListener(type,listener[,useCapture]);

type: a string representing the event type.


Listener: the object that receives a notification when an event occurs.
useCapture: is a Boolean variable specifying whether an event needs to
captured or not.

you can also remove a handler by calling the removeEventListener()


the parameters passed to the addEventListener()
<html>
<head>
<SCRIPT type="text/javascript">
function OnClick ()
{

ANKIT SINGH

119

alert("A click event has occurred on the Submit button.");


}
function AddEventHandler()
{
var Button = document.getElementById("Button");
if(Button.addEventListener)
{
Button.addEventListener("click",OnClick,false);
}
}
function RemoveEventHandler ()
{
var Button=document.getElementById("Button");
if(Button.removeEventListener)
{
Button.removeEventListener("click",OnClick,false);
}
}
</SCRIPT>
</head>
<body>
Click on the Submit button when the "click" event has a listener and
when it does not.<br>
<button onclick="AddEventHandler();">Add a "click" event listener to
the submit button</button>
<button onclick="RemoveEventHandler();">Remove the event
listener</button><br><br>
<button id="Button">Submit</button>
</body>
ANKIT SINGH

120

</html>

Using the navigator Object


The navigator object is one of the top level objects in the javaScript object the
navigator object is an independent object the own set of properties and method.

ANKIT SINGH

121

<html>
<body>
<SCRIPT type="text/javascript">
document.write(navigator.appName);
document.write(navigator.appVersion);
</SCRIPT>
</body>
</html>

Using the screen Object


The screen object enable you to access details of the users screen such as its
width, height, and resolution.

ANKIT SINGH

122

<html>
<body>
<SCRIPT type="text/javascript">
document.write("Height: "+screen.availHeight);
document.write("Width: "+screen.availWidth);
</SCRIPT>
ANKIT SINGH

123

</body>
</html>

Using the history Object


The history object contains a list of all the page that have been visited by user.

<html>
<head>
<SCRIPT type="text/javascript">
function show()
{
alert(history.length);
}
</SCRIPT>
</head>
<body>
<input type="button" value="Show History" onclick="scho()"/>
</body>
</html>

Using the location object


The location object contains information about the current URL it can also be
used to enable navigator to different URLs on the internet.
Protocol://hostname:port/pathname/search#hash

ANKIT SINGH

124

protocol: the protocol such ad HTTP and FTP is used transmit data over
the internet

hostname: the hostname of the URL such as http://www.silvertech.com


port: the port number of the URL it is optional. If the port number is not
specified for the http request.

pathname: the path in the URL such as


http://www.silvertech.com/careers.html.

search: the search string which is any portion of the URL. Followed by a
question mark such as http://www.silvertech.com/careers.html/search?
Programmer.

#hash: the internet hyperlink og a web page. Such as


http://www.silvertech.com/careers.html#position1.

ANKIT SINGH

125

<form>
<input type=button value=visitus
OnClick=location.href=http://www.xyz.com >
</form>

Working with Form Objects

Form
Button
Checkbox
Text
Textarea
Radio
Select

Form
A form accepts user inputs. When a web page containing multiple forms is
viewed in a browser
ANKIT SINGH

126

submit() submit a form to the server for processing syntax is


form1.submit()

reset() reset all the fields of the given form syntax is used for the reset()
method form1.reset()

onsubmit: Occurs a user clicks a button or hyperlink to submit the form


to the server.

Onreset: Occurs a user opts for resetting the fields of the form by clicking
the reset button or hyperlink

Button
The button object refers to the HTML button. It allows you to perform several
tasks based on user action.

click() clicking for a button MyButton.click()


focus() sets focus on a button
blur() Removes focus from the button.
onclick occurs a user clicks a button
onmouseDown Occurs amouse button is pressed
onmouseUp Occurs the mouse button is released.

Checkbox
The checkbox object refers to the HTML check box.

click()
focus()
blur()

document.form1.checkbox1

<html>
<head>

ANKIT SINGH

127

<style>
Body
{
Background-color:pink;
}
</style>
<SCRIPT>
function validate()
{
If(document.f1.check1.checked==false)
{
Alert(please select the check box);
return false
}
else
return turn
}
</SCRIPT>
</head>
<body>
<form name=f1 method=get action=thanks.html
onsubmit=return validate ();>
<input type=checkbox id=check1 />Do you want to accept?
<input type=submit name=submit value=Submit ></input>
<input type=reset name=reset value=Reset></input>
</form>
</body>
</html>

ANKIT SINGH

128

Text
The text object refers to the HTML text box.

blur() remove focus from a text field.


focus() sets focus on a text field.
select() select a text field.
onfocus: fired when an element receives focus.
onchange: fired after the occurrence of the blur event when the value of
the text object.

onselect: fired when the user selects a part of the text within the text
field. Document.form1.text1

Textarea
The textarea object refers to the HTML textarea the textarea object has similar
method and event attribute
Radio
The radio object refers to an HTML radio button.
Document.form1.radio1
<html>
<head>
<style>
Body
{
Background-color:pink;
}
</style>
<SCRIPT>
function validate()

ANKIT SINGH

129

{
if((document.f1.M.checked==false)&&(document.f1.F.checked==false))
{
alert(please select the gender);
return false
}
else
return true
}
</SCRIPT>
</head>
<body>
<form name=f1 method=get action=thanks.html
onsubmit=return validate();>
Gender:
<input type=radio name=gender id=M/>Male
<input type=radio name=gender id=F/>Female
<input type=submit name=submit value=Submit
align=Center></input>
<input type=reset name=reset value=Reset></input>
</form>
</body>
</html>

Select
The select object refers to the HTML drop down list.

blur()
focus ()

ANKIT SINGH

130

onchange
onfocus
onblur

the select object can be referred inside a form


document.form1.select1
<html>
<head>
<SCRIPT>
function validate()
{
if(document.f1.opt.value==0)
{
alert(please select the contry);
return false
}
else
return true
}
</SCRIPT>
</head>
<body>
<form name=f1 method=get action=thanks.html
onSubmit=return validate();>
Country:
<select id=opt style=width:200>
<option value=0> Select any Country</option>
<option value=1>India</option>

ANKIT SINGH

131

<option value=2>USA</option>
<option value=3>UKs</option>
</select>
<input type=submit name=submit value=Submit>
<input type=reset name=reset value=Reset>
</form>
</body>
</html>

ANKIT SINGH

132

Graphics
Canvas
Canvas provides an easy and powerful way to create graphic on a web page. A canvas
has on content of its own. A canvas is simply an area on a web page that act as a
container for embedding graphic objects.

Defining the Canvas


A canvas is defined by using the <canvas> tag. This tag is defined in the body section of
the HTML Document.

<canvas id=myCanvas width=300 height=300 style=border:1px solid


black></canvas>

Accessing the Canvas

ANKIT SINGH

133

A canvas element only create a blank drawing surface however to actually draw graphic
objects on the canvas.
<SCRIPT>
var c=document.getElementById(myCanvas);
var ctx=c.getContext(2d);
</SCRIPT>

Working with Shapes


You can draw shapes such as rectangle and square on it rectangle and square are the
easiest shapes to draw on the canvas element by using the javascript function.

rect ()
fillRect ()
strokeRect ()
clearRect ()

rect()
the rect() method is used to create a rectangle on the canvas the default color of the
canvas to draw the outline of the rectangle.
rect(X,Y,width,height);

X: the X-coordinate of the upper-left corner of the rectangle


Y: the Y-coordinate of the upper-left corner of the rectangle
Width: width of the rectangle in pixels
Height: height of the rectangle in pixels

<html>
<body>
<canvas id="myCanvas" width="300"
height="300" style="border:1px solid black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(30,30,120,120);
ctx.stroke();

ANKIT SINGH

134

</SCRIPT>
</body>
</html>

fillRet()
the fillRect () method is used to create a rectangle filled with the specified color. The
default color is black.
fillRect(X,Y,width,height);
<html>
<body>
<canvas id="myCanvas" width="300"

height="300" style="border:1px solid black"></canvas>


<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(30,30,120,120);
</SCRIPT>
</body>
</html>

ANKIT SINGH

135

strokeRect()
create a rectangle using by the rect() method you also need to use the stroke() method
to define its outline on the canvas.
strokeRect(X,Y,width,height);
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.strokeRect(30,30,120,120);
</SCRIPT>
</body>
</html>

ANKIT SINGH

136

clearRect()
the clearRect() method is used to clear a portion of the rectangle it clears the
specified pixels within the given rectangle.
clearRect(X,Y,width,height);
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(30,30,120,120);
ctx.clearRect(50,50,40,40);
</SCRIPT>
</body>
</html>

ANKIT SINGH

137

Working with Colors


The graphic objects on a canvas by using the default stroke and fill color. You can use
colors other than the default color for creating th graphic object.

fillStyle
strikeStyle
shadowcolor

fillStyle
the fillStyle property is used to define a color that will be used to fill any closed shape
drawn on the canvas.
fillStyle=color;
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(30,30,120,120);

ANKIT SINGH

138

</SCRIPT>
</body>
</html>

strokeStyle
the strokeStyle property is used to set the outline color of a shape drawn on the canvas
strokeStyle=color;
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.strokeStyle="blue";
ctx.strokeRect(30,30,120,120);
</SCRIPT>
</body>
</html>

ANKIT SINGH

139

shadowColor
you have drawn a shape on the canvas you may want to make it more it more stylish by
creating a shadow on it to graphic object on the canvas
shadowColor=color;
<html>
<body>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.shadowBlur=40;
ctx.fillStyle="pink";
ctx.shadowColor="black";
ctx.fillRect(30,30,120,120);
ctx.shadowColor="blue";
ctx.fillRect(170,30,120,120);
</SCRIPT>
</body>

ANKIT SINGH

140

</html>

Working with Style


Creating simple shapes on the canvas you can also apply style such as gradients.

addColorStop()
createLinearGradient()
createRadialGradient()
createPattern()

addColorStop()
to create gradients you need to first specify the colors and their position in a gradient
object.
addColorStop(position,color);

position specifies a value between 0.0 to 1.0 to represent the position from
where to start and end the gradient color.
color the color that needs to be applied on the respective position.

createLinearGradient()
the createLinearGradient() method is used to return a gradient object that represent a
linear gradient for painting the color along a line
createLinearGradient(X0,Y0,X1,Y1);

ANKIT SINGH

141

X0
Y0
X1
Y1

the x-coordinate of the start point of the gradient


the y-coordinate of the start point of the gradient
the x-coordinate of the end point of the gradient
the Y-coordinate of the end point of the gradient

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grad=ctx.createLinearGradient(0,0,170,0);
grad.addColorStop(0,"blue");
grad.addColorStop("0.5","yellow");
grad.addColorStop(1,"red");
ctx.fillStyle=grad;
ctx.fillRect(20,20,180,180);
</SCRIPT>
</body>
</html>

ANKIT SINGH

142

createRadialGradient()
the createRadialGradient() method is used to return a gradient object that represents a
radial or a circular gradient to be applied on a graphic object.
createRadialGradient(X0,Y0,R0,X1,Y1,R1);

X0
Y0
R0
X1
Y1
R1

the x-coordinate of the start point of the gradient


the y-coordinate of the start point of the gradient (x0,y0) the center
the radius of the starting circle
the x-coordinate of the end point of the gradient.
the y-coordinate of the end point of the gradient (x1,y1) the center
the radiu of the ending circle creating the radial gradient object.

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
black"></canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grad=ctx.createRadialGradient(75,50,5,90,60,100);
grad.addColorStop(0,"blue");
grad.addColorStop("0.5","yellow");
grad.addColorStop(1,"red");
ctx.fillStyle=grad;
ctx.fillRect(20,20,180,180);
</SCRIPT>
</body>
</html>

ANKIT SINGH

143

createPattern()
is used to create a pattern by displaying an image on a canvas in the specified direction
createPattern(img,repeat|repeat-x|repeart-y|norepeat);

img the image or video to be used to create a pattern


repeat the pattern should be repeated horizontally and vertically
repeat-x the pattern should be repeated horizontally
repeat-y the pattern should be repeated vertically
no-repeat the pattern should be display only once.

<html>
<body>
<img src="a.jpg" id="pattern">
<button onclick="draw('repeat')">Repeat</button>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
function draw(direction)
{
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ANKIT SINGH

144

var img=document.getElementById("pattern");
var pat=ctx.createPattern(img,direction);
ctx.rect(0,0,300,300);
ctx.fillStyle=pat;
ctx.fill();
}
</SCRIPT>
</body>
</html>

Working with Path


A path ia a series of points joined together to create lines or shapes. In canvas you can
use line or paths to draw shapes other than rectangles or squares.
Using moveTo() and lineTo() method.

ANKIT SINGH

145

ANKIT SINGH

146

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(40,40);
ctx.lineTo(240,40);
ctx.stroke();
</SCRIPT>
</body>
</html>

ANKIT SINGH

147

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(80,90,50,0,Math.PI*2,false);
ctx.closePath();
ctx.fillStyle="yellow";
ctx.fill();
</SCRIPT>
</body>
</html>

ANKIT SINGH

148

Draw more complex curvatures


bezierCurveTo()
bezierCurceTo(cp1x, cp1y, cp2x,cp2y,x,y);

cp1x
cp1y
cp2x
cp2y
x the
y the

the x-coordinate of
the y-coordinate of
the x-coordinate of
the y-coordinate of
x-coordinate of the
y-coordinate of the

the first control point


the first control point
the second Bezier control point
the second Bezier control point
ending point
ending point

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(200,20);

ANKIT SINGH

149

ctx.bezierCurveTo(80,20,80,100,150,100);
ctx.stroke();
</SCRIPT>
</body>
</html>

Working with Text


To drawing shapes or lines on the canvas you can also draw text on it

fillText()
the fillText() method is used to draw a text filled with solid color on a canvas.
fillText(text,x,y,width);

ANKIT SINGH

150

text the text to be written on the canvas


X the x-coordinate of the starting point of the text.
Y the y-coordinate of the starting point of the text.
Width the width of the text.

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="15px Georgia";
ctx.fillText("Fill Text",10,60,120);
ctx.font="15x Verdana";
var gradient=ctx.createLinearGradient(0,0,170,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1","red");
ctx.fillStyle=gradient;
ctx.fillText("Fill Text with Gradient",10,90,120);
</SCRIPT>
</body>
</html>

ANKIT SINGH

151

strokeText()
the strokeText() method is used to draw a text at the specified position on the canvas by
using the current font style and color.
strokeText(text,x,y,width);

Text the text to be written on the canvas


X the x-coordinate of the starting point of the text
Y the y-coordinate of the starting point of text
Width the width of the text.

<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="15px Georgia";
ctx.strokeText("Fill Text",10,60,120);
ctx.font="15x Verdana";
var gradient=ctx.createLinearGradient(0,0,170,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");

ANKIT SINGH

152

gradient.addColorStop("1","red");
ctx.strokeStyle=gradient;
ctx.strokeText("Fill Text with Gradient",10,90,120);
</SCRIPT>
</body>
</html>

Working with images


drawImage(img,x,y);
drawImage(img,x,y,width,height);
drawImagw(img,sx,sy,swidth,sheight,x,y,width,height);

img image that need to be drawn on the canvas


x the x-coordinate for the starting point of the image.
Y the y-coordinate for the starting point of the image
Width the width of the image it is optional argument.
Height the height of the image it is optional argument
Sx the x-coordinate to start the clipping of the image
Sy the y-coordinate to start the clipping of the image
Swidth the width of the clipping image
Sheight the height of the clipping image

ANKIT SINGH

153

<html>
<body onload=setImage()>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
function setImage()
{
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.src="a.jpg"
img.onload=function()
{
ctx.drawImage(img,10,10,150,150);
}
}
</SCRIPT>
</body>
</html>

ANKIT SINGH

154

Working with Graphs


A graph is a way of representing relationships among a collection of items.
If you want to create a bar graph on a web page than you need to download the
RGraph.common.core.js and RGraph.bar.js files.

Transforming Canvas Element


you can move HTML element from one position to another position easily while working
with a canvas you may want to shift the graphics object from one position to another
and increase or decrease their size.

translate()
scale()
rotate()

translate
the translate () method is used to reset the origin of the canvas to the specified position.
translate(x,y);

x the value to be added to the existing value of the x coordinate


y the value to be added to the existing value of the y coordinate

var c=document.getElementById(myCanvas);
var ctx=c.getContext(2d);
ctx.fillStyle=red;
ctx.fillRect(10,10,100,100);

<html>
<body >
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>

ANKIT SINGH

155

var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(10,10,100,100);
ctx.translate(50,25);
ctx.fillStyle="blue";
ctx.fillRect(10,10,100,100);
</SCRIPT>
</body>
</html>

Scale
The scale () method is used to increase or decrease the units in the canvas grid.
scale(scalewidth,scaleheight);

scalewidth the width (in percentage) a graphic object should be scaled to.
scaleheight the length(in percentage) a graphic object should be scale to.

<html>

ANKIT SINGH

156

<body >
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>

var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(10,10,100,100);
ctx.translate(50,25);
ctx.scale(2,2);
ctx.fillStyle="blue";
ctx.fillRect(10,10,100,100);
</SCRIPT>
</body>
</html>

Rotate

ANKIT SINGH

157

The rotate() method is used to rotate the graphic object to a degree in the clockwise
direction
rotate(angle);
<html>
<body >
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;">does not</canvas>
<SCRIPT>
var c =document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(10,10,100,100);
ctx.rotate(25);
ctx.fillStyle="blue";
ctx.fillRect(40,40,100,100);
</SCRIPT>
</body>
</html>

ANKIT SINGH

158

Animating Canvas Elements


An animation is a visual technique that provides the object is moving by displaying
graphic object in rapid sequence.
1. Create variables for the animation state.
2. Draw the animation.
3. Redraw the object.

<html>
<head>
</head>
<BODY>
<CANVAS Id="canvas" width="400"
height="300" style="border:2px solid black">
</CANVAS>

<SCRIPT type="text/javascript">
var canvas;
var ctx;
var x = 390;
var y = 290;
var dx = 2;
var dy = 2;
var WIDTH = 400;
var HEIGHT = 300;
function circle() {
ctx.beginPath();
ctx.fillStyle="red";
ctx.arc(x,y,10,0,Math.PI*2,true);
ctx.fill();
ctx.closePath();

ANKIT SINGH

159

}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById
("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
circle();
if (x> WIDTH || x< 12)
dx = -dx;
if (y> HEIGHT || y< 12)
dy = -dy;
x += dx;
y += dy;
}
init();
</SCRIPT>
</BODY>
</html>

ANKIT SINGH

160

Project time
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="400" height="400">
</canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90

ANKIT SINGH

161

setInterval(drawClock, 1000);

function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}

function drawFace(ctx, radius) {


var grad;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2*Math.PI);
ctx.fillStyle = 'pink';
ctx.fill();
grad = ctx.createRadialGradient(0,0,radius*0.90, 0,0,radius*1.05);
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');
ctx.strokeStyle = grad;
ctx.lineWidth = radius*0.1;
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius*0.1, 0, 2*Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
}

function drawNumbers(ctx, radius) {


var ang;

ANKIT SINGH

162

var num;
ctx.font = radius*0.15 + "px arial";
ctx.textBaseline="middle";
ctx.textAlign="center";
for(num = 1; num < 13; num++){
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius*0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius*0.85);
ctx.rotate(-ang);
}
}

function drawTime(ctx, radius){


var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//hour
hour=hour%12;
hour=(hour*Math.PI/6)+
(minute*Math.PI/(6*60))+
(second*Math.PI/(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);
//minute
minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));

ANKIT SINGH

163

drawHand(ctx, minute, radius*0.8, radius*0.07);


// second
second=(second*Math.PI/30);
drawHand(ctx, second, radius*0.9, radius*0.02);
}

function drawHand(ctx, pos, length, width) {


ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0,0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
</script>
</body>
</html>

ANKIT SINGH

164

ANKIT SINGH

165

Geolocation
Implementing Geolocation
The store offers clothes accessories and footwear in addition it sells the home furnishing
goods and electronic items such as refrigerator air conditioner laptops and mobile
devices.
Using the Geolocation API the Geolocation API-enabled website can locate users current
geographical location display points of interest around that location or guide the users
from their current location to a target destination.

Implementing the Geolocation API


The users location is not retrieved just through code or browser. Instead the Geolocation
API uses certain features such as Global Positioning System (GPS) Internet Protocol (IP)
address of a device. Nearest mobile phone towers and input from user in the users
device to retrieve the users location.

getCurrentPosition()
watchPosition()

getCurrentPosition()
the getCurrentPosition() method is used to retrieve the current geographical location of a
user the location is retrieved as a set of coordinate
getCurrentPosition(callbackFunction,ErrorHandler,Options);

callbackFunction this is a function defined by the developer to retrieve the


current location
ErrorHandler this is the name of a function that is called when an error occurs
while retrieving the location of a user. This is a optional parameter.
Options this optional parameter a set of options such as timeout for retrieving
the information about the user

ANKIT SINGH

166

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

ANKIT SINGH

167

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>

watchPosition()
the watchPosition() method return the current location of a user and continuously update
the location while user is moving. The watchPosition ()
method takes the same parameter as the getCurrentPosition() method and returns
the same object.
<!DOCTYPE HTML>
<head>
<html>
<script type="text/javascript">
var watchID;
var geoLoc;
function showLocation(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}

function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");

ANKIT SINGH

168

else if( err.code == 2) {


alert("Error: Position is unavailable!");
}
}

function getLocationUpdate(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler,
options);
}

else{
alert("Sorry, browser does not support geolocation!");
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="getLocationUpdate();" value="Watch
Update"/>
</form>

</body>
</html>

ANKIT SINGH

169

Handling Errors
User may not provide the permission to access his location. This may raise an error in
your website. The error may also occur when a user checks the current location on a
mobile device and the device goes out of coverage area or the network connection is
time out error.

Permission_denied that the user has declined the request to share the location
Position_unavailable that the users current location cannot be retrieved.
Timeout that the time given to retrieve the users location exceeded the
maximum limit.
Unknoen_error that an unknown or undefined error has occurred.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}

function showError(error) {

ANKIT SINGH

170

switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>

Offline Support

Ensures that the website is available even when the user is not connected to the
network.
Reduces network load on the server. You can make your website work offline by
using the
Implement client-side storage
Implement application cache

Client-side storage
The client-side storage refers to the process of storing data locally within the users
browser the date stored by using client-side storage is retrieved only when it is
requested the date stored in the key value pairs.

ANKIT SINGH

171

localStorage
sessionStorage

localStorage
the localStorage object allow you to store data without any expiration date. The implies
that the date stored by using the localStorage .
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML =
localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does
not support Web Storage...";
}
</script>
</body>
</html>

sessionStorage
the sessionStorage object is used to store the data for only one session.
<!DOCTYPE html>
<html>
<head>

ANKIT SINGH

172

<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the
button " + sessionStorage.clickcount + " time(s) in this session.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser
does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!
</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is
reset.</p>
</body>
</html>

Implementing Application ache


You must have faced a situation when the network connection is lost and you click the
back button in the browser to view the previous page.

Offline browsing that a website can be viewed even if the user is not connected
to the internet.

ANKIT SINGH

173

Speed that if the user request the web page which is already there in the cache
it is retrieved from the cache and not from the server.
Reduced server load that the web page if cached will always be made available
from the cache unless the browser detects that the cache manifest has been
updated on the server or user has cleared the browser cache.
Cache the files that need to be cached after they are downloaded for the first
time.
Network the files that should never be cached.
Fallback the task to be performed a user tries to fetch the uncached files.

<html manifest=HotelFacilities.appcache>

ANKIT SINGH

174

jQuery
The website should be designed in such a way that it displays the product categories
and items in the sliding and collapsible menu and submenu format the web designer has
been asked to complete the task quickly and keep the code simple for this situation the
designer can use the prewritten JavaScript library known as jQuery.
Manipulating HTML Element by Using jQuery
You can make use of jQuery in a web page to manipulate HTML element by using jQuery.
The using jquery before you need to download jquery-1.8.3.js file. It can be referred
to the web page by using the <SCRIPT>tag in the head section.
<SCRIPT type=text/javascript src=path/jquery-1.8.3.js>
</SCRIPT>
The SCRIPT tag instructs the browser that the HTML document uses a script.
The type attribute specifies the type of scripting used.
The src is used to path of jquery file store in your hard drive.
document.ready()
this function contains the jquery code to be executed on HTML element after the web
page has been fully loaded in the browser.

<SCRIPT type="text/javascript"
src="F:\HTML\class\jQueryS\jquery.1.8.3.js">
$(document).ready(function(){//jQuery code})
</SCRIPT>

The dollar sing ($) represent start of the jQuery code block and jQuery code is the code
to be implemented for the document.ready() function
$ (selector).action();
The selector is the element to be manipulated and action represents action to be taken
on the selector element.
<html>
<head>

ANKIT SINGH

175

<SCRIPT type="text/javascript"
src="F:\HTML\class\jQueryS\jquery.1.8.3.js">
</SCRIPT><SCRIPT>
$(document).ready(function(){//jQuery code})
</SCRIPT>
</head>
<body>
...
</body>

jQuery HTML
the JQuery provides predefined functions to perform modifications on the content of
HTML elements.

ANKIT SINGH

176

ANKIT SINGH

177

<html>
<head>
<SCRIPT type="text/javascript"
src="F:\HTML\class\jQueryS\jquery.1.8.3.js">
</SCRIPT><SCRIPT>
$(document).ready(function(){$("button").click (function() { $
("#para").prepend("<b>jQuery<b>"); $("#para").append('<h3> This is the
newly inserted heading.</h3>');
$("#newhead").remove();});});
</SCRIPT>
</head>
<body>
<div align="center"></div>
<h3>Complete the sentence:</h3>

ANKIT SINGH

178

<p id="para">is a javascript library that enables the content to be appended


after the inner content in the selected element using the</p><br><h2
id="newhead">this heading would be removed.</h2>
<button id="b">click me</button>
</body>

After click me button clicked

ANKIT SINGH

179

Handling jQuery Events


In jQuery events are handled by using functions or predefined event method.

ANKIT SINGH

180

ANKIT SINGH

181

ANKIT SINGH

182

Visual Effects
Hide
Show
Toggle
Slide
Fade
Animate

Hide Effect
The hide() function is used to make an element disappear when an event such as click or
double-click occurs.
$(selector).hide(speed)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</body>
</html>

ANKIT SINGH

183

Show Effect
The show() function is used to make a hidden element visible when an event occurs.
$(selector).show(speed)
<!DOCTYPE html>
<html>
<head>
<script src="F:\HTML\class\jQueryS

\jquery.1.8.3.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});

ANKIT SINGH

184

});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>


<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>

Toggle Effect
The toggle () function is used to switch between the show and hide effects of an
element.
$(selector).toggle(speed)
<!DOCTYPE html>
<html>
<head>
<script src="F:\HTML\class\jQueryS\jquery.1.8.3.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>

<button>Toggle between hiding and showing the paragraphs</button>

ANKIT SINGH

185

<p>This is a paragraph with little content.</p>


<p>This is another small paragraph.</p>

</body>
</html>

Slide Effect
The slide effect used to produce a sliding effect on the selected element. The slide
functions slideDown() slideUp() and slideToggle()
slideDown()
$(selector).slideDown(speed)
slideUp()
$(selector).slideUp(speed)
slideToggle()
$(selector).slideToggle(speed)

<!DOCTYPE html>
<html>
<head>
<script src="F:\HTML\class\jQueryS\jquery.1.8.3.js"></script>
<script>
$(document).ready(function(){
$("#flip").mouseenter(function(){
$("#panel").slideToggle("slow");
});
});
</script>

ANKIT SINGH

186

<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide the panel down or up</div>


<div id="panel">Hello world!</div>

</body>
</html>

Fade Effect
Fade effect is used to gradually reduce the opacity of the selected elements.

ANKIT SINGH

187

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
</head>

ANKIT SINGH

188

<body>
<p>Demonstrate fadeOut() with different parameters.</p>
<button>Click to fade out boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;">
</div><br>
<div id="div2" style="width:80px;height:80px;background-color:green;">
</div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;">
</div>
</body>
</html>

Animate Effect
The animate effect is used to create custom animation.
Animate({params},speed,callback);

Params the CSS properties to be animated.


Speed duration of the animated effect
Callback the function that will be executed after completing the animation.
<!DOCTYPE html>
<html>
<head>
<script src="F:\HTML\class\jQueryS\jquery.1.8.3.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',

ANKIT SINGH

189

height: '150px',
width: '150px'
});
});
});
</script>
</head>
<body>
<div
style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>
</body>
</html>

Image Rollover
The images can be replaced by other images at runtime by creating the image rollover
effect.
<!DOCTYPE html>
<html>
<body>

<img onmouseover="bigImg(this)" onmouseout="normalImg(this)"


border="0" src="smiley.gif" alt="Smiley" width="32" height="32">

<p>The function bigImg() is triggered when the user moves the mouse pointer
over the image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved
out of the image.</p>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";

ANKIT SINGH

190

}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
</body>
</html>

Image Gallery
An image gallery is a collection of thumbnail pictures or image links. All of these can be
clicked individually to provide a large view of the corresponding product on another web
page.

Using colorbox plugin


Using galleria plugin

Colorbox plugin enables displaying a collection of images one by one by using the
previous and next button and variety of transition effects.
If you want to use this effect than you need to download a colorbox.zip file.

Colorbox this folder comprises the jquery.colorbox.js file. Is used to implement the
lightbox slideshow and the transition effects.

Colorbox.css style sheet contains the formatting instructions to stylize position and
decorate the image gallery.
<html>
<head>
<link media="screen" rel="stylesheet"
href="F:\HTML\class\demo\colorbox.css"/>
<script src="F:\HTML\class\jQueryS\jquery.1.8.3.js"></script>
<script src="F:\HTML\class\jQueryS\jquery.colorbox.js"></script>

ANKIT SINGH

191

<script type="text/javascript">
$(document).ready(function(){
$("a").colorbox({transition:"fade",height:"250",width:"220"});
});
</script>
</head>
<body>
<h1 product demonstration</h1>
<a href="a.jpg">shanu</a>
</body>
</html>

Galleria plugin
This plugin is used to display image gallery and create thumbnails of the images to be
displayed in the gallery automatically. When the mouse pointer is moved on a thumbnail
image is large version of image.
If you want to used galleria plugin you need to download the galleria.zip file

ANKIT SINGH

192

You might also like