0% found this document useful (0 votes)
24 views93 pages

Unit1 WP

The document outlines the course structure for AD513PE: Web Programming, detailing objectives, outcomes, and units covering client-side programming, Java, JDBC, applets, and web services. It emphasizes the importance of HTML, Java, and various protocols such as HTTP and FTP in web development. Additionally, it provides a historical context for HTML and the World Wide Web, explaining their evolution and significance in internet communication.

Uploaded by

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

Unit1 WP

The document outlines the course structure for AD513PE: Web Programming, detailing objectives, outcomes, and units covering client-side programming, Java, JDBC, applets, and web services. It emphasizes the importance of HTML, Java, and various protocols such as HTTP and FTP in web development. Additionally, it provides a historical context for HTML and the World Wide Web, explaining their evolution and significance in internet communication.

Uploaded by

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

AD513PE: WEB PROGRAMMING (Professional Elective – I)

B.Tech. III Year I Sem. L T P C


3 0 0 3
Course Objectives:
 Understand the technologies used in Web Programming.
 Know the importance of object-oriented aspects of Scripting.
 Understand creating database connectivity using JDBC.
 Learn the concepts of web-based application using sockets.

Course Outcomes:
 Design web pages.
 Use technologies of Web Programming.
 Apply object-oriented aspects to Scripting.
 Create databases with connectivity using JDBC.
 Build web-based application using sockets.

UNIT - I
Client side Programming
HTML- Basic Tags- List, Tables, Images, Forms, Frames, CSS
JAVA Script -
Web page Designing using HTML, Scripting basics- Client side and server side
scripting. Java Script Object, names, literals, operators and expressions- statements
and features- events - windows - documents - frames - data types - built-in
functions- Browser object model - Verifying forms.-HTML5- CSS3- HTML 5
canvas - Web site creation using tools.

UNIT – II

JAVA
Introduction to object-oriented programming-Features of Java – Data types,
variables and arrays – Operators – Control statements – Classes and Methods –
Inheritance. Packages and Interfaces – Exception Handling – Multithreaded
Programming – Input/Output – Files – Utility Classes – String Handling.

UNIT – III

JDBC
JDBC Overview – JDBC implementation – Connection class – Statements -
Catching Database Results, handling database Queries. Networking– InetAddress
class – URL class- TCP sockets – UDP sockets, Java Beans –RMI.

UNIT – IV

1
APPLETS
Java applets- Life cycle of an applet – Adding images to an applet – Adding
sound to an applet. Passing parameters to an applet. Event Handling. Introducing
AWT: Working with Windows Graphics and Text. Using AWT Controls, Layout
Managers and Menus. Servlet – life cycle of a servlet. The Servlet API,
Handling HTTP Request and Response, using Cookies, Session Tracking.
Introduction to JSP.

UNIT – V
XML AND WEB SERVICES
Xml – Introduction-Form Navigation-XML Documents- XSL – XSLT- Web
services-UDDI-WSDL-Java web services – Web resources.

TEXT BOOKS:
1. Harvey Deitel, Abbey Deitel, Internet and World Wide Web: How To Program 5th
Edition.
2. Herbert Schildt, Java - The Complete Reference, 7th Edition. Tata McGraw- Hill
Edition.
3. Michael Morrison XML Unleashed Tech media SAMS.

REFERENCE BOOKS:
1. John Pollock, Javascript - A Beginners Guide, 3rd Edition –- Tata McGraw-Hill
Edition.
2. Keyur Shah, Gateway to Java Programmer Sun Certification, Tata McGraw Hill,
2002.

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

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

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

World Wide Web:

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

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


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

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

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


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

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


interconnecting computer networks with special gateways or routers. The Internet is
also often referred to as the Net. The Internet is a massive network of networks, a
networking infrastructure. It connects millions of computers together globally, forming a
network in which any computer can communicate with any other computer as long as

3
they are both connected to the Internet. Information that travels over the Internet does
so via a variety of languages known as protocols.

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

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


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

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

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


frequently and automatically, based on certain criteria

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

What is Hypertext?

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

Retrieving Data from the Web :

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

Structure of URLs:

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

The URL consists of three parts:

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

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

Protocol domain name path

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


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

Ex: HTTP -:Hyper Text Transfer Protocol


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

HTTP:

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

5
FTP:

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

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

TCP/IP :

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


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

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

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

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

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


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

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

SMTP

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

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

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

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

