Unit1 WP
Unit1 WP
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.
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.
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.
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).
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.
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.
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 Protocol
The Domain name (Webserver name)
The Path.
Eg: http://www.linccweb.org/eresources.asp
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 :
There are four total layers of TCP/IP protocol, listed below with a brief description.
Internet Layer - This layer uses IP (Internet Protocol) to describe how packets are to be
delivered.
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.
8
HTML documents describe WebPages. HTML documents contain HTML tags
and plain text. HTML documents are also called “WebPages”.
Editing HTML:
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.
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>
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>
Eg:
<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>
13
<i> Defines italic text
Quotations " “
<html>
<head>
<title> Second Program </title>
</head>
<body>
<pre>
<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.
---> .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>
<a href="abc.html">google</a>
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 name="chap1"></a>
To link to that named anchor you'd code your link like this:
<a href="#chap1">Table of Contents</a>
Target=_top Opens the linked document in the full body of the window
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.
The name attribute is used to create a named anchor. The name of the anchor
can be any text .
<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>
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> 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
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> 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
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>
<html>
<head>
<title> Types of Lists </title>
</head>
<body bgcolor="yellow">
<h1 align="center"> Lists </h1>
<br>
<h2 align="center"> Unordered Lists </h2>
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.
<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>
<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>
</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:
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.
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.
<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.
"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
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".
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.
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>
1. <title>….</title>
It is used to display the title of the document at the top of the browser window.
Eg: <title> welcome> </title>
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>
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.
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 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.
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.
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.
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;
}
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.
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>
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 “.”
<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>
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:
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.
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}
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>
There are three ways to apply a CSS style sheet to an HTML document:
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.
<head>
<link rel=stylesheet type = "text/css" href = "URL"> </link>
</head>
<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 ?
We have listed out all the CSS Measurement Units along with proper Examples
45
cm Defines a measurement in centimeters. div {margin-bottom: 2cm;}
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 −
46
RGB % rgb(rrr%,ggg%,bbb%) p{color:rgb(50%,50%,50%);}
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.
1. Font Properties:
The font property can set the style, weight, variant, size, line height and font
font-weight :normal,bold,bolder,lighter,100,200,300,400,500,600
47
font-size : small, medium, large, x-large, or size measurement
Ex:
<html>
<head>
</head>
<body>
2.Text Properties:
Text properties specify the characteristics of text blocks. The following table shows
some of the most common text properties.
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>
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.
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:
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>
50
</body>
</html>
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:
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>
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.
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>
a.css
p { background-color:#FF0000; }
h2 { color: #3645DB; letter-spacing : 1em;}
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.
CSS CSS3
Compatibility
Between Not compatible with CSS3 Backward compatible with CSS
Versions
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 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).
• JavaScript:
56
function funname(str)
{
…..Function body…..
}
• Java:
• JavaScript cannot write to files on the server without the help of a server side
script.
Syntax:
<script type=”text/javascript”>
…………….
…………….
</script>
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.
The following example uses single line comments to explain the code:
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>
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>
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>
• 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”;
• Null : It is an empty value. A null value means not yet decided. It does not mean
nil or zero.
JavaScript variables:
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>
<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>
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
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.
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.
• 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.
• 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:
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
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():
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.LN2 : Log of 2.
• Math.abs():
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
6.Math.min():
The min() method returns the number with the lowest value. If no arguments are
given, the results is -Infinity
7.Math.pow():
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)
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:
• if-else statement:
if (test-condition1)
{
if (test-condition2)
{
Statement-1
}
else
{
Statement-2
}
}
else
{
Statement-3
}
• else if ladder:
• 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:
• While loop:
Syntax:
while(test-condition)
{
body of the loop;
}
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:
do
{
body of the loop;
} while(test-condition);
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:
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:
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 :
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:
• The second approach is to create an array object using the keyword new
and a set of elements to store.
• The third approach is to create an empty array which has space for a
number of elements to be stored.
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:
Note: length is an array property used to count the no of data items 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:
<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:
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 (,).
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.
5.shift ():
The shift () method removes the first item of an array, and returns that
item.
6.unshift ():
The unshift () method adds new items to the beginning of an array, and returns
the new length.
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.
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.
10.splice ():
The splice () method adds/removes items to/from an array, and returns the
removed item(s).
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>
}
</script>
</head>
<body>
<script language="javascript">
Addition(10,15);
</script>
</body>
</html>
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.
<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
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.
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”);
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