What is HTML?

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

Features of HTML:

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

What is HTML Document?

8
 HTML documents describe WebPages. HTML documents contain HTML tags
and plain text. HTML documents are also called “WebPages”.

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


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

Editing HTML:

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


 Notepad is available in
Startsearchnotepad
 All HTML files have either the .html or .htm as file extensions

HTML Tags & Attributes:

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

< tag name >.

About HTML Tags

1. Tags are delimited by angled brackets.


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

What are attributes?


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

HTML Elements

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

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

9
Explain the STRUCTURE of HTML Document ?

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

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


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

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

Explain body tag and its attributes?


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

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

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

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

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

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

HTML Line Breaks:


Use the < br > tag if you want a line break (a new line) without starting a new
paragraph. The <br> tag is used to force line breaks within text. Normally, line breaks
are treated as a space by browsers. This <br> has no ending tag(ie,</br>).
Eg: <html> <body>
<p>This is<br>a Para<br><br>graph with line breaks</p>
</body></html>
HTML Headings:
Page headings are created with the <h1>, <h2>,<h3>,<h4>,<h5>,<h6> tags.
Syntax: <hi> sairam </hi> i.e i=1,2,3,4,5,6
Attribute: align=left(default) | right | center
<h1> defines the Largest size heading.
<h6> defines the smallest size heading.

Eg: HTML program to display different sizes of heading.


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

HTML <hr> Tag (Horizontal Ruler)


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

Size=n Specifies the rule height

Width= n% Specifies the rule width

Align=left |right |center Specifies the alignment.

Noshade Specifies the rule has no shading

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

Eg:

Illustrate the horizontal rulers in your page

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

HTML Text Formatting Tags:


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

<b> Defines bold text

<u> Defines underline

13
<i> Defines italic text

<big> Defines big text

<small> Defines small text

<em> Defines emphasized text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

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

<strike> strikes a line through the text

<marquee> Displays scrolling text in a marquee style


Escape sequences used in text formatting are

Name Escape Sequence Result


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

Quotations &quot; “

Write a HTML program illustrating text formatting tags.

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

<body>

<h3>Text Formatting Tags</h3>


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

<pre>

“SAI SPURTHI INSTITUTE OF TECHNOLOGY “


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

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

ATTRIBUTES:
Attribute Description
size=n Size of your text, n takes values 1 to 7
color=rgb colorcode (or) colorname Indicates color of the text
face="name of font" Indicates type of font
Eg:
Illustrate font variations in your HTML code.
<html>
<head>
<title> Second Program </title>
</head>
<body bgcolor="#ffcc88">
<font face=”Arial” size=”1” color=”blue”>SSIT</font><br>
<font face=”Times New Roman” size=”2” color=”green”> JKCCOLLEGE </font>
<br>
<font face=”Verdana” size=”3” color=”violet”> SSIT </font><br>
<font face=”Symbol” size=”4” color=”red”> SSIT </font> <br>
<font face=”Calibri” size=”5” color=”yellow”> SSIT </font> <br>
<font face=”Algerian” size=”+1” color=”pink”> SSIT </font><br>
<font face=”impact” size=”-1” color=”cyan”> SSIT </font> <br>
15
</body>
</html>

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

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

Embedding Images (or) <img> Tag :


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

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


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

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

src=URL Specifies the location of an image

Border=n Specifies the border for image

Width=n Specifies the width of the image

Height=n Specifies the height of the image

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

Two types of image files are commonly used:

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

Eg1:

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

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

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


The HTML anchor element is used to create a link to a resource (another web
page, a file, etc.) or to a specific place within a web page.
The anchor tag is written like this <a href=URL>--------------</a>
Anchor tag attributes:
Attribute description
HREF=URL URL you are linking to
NAME=”text” name a section of the page
TARGET = "_blank" | "_parent" | "_self" which window the document should be
| "_top" | window name displayed.
The HREF Attribute:
The href attribute is used to specify the address of documents or services at
other internet sites, address of document within the sane website or address of a
specific part of either the current page or another page.
External Linking: External links are useful to navigate another webpage or website from
the current webpage. Here the URL address is the webpage address.

<a href="abc.html">google</a>

Absolute vs. Relative URLs:

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


an absolute URL. Absolute URLs are those that include a complete (absolute)
description of the link destination. Absolute URLs include the protocol (http) and the
complete domain name and file path needed to reach the destination anchor.
The second is an example of a relative URL. Relative URLs link to a web page by
describing the position of the page relative to the position of the current page. When
writing internal links that point to other pages of the same website we have the option of
writing relative URLs rather than absolute URLs.

17
For example, if we are at this address: http://example.com/products/red-product/, and
we want to link to the blue product page, we can use either of the following anchor
elements:

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


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

The NAME Attribute (used for Internal linking):


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

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

The TARGET Attribute:


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

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

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


clicked (this is default)

Target=_parent Opens the linked document in the parent frame

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

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


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

18
The Anchor Tag and the Name Attribute

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

Below is the syntax of a named anchor:

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

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

The line below defines a named anchor:


Ex.
<a name="chap1">Useful Tips Section</a>

3. Prepare a sample code to illustrate links between different


sections of a page. (Internal linking)

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

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


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

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


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

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


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

Explain different types of LISTS in HTML?:


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

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

<ol> Defines an ordered list

<li> Defines a list item

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

List Items <li>


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

The end tag </li> may be omitted.

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

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

Tags:
Tag Description

<ul> Defines an unordered list

<li> Defines a list item

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

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

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

<dl> Defines a definition list

<dt> Defines an item in a definition list

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

21
Eg:
<html><body>
<h4>A Definition List:</h4>
<dl>
<dt>HTML</dt>
<dd>Hyper Text Markup Language</dd>
<dt>WWW</dt>
<dd>World Wide Web</dd>
</dl>
</body>
</html>

NESTED LISTS:
Nested lists may be used to display sub elements of an item. Any of the three
types of lists may be nested in another.
Eg:<html><body>
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ol>
<li>Black tea</li>
<li>Green tea </li>
</ol>
</ul>
</body>
</html>

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

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

<h3> PROGRAMMES OFFERED IN SSIT</h3>


<ul type = "circle" >
<li> DIPLOMA</li>
<li>BTECH</li>
<li> MBA</li>
22
</ul>
<br>
<h2 align="center"> Ordered Lists </h2>
<br>
<h3> COMPUTER SCIENCE PROGRAMMES</h3>
<ol type="i">
<li>CSE </li>
<li> CSE(AIML)</li>
<li>AIDS </li>
</ol>
<br>
<h2 align="center"> Definition Lists</h2>
<br>
<dl>
<dt> Computer </dt>
<dd> It is an electronic device that takes input, process it and
generates output</dd>
<dt>HTML</dt>
<dd>Hyper Text Markup Language to display content in the web
pages</dd>
</dl>
</body>
</html>

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

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

Note: <tr> Table Row, <td> Table data(or)cell data, <th> Table heading.
Adding captions to table:
A caption is explanatory or descriptive text that usually appears above the table. A
caption serves two purposes:
 To summarize table contents
 To provide at-a-glance information about table contents

<caption>: used within a table to identify the text of the table caption

23
<caption> tag Attributes: align=top|bottom places the caption at the top or bottom of
the table.

<TABLE> tag ATTRIBUTES:


Attribute Description
Border=n size of border around the table
Cellpadding=n space between the edge of a cell and the contents
Cellspacing=n space between cells
Width=n px width of the table as a whole
Height=n px height of the table as a whole
Bgcolor=RGB(or)colorname color of the background
Background=URL picture to use as background
Bordercolor=RGB(or)colorname color of border around the table
Align=left|right alignment of table to surrounding text
Hspace=n horizontal space between table and surrounding text
Vspace=n vertical space between table and surrounding text
Rules=none|all|cols|rows|groups if there should be internal borders

<td> Attributes:
Attribute Description
align=left|center|middle|right horizontal alignment of cell contents
valign=top|middle|center|bottom| vertical alignment of cell contents
baseline
width=n width of cell
height=n height of cell
colspan=n number of columns to cover
rowspan=n number of rows to cover
bgcolor=RGB(or)colorname color of the background
background=URL of image color of border around the table
bordercolor=RGB(or)colorname color of border around the table

<tr> ATTRIBUTES:
Attribute Description
align=left|center|right horizontal alignment of cell contents
24
valign=top|middle|bottom|baseline vertical alignment of cell contents
bgcolor= RGB(or)colorname color of the background
background=URL of image color of border around the table
bordercolor= RGB(or)colorname color of border around the table

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

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

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

</table>

</body>
</html>

7. Create nested table to store your curriculum

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

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

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

25
<tr> <th> Name</th> <td> Sai</td> </tr>
<tr> <th> Qualification</th> <td> BTech(CSE) </td> </tr>
<tr> <th align="center" colspan="2"><b><i> Acadamic Details:</b></i></td></tr>
<tr>

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


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

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


8%</td> </tr>

<tr> <td>Intermediate</td> <td> Chaitanya Junior College</td><td> Board of


Intermediate</td> <td> 72%</td> </tr>

<tr> <td>B.Tech(CSE)</td> <td> SSIT </td><td>JNTUH</td> td> 74%</td> </tr>


</td>
</tr>
</table>

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


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

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

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

26
Multimedia Objects

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

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

Attributes:

Attribute Value Description


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

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

FRAMES
The HTML frame is a powerful feature that enables a web page to be broken into
different unique sections that are related but can be operated independently without
depending on each othe
r.
Advantages (Pros) of using Frames:
 One of the most beneficial feature of frames is it lets the user to have multiple pages
in the same browser.
 Using frames we can keep one part of the page static while changing the other
parts of the page.
 If we create a top frame we can use it as a header i.e, as that page is static it acts
like an include page.
 Frames can be used to reduce server load, as there is no need to reload all the
pages whenever a new page is visited.

Disadvantages (Cons) of using Frames:


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

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

28
bordercolor=RGB(or)colorname color of frame borders

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

Frame tag Attributes:


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

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


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

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

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

</html>

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

Web2.html
<html>
<body>
<h1>web2</h>

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

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

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

HTML Forms

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

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

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

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

30
The image below illustrates the concept:

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

The following are the attributes of the form tag:

 action=”Link to the form processor script”


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

 method =get|post ( either GET or POST)


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

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

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

31
Form elements are:

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

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

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


Output:
First name:

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

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

Attributes:

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

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

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

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

Male
Female

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

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

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

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


Eg: <input type=file name="fl">
attribute Use

34
Name=”text string” Name of the field

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

Example form:
<html>
<head>
<title>Mailing system</title> </head>
<body>
<h2 align="center">Subscriber Information</h2>
<form>
UserName: <input type="text" maxlength=30 size=15><br>
Enter Password:<input type="password"><br>

Address for correspondence:<br>


<textarea name="b" rows=5 cols=35></textarea><br>
Gender: &nbsp;&nbsp; Male <input type="radio" name="gen" value="m">
Female: <input type="radio" name="gen" value="f"><br>
File to upload: <input type="file" value="browse"><br>
Country:
<select name="cou" size=1>
<option>United States</option>
<option>Brazil</option>
<option>Russia</option>
<option selected>India</option>
</select><br>
if u have already account in:<br>
<input type=checkbox name=acc1 checked>yahoo<br>
<input type=checkbox name=acc2 >gmail<br>
<input type=checkbox name=acc2>rediff<br>

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


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

Explain Head section in detail ?


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

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

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

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

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


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

4. <meta> tag:

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

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

Define a description of your web page:


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

Define keywords for search engines:


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

Define the author of a page:


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

Refresh document every 30 seconds:


<meta http-equiv="refresh" content="30">

5. <script> tag :

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

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

CSS (Cascading Style Sheet)


37
DHTML:

Dynamic Hyper Text Markup Language is the name given to the


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

1.Cascading Style Sheets(CSS)


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

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

CSS Definition:

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

Advantages of CSS:

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

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


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

3. Pages load faster — CSS enable multiple pages to share formatting, and reduce
complexity and repetition in the structural content. It significantly reduces the file
transfer size, which results in a faster page loading.

4. Superior styles to HTML — CSS has much wider presentation capabilities than
HTML, so you can give far better look to your HTML pages in comparison to the
HTML presentational elements and attributes.

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

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

Disadvantages of CSS :

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

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

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

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

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

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

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

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

Types of selectors:

1. Type selector
39
2. Grouping

3. Class
4. ID
5. Universal
Type selectors

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

Example: h1 {color: red; }

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

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

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

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

h1 ,h2, h3 { property:value; }

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

Class selectors (or) Anonymous class:

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

The syntax for declaring a Class selector is as follows:

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

The tree diagram would be:

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

Combining class and type selectors

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

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

H1.big { color : yellow; }

Combining multiple classes

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

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

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

The syntax for declaring an ID selector is as follows:

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

Example:

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

Syntax: * {property:value}

EX: * {color: blue; }

The document tree would be:


<html>
<head>
<style type=text/css>
* { color: blue; }
</style>

42
</head>
<body>
<p><em>this will be affected</em></p>
<div><em>this will be affected</em><div>
<h1><em>this will be affected</em></h1>
</body>
</html>

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


of CSS?

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

1. Inline Style Sheet (style attribute)


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

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

Example:

<html>
<body>
<p style=”color:red;”> The text color is red. This is example for inline style sheet. </p>
<br>
<p style=”font-family : verdana; color :blue ;”>This text color is blue and font face is
verdana.</p>
</body>
</html>
4. Embedded (internal) Style sheet :
 We can put your CSS rules into an HTML document using the <style> element.
The HTML <style> element contains style information for a document.
 This tag is placed inside <head>...</head> tags.
 Rules defined using this syntax will be applied to all the elements available in the
document body section.

EX:

<html>
<head>
<style type="text/css">
p { background-color : yellow; }
h1 { color : maroon; }
</style>
</head>
43
<body>
<h1> WELCOME </h1>
<p> The background color is red. This is an example for internal style sheet. </p>
</body>
<html>
5. External Style sheet :

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

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

Here is the generic syntax of including external CSS file −

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

<link> Tag Attributes:


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

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

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

a.css

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

import

44
Another way to add css to html is by using @import.External CSS declarations
can also be imported into an HTML document. To do so, use the @Import command.
The syntax is:

<STYLE TYPE="text/css">

@import url(filename.css);

</STYLE>

Ex:

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

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

a.css

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

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

CSS supports a number of measurements including absolute units such as


inches, centimeters, points, and so on, as well as relative measures such as
percentages and em units. You need these values while specifying various
measurements in your Style rules e.g. border = "1px”.

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

Unit Description Example

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


to another value, typically an enclosing element.

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

em A relative measurement for the height of a font


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

ex This value defines a measurement relative to a


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

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

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

pc Defines a measurement in picas. A pica is


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

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


defined as 1/72nd of an inch.

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

CSS uses color values to specify a color. Typically, these are used to set a
color either for the foreground of an element (i.e., its text) or else for the
background of the element. They can also be used to affect the color of
borders and other decorative effects.

You can specify your color values in various formats. Following table lists all the possible
formats −

Format Syntax Example

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

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

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

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

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

CSS Rules Overriding:


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

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

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

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

Q6). Write about Properties and values in styles ?

1. Font Properties:

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

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


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

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


font-style : normal, italic, oblique

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


font-variant : normal small-caps

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


font appears.

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

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

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

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


properties.

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

<body>

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


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

2.Text Properties:

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

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


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

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


text-indent :measurement or %

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


text-align : left, right, center, justify

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

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

<body>

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


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

3.Background Properties:

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

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


background-color : #rrggbb, transparent

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


element.
background-image :url(tulips.jpg)

3) The background-repeat property is used to control the repetition of an image in


the background.
background-repeat : repeat-x, repeat-y,no-repeat
4) The background-position property is used to control the position of an image in
the background.
background-position : right top, right bottom, left top, left bottom

49
5) The background property is used as a shorthand to specify a number of
other background properties.
Ex:

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

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

6. Box Properties:

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


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

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

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

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

50
</body>
</html>

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


DIV tags?

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

Divisions:

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

Syntax:

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


Some tags
</div>

Spans:

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

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

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

Example:

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

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

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

</body>
</html>

Q8). Write about Layers ?

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

There are a few variables that need to be defined

1. position: absolute | relative:

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

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

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

Example:

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

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

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

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

</body>
</html>

Output:

53
Lab17: Write the html program including the style sheets.

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

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

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


<h1> Welcome </h1>

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


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

a.css

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

CASCADING STYLE SHEETS LEVEL 3(CSS3)

54
CSS3, also known as Cascading Style Sheets Level 3, is a more advanced version of
CSS and the successor of CSS2. CSS3 is used for the same thing as CSS, namely to
style web pages and make them more attractive and user-friendly. In addition, CSS3
incorporates more up-to-date features designed to increase efficiency and make it more
convenient for developers to use.
Key CSS3 Features
 Advanced Animations. Animations are one of the most eye-catching features you
can add to a web page. And while CSS allows web designers to use animations,
CSS3 ups the stakes with more complex animation properties such as
transforms, transitions, and special effects.
 Opacity. This property lets web designers make web page elements partially or
fully transparent. You can define the elements’ opacity levels to make them fully
opaque, transparent, or even see-through.
 Rounded Corners. Rounded corners make selected web page elements look
more professional and visually appealing. Before the introduction of the border-
radius property, web developers had to spend lots of time writing lengthy code to
round off an element's corners.
 Text and Box Shadows. CSS3 features built-in support for text and box shadows,
so web designers can easily apply shadowing to different text sections and even
easily define the shadow's color, angle, and blur level.
As a result, there’s no need to Photoshop the shadowed text and place it as an image
on the web page. The same holds for adding a shadow effect to elements, which you
can easily do by using the box-shadow property.

What’s the Difference Between CSS and CSS3?

CSS CSS3

Year Released 1996 2005

Media Queries Doesn’t support Supports responsive web design

No support for modern


browsers, but it still works
Browser Support Supported fully by all modern browsers
on older versions of
Explorer or Chrome

Compatibility
Between Not compatible with CSS3 Backward compatible with CSS
Versions

Supports single blocks


Block Support Supports multi-column text blocks
only

55
It only allows basic
animations and doesn't It offers advanced animations and many
Animation Use support transformation, customization options. It also supports text
text animation, transition, animation, transformation, and transition
or 3D animations

It doesn’t support media


Responsive queries, thus not ideal for Works with media queries, thus allowing
Design making responsive responsive web design
designs

Can group CSS codes into convenient


Module Use It doesn’t have modules
modules

It uses an old standard It offers different gradient colors and


Color Format
color format schemes like RGBA, HSLA, HSL, etc.

It provides average
It offers fast, excellent performance and
Performance performance and requires
doesn’t use as much memory
high memory usage

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

• Variables in java declared as datatype varname;

Ex: int sum;


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

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

public int function funname(int n)


{
…..function body…..
}

Benefits or advantages of JavaScript:

The following are the benefits of JavaScript:


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

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

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

• JavaScript cannot access databases

How to put a JavaScript into an HTML page:


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

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

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


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

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

1.Single line comments start with //.

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

2. JavaScript Multi-Line Comments

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

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

Where to Put the JavaScript:

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

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

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

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


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

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

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

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

Example:
sai.js

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

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

Data types in JavaScript

Programming languages usually have several different types of data.


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

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

61
• Strings : Collection of characters enclosed in quotation marks. Strings can have
spaces and digits. Eg: var a=”rama”;

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


variables hold values true and false.

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

JavaScript variables:

Variables in JavaScript behave the same as variables in most popular


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

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

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

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

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


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

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

Note: Use the var keyword only for declaration or initialization. once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell JavaScript
62
during variable declaration what type of value the variable will hold. The value type of a
variable can change during the execution of a program and JavaScript takes care of it
automatically.
JavaScript Variable Scope:
The scope of a variable is the region of your program in which it is defined. JavaScript
variable will have only two scopes.
• Global Variables: A global variable has global scope which means it is defined
everywhere in your JavaScript code.
• Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the same
name as a global variable, you effectively hide the global variable.
Example:
<html>
<head>
<script type="text/javascript">
var a = "20"; //Declare a global variable
function checkscope( )
{
var a = "10";//Declare a local variable
document.write(a);
}
</script>
</head>
<body>
<script language="javascript">
checkscope();
</script>
</body>
</html>

Rules for JavaScript Variable Names:


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

JavaScript Reserved Words or Keywords:


The following are reserved words in JavaScript. They cannot be used as JavaScript
variables, functions, methods, loop labels, or any object names.

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

Write a program to add two numbers in javascript.

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


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

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

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

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

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

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

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

Ex2: “jkc”+”123”=jkc123

3.Relational Operators:

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

There are following relational operators supported by javascript language is:


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

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

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


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

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

Type String Returned by typeof


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

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

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

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

String object methods:

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

5. indexOf():

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

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

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

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


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

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

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

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

• Math.PI : This returns 3.14


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

• Math.LN2 : Log of 2.

• Math.LN10 ; Log of 10.

• Math.SQRT_2 : The square root of 2.

• Math.SQRT1_2 : The square root of ½.

Math Object Methods:

• Math.abs():

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

Syntax: Math.abs(n)

2.Math.ceil():

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

3.Math.floor():

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

70
4.Math.round():

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

Syntax: Math.round(n)

5.Math.max():

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

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

6.Math.min():

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

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

7.Math.pow():

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


Syntax: Math.pow(x, y)

8.Math.random():

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

9.Math.sqrt():

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

Syntax: Math.sqrt(n)

• Math.log():

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

Syntax: Math.log(n)

11.Math.sin():

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

12.Math.cos():

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

• Math.tan():

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

Syntax: Math.tan(n)

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

Example:
<html><head></head>
<body>
<script type="text/javascript">
document.write(Math.max(5,10) + "<br />");
document.write(Math.min(0,150,30,20,38) + "<br />");
document.write(Math.sqrt(36) + "<br />");
document.write(Math.pow(3,4) + "<br />");
document.write(Math.ceil(1.5)+ "<br />");
document.write(Math.floor(1.5)+ "<br />");
document.write(Math.round(1.5)+ "<br />");
document.write(Math.abs(-12.345)+ "<br />");
document.write(Math.sin(30)+ "<br />");
document.write(Math.cos(30)+ "<br />");
document.write(Math.tan(30)+ "<br />");
document.write(Math.log(5)+ "<br />");
document.write(Math.random(-12.345)+ "<br />");
document.write(Math.random(11)+ "<br />");
document.write(Math.random()+ "<br />");
</script></body></html>
Output:
10
0
6
81
2
1
2
12.345
-0.9880316240928618

72
0.15425144988758405
-6.405331196646276
1.6094379124341003
0.7091526409954392
0.6440733917520216
0.09861611898007938
CONTROL STATEMENTS
The control statements are used to control the flow of execution of the program. This
execution order depends on the supplied data values and the conditional
logic. JavaScript contains the following types of control statements:
• Conditional Statements.
• Looping Statements.
• Unconditional Statements.

• Conditional Statements:

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


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

• if-else statement:

The general syntax of if-else statement is:


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

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


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

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

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

}
else
{
Statement-3
}

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


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

• else if ladder:

The general syntax of else if ladder is:


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

• switch:

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

• switch
• case
• break
• default

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

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

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

• Looping statements:

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


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

• While loop:

The general syntax of while loop is:

Syntax:

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

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


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

Example :

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

• Do-while loop:

The general syntax of while loop is:

do
{
body of the loop;

} while(test-condition);

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


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

Example:

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

• For loop:

The general syntax of for loop is:

for (initialization; test-condition; updation)


{
body of the loop;
}

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


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

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

• unconditional statements:

• Continue statement:

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


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

Syntax : continue;

Example:

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

• break statement :

This statement takes control out of the switch statement or


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

Syntax : break;

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

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

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

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


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

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

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


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

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

Syntax: var array_name=new Array ( )


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

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

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

Output:

Monday Tuesday 34 76.34 Wednesday Thursday

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

Searching element in an Array:

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

Example:

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

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

Output:

Element found at position 1

JavaScript Array Object


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

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

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

Syntax: arrayname.join (separator);

3.pop():

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

Syntax: arrayname.push (new item);

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

Syntax: arrayname.shift ();

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

Syntax: arrayname.unshift (new item);

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

Syntax: arrayname.sort ();

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

Syntax: arrayname.slice (start, end);

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

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

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

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

Function parameters or passing arguments to function:


Till now we have seen function without a parameters or arguments. But there is a
facility to pass different parameters while calling a function. These are variables, either
numbers or strings, with which the function is supposed to do something.
These passed parameters can be captured inside the function and any
manipulation can be done over those parameters. A function can take multiple
parameters separated by comma.
Syntax for passing arguments to a function is:
function_name (agrument1, argument2 …)
Example for passing arguments to a function:
<html>
<head>
<title>Calling a function</title>
<script language="javascript">
function Addition(x,y)
{
var a,b,c;
a=x;
b=y;
c=a+b;
document.write("The addition of a and b is"+c);

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

The return statement:

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

Syntax: return value;

Example for return statement:

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

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

Objects

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


are designed using classes.
 An object is a run-time instance of a class.

 In JavaScript everything is an Object: a String, a Number, an


Array, a Function....

 In addition, JavaScript allows you to define your own objects.


Class: A class usually contains both data items and some methods. Each class
provides services to other classes in the system.

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

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

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

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


placed between the object name and the property.

Creating JavaScript Objects

We can create object by using two ways.


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

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


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

Example2: <html> <head>


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

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

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

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


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

 close():Closes the current window


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

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

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

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

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

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

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

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

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

93

You might also like