Web Tech PDF
Web Tech PDF
Web Tech PDF
UNIT-I
Internet Principles and Components: History of the Internet and World Wide Web –
HTML - protocols – HTTP, SMTP, POP3, MIME, IMAP. Domain Name Server, Web
Browsers and Web Servers. HTML-Style Sheets-CSS-Introduction to Cascading Style
Sheets-Rule-Features- Selectors- Attributes. Client-Side Programming: The JavaScript
Language- JavaScript in Perspective-Syntax-Variables and Data Types-Statements-
Operators-Literals-Functions-Objects-Arrays-Built-in Objects-JavaScript Debuggers and
Regular Expression.
2 MARKS
1. Define internet?
Network is an interconnection of systems to share data and information. Internet is network of
network or collection of heterogeneous networks.
The Internet is a global system that consists of millions of public, private, academic, business, and
government networks of local to global scope. It allows all the computers connected to it to exchange
information with one another.
7. What isprotocol?
A protocol is a set of rules or an agreement that specifies a common language that computer on a
network use for communication with other computers. It specifies on how the computer talk with
each other.
A protocol is a set of rules that define the syntax and semantics of the connection, communication,
and data transfer between two computing end-points.
Web browser fetches a page from a web server by an http request. The request includes page address
of an http standard.
Some of the web browsers are:
✓ MozillaFirefox,
✓ Googlechrome,
✓ Internet explorerand
✓ Operaetc.
Unordered List:
It starts with <ul> and ends with </ul>
Attributes of Unordered lists
Type
TYPE = FILLROUND or TYPE = SQUARE
Example:
<UL TYPE = FILLGROUND>
<LI> CSE </LI>
<LI> IT </LI>
</UL>
Output:
▪ CSE
▪ IT
Ordered List(Numbering):
TYPE: Controls the numbering scheme to be used
TYPE = “1” will give counting numbers (1,2,…).
“A” will give A, B, C...
“a” will give a,b,c
“I” starts with Capital roman letters I, II, II…
“I” starts with small case roman letters.
START: Alters the numbering sequence can be set to any numeric value.
VALUE: Change the numbering sequence in the middle of an ordered list.
Example:
<OL TYPE = “1” START = 5>
<LI> CSE </LI>
<LI> IT </LI>
</OL>
Output:
5. CSE
6. IT
25. Explain the attributes of table tag with anexample?
A table is a two dimensional matrix, consisting of rows and columns. All table related tags are
included between <TABLE> </TABLE> tags.
<TABLE BORDER=“3” WIDTH=”100” HEIGHT=”200”>
<TH> Heading </TH> <TR>
Row elements </TR> <TD>
Table data values </TD>
</TABLE>
Syntax:
<MAP NAME = “map name”>
Attributes of Frames:
▪ ROWS–This attributeisusedtodividethescreenintomultiplerows.Itcanbesetequaltoalist of
values. Depending on the required size of each row. The values can a number ofpixels.
▪ Expressed as a percentage of the screenresolution.
▪ The symbol *, which indicates the remainingspace.
▪ COLS – This attribute is used to divide the screen into multiplecolumns.
Example:
<FRAMESET ROWS = “30 %,*”> => Divides the screen into 2 rows, occupying the remaining space.
<FRAMESET COLS = “50%, 50 %”> => Divides the first row into 2 equal columns.
<FRAME SRC =“file1.html”>
<FRAME SRC =“file2.html”>
<FRAMESET COLS = “50%, 50 %”> => Divides the second row into 2 equal columns.
<FRAME SRC =file3.html”>
<FRAME SRC =file4.html”>
</FRAMESET>
44. DefineDHTML?
▪ DHTML stands for DynamicHTML.
▪ It is NOT a language or a webstandard.
▪ It means the combination of HTML, JavaScript, DOM andCSS.
According to the World Wide Web Consortium (W3C): “Dynamic HTML is a term used
by some vendors to describe the combination of HTML, style sheets and scripts that
allows documents to be animated”.
Example:
#para1 {
text-align: center;
color: red;
}
Example:
All HTML elements with class="center" will be red and center-aligned:
.center {
text-align:center;
color:red;
}
2. The [attribute="value"]selector is used to select elements with a specified attribute and value.
The following example selects all <a> elements with a target="_blank"attribute:
a[target="_blank"] {
background-color: yellow;
}
3. The[attribute~="value"]selectorisusedtoselectelementswithanattributevaluecontaininga
specifiedword.
The following example selects all elements with a title attribute that contains a space-separated list
of words, one of which is "flower":
[title~="flower"] { border:
5px solid yellow;
}
4. The [attribute|="value"]selector is used to select elements with the specified attribute starting
with the specifiedvalue.
The following example selects all elements with a class attribute value that begins with
"top": [class|="top"] {
background:yellow;
}
5. The [attribute$="value"] selector is used to select elements whose attribute value ends with a
specifiedvalue.
Thefollowingexampleselectsallelementswithaclassattributevaluethatendswith "test":
[class$="test"]{
background:yellow;
}
6. The [attribute*="value"]selector is used to select elements whose attribute value contains a
specifiedvalue.
The following example selects all elements with a class attribute value that contains
"te": [class*="te"]{
background: yellow;
}
P a g e | 17WEB TECHNOLOGY
53. What are the types ofCSS?
There are four ways to specific style information in a document
i. External stylesheet
ii. Embedded stylesheet
iii. Imported stylesheet
iv. Inline stylesheet
P a g e | 18WEB TECHNOLOGY
57. Explain the JavaScript variables with an example?
▪ JavaScript variables are containers for storing datavalues.
▪ Javascript allows us to create and manipulatevariables.
▪ Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the varkeyword:
var carName;
var x = 5;
var person = "John Doe";
var person = "John Doe", carName = "Volvo", price = 200;
Example:
document.getElementById("demo").innerHTML = "Hello Dolly.";
P a g e | 19WEB TECHNOLOGY
62. List the various operators inJavaScript?
JavaScript supports the operators are
i. Arithmetic operators
ii. Assignmentoperators
iii. Relationaloperators
iv. Logicaloperators
v. Bitwiseoperators
Example:
Creating an array with four elements.
var fruits = ["Orange", "Apple", "Banana", "Mango"]
Syntax:
function name(parameter1, parameter2, parameter3)
{
code to be executed
}
P a g e | 20WEB TECHNOLOGY
66. What is functionInvocation?
The code inside the function will execute when "something" invokes (calls) the function:
▪ When an event occurs (when a user clicks abutton).
▪ When it is invoked (called) from JavaScriptcode.
▪ Automatically(self-invoked).
Example:
var cars = new Array("Saab", "Volvo", "BMW");
P a g e | 21WEB TECHNOLOGY
71. What are the various Built-in objects inJavaScript?
▪ Mathobject
▪ Stringobject
▪ Date object
▪ Boolean and Numberobjects
▪ Arrayobject
▪ Regular Expressionobject
▪ Documentobject
▪ Windowobject
Example:
var patt = /w3schools/i;
P a g e | 22WEB TECHNOLOGY
where
▪ /w3schools/i is a regularexpression.
▪ w3schools is a pattern (to be used in asearch).
▪ i is a modifier (modifies the search to becase-insensitive).
P a g e | 23WEB TECHNOLOGY
11 MARKS
Internet:
▪ The internet is a collection of interconnected computer networks, linked by copper wires, fiber
optic cables, wireless connectionsetc.
▪ Network is an interconnection of systems to share data and information. Internet is a network of
network or collection of heterogeneousnetworks.
▪ The internet (also known as net) is the worldwide, publicly accessible system of interconnected
computer networks that transmit data by packet switching using the standard Internet Protocol
(IP).
▪ It consists of millions of smaller domestic, academic, business and government networks, which
together carry various information services suchas
✓ Electronic mail
✓ Online chat
✓ Interlinked webpages
✓ Other documents ofWWW
Internetworks (Networks):
When two or more networks are connected, they become an internetworks or networks
LAN R LAN
R R
Web:
The web is a collection of interconnected documents, linked by hyperlinks and URLs and is accessible
using the Internet.
P a g e | 24WEB TECHNOLOGY
Applications of internet:
▪ Electronic mail
▪ World WideWeb
▪ FTP
▪ Telnet
▪ Chat & Onlinetransaction
History of theInternet:
▪ The USSR (Russia) launch of Sputnik spurred the U.S. to create the Advanced Research Project
Agency (ARPA) in February 1958 to regain a technologicallead.
▪ ARPA created the information processing technology office (IPTO), to further the research of the
semi-Automatic Ground, Which had networked country-wide radar systems together for the first
time.
▪ In late 1960’s, one of the authors (HMD) research project MAC was funded by ARPA – of the
Department of Defense(DOD).
▪ ARPA rolled out for networking the main computer systems of about a dozen ARPA – funded
universities and researchinstitutions.
▪ They were to be connected with communications lines operating at a then – stunning 56kbps
(i.e., 56.000 bits per second) - this at a time of most people was connecting over telephone lines
to computers at a rate of 110bps.
▪ ARPA proceeded to implement the ARPANET which eventually evolved into today’sinternet.
▪ Researchers to share each other’s computers, it rapidly became clear that enabling researchers
to communicate quickly and easily (via) became known as electronicmail(e-mail).
▪ As e-mail facilities communications of all kinds among a billion peopleworldwide.
P a g e | 25WEB TECHNOLOGY
▪ The network was designed to operate without centralized control. If a portion of the network
failed, the remaining working portions would still route packets from senders to receivers over
alternative paths forreliability.
▪ The protocol for communicating over the ARPANET became known as TCP – the Transmission
ControlProtocol.
▪ TCP ensured that messages were properly routed form sender to receiver and that they arrived
intact.
▪ Internet involved, organizations worldwide were implementing their own networks forboth
✓ intero-organization (within theorganization)
✓ inter- organization (betweenorganization)
▪ ARPA accomplished with internet protocol (IP), creating a “network of networks”, the current
architecture of the internet the combined set of protocols is commonly calledTCP/IP.
Usage:
▪ Internet was limited to universities and research institutions; then the military began using
theinternet.
▪ The government decided to allow access to the internet for commercialpurposes.
P a g e | 26WEB TECHNOLOGY
▪ The internet mixes computing & communication technologies. It makes our work easier. It
makes information instantly and conveniently accessibleworldwide.
▪ Itenablesindividualsandsmallbusinesstogetworldwideexposure.Itischangingtheway
business isdone.
▪ People can search for the best prices on virtually any product or service special interest
communities can stay in touch with oneanother.
▪ HTTP – Communication between a web server and a webbrowser.
▪ HTTP is used for sending requests from a web client (browser) to a web server, returning web
contents (web pages) from the server back to theclient.
The World Wide Web (abbreviated WWW or the Web) is an information space where documents and
other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links,
and can be accessed via the Internet. English scientist Tim Berners-Lee invented the World Wide Web in
1989. He wrote the first web browser computer programmein 1990 while employed at CERNin
Switzerland.
The World Wide Web is known as WWW or W3 or Web. The World Wide Web is an architectural
frame work for accessing linked documents and repository of information spread all over the Internet.
The WWW has a unique combination of flexibility, portability and user-friendly features that distinguish
it from other services provided by the Internet. The main reason for its popularity is the use of a concept
called hypertext. Hypertext is a new way of information storage and retrieval, which enables authors to
structure information in novel ways. An effectively designed hypertext document can help users rapidly
locate the desired type of information from the vast amount of information on the Internet. Hypertext
documents enable this by using a series of links. A link is a special type of item in a hypertext document,
which connects the document to another document that provides more information about the linked
item.
Hypertext documents on the Internet are known as Web pages. Web pages are created by using
a special language called hypertext markup language (HTML). HTML is becoming a de-facto industrial
standard for creating Webpages.
The WWW uses the client-server model, and an Internet protocol called hypertext transport
protocol (HTTP) for interaction between the computers on the Internet. Any computer on the Internet,
which uses the HTTP protocol is called a Web server and any computer, which can access that server is
called a Web client.
Uniform Resource Locator (URL) – To access a webpage, one requires an address. For any data
access distributed all over world, WWW uses the concept of locators. Any kind of information can be
defined on the Internet using the standard URL. URL defines three things – method, host computer and
pathname.
Method – It is the protocol used to retrieve the document. For example, Gopher, FTP, HTTP,
news, TELNET,etc.
P a g e | 27WEB TECHNOLOGY
The World Wide Web has been central to the development of the Information Age and is the primary tool
billions of people use to interact on the Internet. Web pages are primarily text documents formatted and
annotated with Hypertext Markup Language(HTML). In addition to formatted text, web pages may
contain images, video, audio, and software components that are rendered in the user's web browser as
coherent pages of multimediacontent. Embedded hyperlinkspermit users to navigatebetween web pages.
Multiple web pages with a common theme, a common domain name, or both, make up a website.Website
content can largely be provided by the publisher, or interactive where users contribute content or the
content depends upon the user or their actions. Websites may be mostly informative, primarily for
entertainment, or largely for commercial, governmental, or non-governmental organizational purposes.
P a g e | 28WEB TECHNOLOGY
▪ With these tags lie the header tags <HEAD> ……</HEAD>; the HEAD tags are always first and do
not contain the page’s actualcontent.
▪ The only content the page title enabled through the TITLEtags.
▪ The TITLE tags occur within the HEAD tags and are the name of the browser window that is
currentlyactive.
▪ The HEAD tag can also containscript.
▪ The syntax for the HEADsection
1. TITLE – Documenttitle
2. LINK – Sitestructure
3. BASE – Documentlocation
4. SCRIPT – Java script and VBscript
Example:
<Html>
<Head>
<Title> Example Of Web </Title>
</Head>
</Html>
P a g e | 29WEB TECHNOLOGY
The various types of tags in HTML are
Heading tags:
▪ HeadinginHTMLaretobeusedlikeheadinginBooksandNewspapers.Headingsdividesectionsof text
and improve pagereadability.
▪ The above six levels of headings defined byHTML.
✓ <H1>……</H1> - Level 1 Header
✓ <H2>……</H2> - Level 2 Header
✓ <H3>……</H3> - Level 3Header
✓ <H4>……</H4> - Level 4 Header
✓ <H5>……</H5> - Level 5 Header
✓ <H6>……</H6> - Level 6 Header
Example:
<HTML>
<HEAD>
<TITLE> HEADING OG VARIOUS SIZE </TITLE>
</HEAD>
<BODY>
<H1> IP </H1>
<H2> Web </H2>
.
.
.
<H6> Technology </H6>
</BODY>
</HTML>
P a g e | 30WEB TECHNOLOGY
Text level elements:
▪   is used to insert a single blankspace.
▪ <BR> indicates the line break sometimes user might want to use is to separate text intoparagraphs.
▪ <P> …. </P> - Paragraph tag. These tags add a blank line before and after the block they enclose.
Two line break tag can be usedconsecutively.
▪ <B>…..</B> - Boldtag
▪ <I>…..</I> - Italictag
▪ <U>…..</U> - Underlinetag
▪ It can effect as indicated in the modification of thefont.
Example:
<HTML>
<HEAD>
<TITLE> Page with HTML Format tag </TITLE>
</HEAD>
<BODY>
<B> India is one of the developing country </B>
<BR>
<I> Web Technology </I>
<U> Internet Programming </U>
<P> Welcome to web technology laboratory
</P> </BODY>
</HTML>
Output:
Web Technology
Internet Programming
Lists of text:
The most commonly list are of 2 types
1. Ordered Lists(OL)
2. Unordered Lists(UL)
P a g e | 31WEB TECHNOLOGY
▪ The ordered list tags <OL>……</OL> create ordered listitem.
▪ The unordered list tags <UL>……</UL> create unordered listitem.
▪ For each list item in the list, within either of these set of tag, user can use the listing tag (LI) – List
Item, this tag is used singly and does not have an endtag.
▪ <HR> is used to draw a horizontal line on the web page requires only a singletag.
Example:
<HTML>
<HEAD>
<TITLE> Using Lists </TITLE>
</HEAD>
<BODY>
<HR>
<UL>
<B> SMVEC
<LI>CSE
<LI>IT
</B>
</UL>
Dept
<OL>
<LI> Computer
<LI> Information
</OL>
</BODY>
</HTML>
Output:
SMVEC
• CSE
• IT
Dept
1. Computer
2. Information
Example:
<HTML>
<HEAD>
<TITLE> Using definition lists </TITLE>
</HEAD>
<BODY>
<U> <H2> Bharath infotech </H2> </U>
<Font size = 2 >
<DL>
<DT> The company </DT>
<DD> Mr. X is the CEO of thecompany</DD>
<DD> Mr. Y & Z are the incharge ofQC</DD>
</DL>
</Font>
</BODY>
</HTML>
Output:
Bharath Infotech
The Company
Mr. X is the CEO of the company
Mr. Y & Z are the incharge of QC
Font tag:
<Font color = “Red” Face = “Times” size = 5>
All data displayed here is red in color and has the times font and the size is 5
</Font>
Example:
<html>
<head>
<title> Linking <title>
</head>
<body>
<h1 align=center> My favorite search sites</h1>
<p align=center> The yahoo!: <a href=””> http://www.yahoo.com</a> </p>
<p align=center> The Google: <a href=”> http://www.google.com</a>
</p> </body>
</html>
Output:
The yahoo! :
http://www.yahoo.comThe google :
http://www.google.com
Internal linking:
▪ To create links to external documents. HTML has facilities to include internal links also by
assigning a location name to any individual point in an HTMLdocument.
▪ This location name can then be added to the pageURL
Example:
<html>
<head>
<title> Internal Linking <title>
</head>
<body>
<h1 align=center> My book </h1>
<p> the book contains the following chapters </p> <br>
<a href = “#chap1” > 1. Introduction </a> <br>
<a href = “#chap2” > 2. Topics1 </a><br>
<a href = “#chap3” > 3. Topics2 </a><br>
<a name = “chap1” > </a>
<h3 align = “center”> Chapter 1 </h3>
<p> The text is here </p> <br>
<a name = “chap2” > </a>
<h3 align = “center”> Chapter 2 </h3>
<p> The text is here </p> <br>
<a name = “chap3” > </a>
<h3 align = “center”> Chapter 3 </h3>
<p> The text is here </p> <br>
</body>
</html>
Output:
My book
The book contain the following chapters
1. Introduction
2. Topics1
3. Topics2
Chapter1
The text is here
Chapter2
The text is here
Example:
< img src = “url “ height = “144” border = “1” width = “200” alt = “An image is here”>
</img>
The other related tag is <map> which is used to create hot spots. The syntax
is <map name = “ “>
……
</map>
Example:
The following code creates a hot spot of rectangular shape and has the hyperlink in the coordinates
mentioned.
<map>
<area shape = “rect” cords =”23, 45, 56, 89” href = “source.html”>
</map>
Frames:
▪ Frame layout is one in which the browser windows is broken into multiple region calledframes.
▪ Each frame contains different HTMLdocuments.
▪ The <frameset> tag is a container for frames and replaces the body tag.</frameset>
▪ <frame> tag is used to place the contents into theframe.
Example:
▪ Divides the window into 2 regions in rowwise
<frameset rows = “30%,70%”>
▪ The <frame> tag is used to place different HTML documents in eachframe.
<frame src = “ “ frameborder = “0|1” name = “name” scrolling = “yes|no|auto”>
Example:
<html>
<head>
<title> Internal Linking <title>
</head>
<frameset cols = “40% , * “>
<frame src=”list1.html”>
<frame src=”l.html”>
</frameset>
</html>
Other tags:
▪ & – is used to insert anampersand
▪ The tag <del> is used to strike through text with a horizontalline.
▪ The tag <sub> and <aup> are used to turn the text into subscript andsuperscript.
▪ To draw a horizontal line in the web page <hr> tag is used. This tag has 3attributes
✓ width – to specify the width of theline
✓ size – to specify the height of theline
✓ noshade – eliminates the default shading effect and instead display the horizontal rule as
a solid colorbar.
Example:
<hr noshade width = “50%” size = 5 align = “center”>
Example:
<table>
<tr>
<td> apples</td>
<td> celery</td>
</tr>
<tr>
<td> oranges </td>
<td> carrots </td>
</tr>
</table>
Output:
apples celery
oranges carrots
▪ <caption> tag is used to be added to row and column headings. By default it will be aligned in center
of atable.
▪ <border> is used for draw a border around the tables and the individual cells. Specify the border
width inpixels.
Example:
<table border = 1>
<caption> Fruits and vegetables </caption>
<tr>
<th> Fruits </th>
<th> vegetables </th>
</tr>
Output:
Fruits and Vegetables
fruits vegetables
apples celery
oranges carrots
▪ Color can be added to tables by using the bgcolor = and bordercolor = attributes. These attributes
are available in the Table, <tr> and <td> elements; so user can apply colors to all the cell in a table,
selected rows and individualcells.
Example:
<table border = “1” cellspacing = “10%” cellpadding = “10%”> …. </table>
Spanning rows:
▪ The two types of attributes are
✓ colspan – to spancolumn
✓ rowspan – to spanrows
Example:
<table border = “2”>
<tr>
<th colspan = 3> Tic Tac Games </th>
</tr>
<tr>
<td> X</td>
<td> O</td>
<td> X</td>
</tr>
</table>
Example:
<table border color = “navy” border = 5>
<tr bgcolor = “gray”>
<th> Fruits </th>
<th> Vegetables </th>
</tr>
<tr>
<td bgcolor = “lime”> Apples</td>
<td bgcolor = “Aqua”>Celery</td>
</tr>
<tr>
<td bgcolor = “lime”> Oranges</td>
<td bgcolor = “Aqua”> Carrots</td>
</tr>
</table>
HTML Forms:
▪ Form provides a way to prompt the user for information and to carry out the actions based on the
input.
▪ A form consists of one or more input controls that the user uses to enter text and selectchoices.
▪ Once the user provides the input, the form collects the data and sent it to a destination specified in
the formelement.
▪ To carry out the requested action, the server must have a script or other service that corresponds to
thedestination.
▪ A form can contain inputs like text fields, check boxes, passwords, radio-buttons, submit buttons
and resetbuttons.
▪ The <form> tag is used to create an HTMLform.
<form name=” frm1“ action=”index.jsp“ method=”get | post” >
</form>
▪ HTML forms are used to pass the data to theserver.
Input Element:
The <input> element can be displayed in several ways, depending on the type attribute.
▪ TextFields
▪ Password
▪ RadioButton
▪ CheckBoxes
▪ SubmitButton
▪ ResetButton
▪ ImageButton
The syntax is
<input type = “text | passwd” name =”name” value =”default_value” size=”field size”>
1. TextFields:
<input type=”text”> defines a one line input field that a user can text into.
Example:
<form>
First name: <input type=”text” name=”first name”>
Last name: <input type=”text” name=”last
name”> </form>
2. PasswordField:
<input type=”password”> defines a password field.
Example:
<form>
Password: <input type=”password” name=”pwd”>
</form>
*******
▪ The characters in a password field are masked (shown as asterisks orcircles).
3. RadioButtons:
▪ <input type=”radio”> defines a radiobutton.
▪ Radio buttons let a user to select only one of a limited number ofchoices.
Example:
<form>
Gender <input type=”radio” name=”gender” value=”male” checked> Male
Gender <input type=”radio” name=”gender” value=”female”> Female
</form>
The output is
Male
Female
4. Checkboxes:
▪ <input type=”checkbox”> defines acheckbox.
▪ Checkboxes let a user to select one or more options of a limited number ofchoices.
Example:
<form>
<input type=”checkbox” name=”vehicle” value=”bike”> Bike <br>
<input type=”checkbox” name=”vehicle” value=”car”> Car
</form>
5. Submit Button
▪ <input type=”submit”> defines a submitbutton.
▪ A submit button is used to send the form data to a server. The data is sent to the page specified in
the form’s actionattribute.
▪ The file defines in the action attribute usually does something with the receivinginput.
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
Submit
Username:
▪ Click the “submit” button, the browser will send your input to a page called“filename”.
6. ResetButton:
▪ A reset button is used to clear all thefields.
<input type= "reset" value= "Clear" >
7. ImageButton:
<input type=”image” src=” “ name=”submit” value=”submit”>
8. Filename:
<input type=”file” name=”filename” value=” “ size=25> Browser
Example:
Browse
The Syntax is
<textarea name=”name” rows=”no of rows” cols=”no of cols” accesskey=”shortcut
key”></textarea>
▪ The rows attribute specifies the visible number of lines in a textarea.
▪ The cols attribute specifies the visible width of a textarea.
Output:
Select Element:
▪ This form tag is used to set up a list of choices from which a user can select one ormany.
▪ The <option> elements defines an option that can beselected.
▪
By default, the first item in the drop-down list is selected.
The syntax is
<select name=”name”>
<option>… ........... </option>
</select>
Example:
<form name=”form1”>
Text<input type=”text” name=”textfield” size=”20”> <br>
<select name=”select1”>
<option>Item1</option>
<option>Item2</option>
</select>
</form>
Output:
Example:
<button type="button" onclick="alert('Hello World!')"> Click Me! </button>
Output:
Click Me!
1. The method attribute specifies how to send form-data (the form-data is sent to the page specified
in the actionattribute).
2. The form-data can be sent as URL variables (with method="get") or as HTTP post transaction
(withmethod="post").
POST Method:
• Appends form-data inside the body of the HTTP request (data is not shown is inURL).
• Has no sizelimitations.
• Form submissions with POST cannot bebookmarked.
Write an HTML document to provide a form that collect name and telephone numbers.
<html>
<head>
<title> Form for Name and Telephone Numbers </title>
</head>
<body> <center> <h1> Customer Name and telephone Numbers </h1> </center> <form
name="cust" action=" home.jsp" method="post">
<table align="center" cellpadding="10%" cellspacing="5%"
border="1"> <tr>
<th> NAME : </th>
<th> <input type="text" name="login" size=20> </th>
</tr>
<tr>
<th> PHONE NUMBER </th>
<th> <select name="Phone_No">
<option> +91</option>
<option> +90 </option>
</select>
<input type="text" name="phone_no" size="20"> </th>
</tr>
<tr>
<th> <input type="submit" value="Submit"> </th>
<th> <input type="reset" value="Clear"> </th>
</tr>
</table>
</form>
</body>
</html>
Example Program:
<html>
<head>
<title> Frame </title>
</head>
<body>
<center> <h1>Form Submission </h1> </center>
<form action=" home.jsp" method="get">
Login Name: <input type="text" name="login" size=20> <br>
Password: <input type="password" name="pass" size=20> <br>
Birthdate: <input type="text" name="DOB" size=20> <br>
Gender: <input type="radio" name="gender" value="F" checked>
Female <input type="radio" name="gender" value="m"> Male <br> <br>
Department
<select name="dept">
<option> CSE</option>
<option> IT</option>
</select> <br>
Output:
“GET/home/web/cs336/syll.so9 HTTP/1.0\r\n”
Command
Resource
Pathname(UNIX Protocol & CarriageReturn
filenameSyntax) Version &Line-Feed
i. Request Method
The various methods supported by HTTP are:
METHODS DESCRIPTIONS
GET Gets a file from the server (or) tells the server the client wants to get some resource.
POST Sends user information to the server (or) tells the server the client wants to get
some resources and information will be sent by the client that may modify the
request (ex: Submitting the form).
HEAD Gets information about a file from the server.
PUT Sends a file to be stored on the server (transfers a file from the client to the server).
DELETE Deletes a file on the server.
OPTIONS Requests the available server options.
URL
Format:E
xample:
Method: //host: port/path/filename
http://www.google.com:80/icuse/cs336/syllabus.pdf
Example:
GET/HTTP/1.0
HTTP/1.0 200 OK
Date: Mon, 12 Dec 2011 11:40:40 GMT
Server: Apache/1.3.3.7 (UNIX)
Last_Modified: Wed, 08 Jan 2003 12:10:10 GMT
E tag: “3f80F-1b6-3e1cb03b”
Server receives a request and uses its URL to decide how to handle it.
▪ Accept-Range:bytes
▪ Content-Length:438
▪ Connection:close
▪ Content-Type:text/html
▪ Etag (Entity Tag) header is used to determine if a cached version of the requested resource is
identical to the current version of the resource on theserver.
▪ Content-Type specifies the internet media type of the data conveyed by the HTTPmessage.
▪ Content-Length indicates it length inbytes.
▪ The HTTP/1.1 Web Server publishes its ability to respond to requests for certain byte range
of the document – accept rangesbytes.
▪ Connection: Close is sent in a header. It means that the web server will close theTCP
connection immediately after the transfer of thisresponse.
SMTP provides for mail exchanges between users on the same or different computers and supports
are
▪ Sending a single message to one or morerecipients.
▪ Sending messages that include text, audio, video format or graphicsfile.
▪ Sending messages to users onnetworks.
SMTP:
▪ It is used to exchange mail messages between mail servers(MTA).
1. User Agent(UA):
▪ The UA is normally a program used to send and receivemail.
▪ Example: Gmail, yahoomail,Hotmail
Addresses
▪ To deliver mail, a mail handling system must use a unique addressingsystem.
▪ The addressing system used by SMTP as 2parts
✓ A localpart
✓ A domain name, separated by an @sign
e-M ailAddress
Localpart @ domain name
Domain Name
▪ The 2nd part of the address is the domainname.
▪ An organization usually selects one or more hosts, to receive and send e-mail. They are called
mailexchangers.
▪ The domain name assigned to each mail exchanger from the DNSdatabase.
Example: prince@yahoo.com
Local Domainname
SMTP Commands
▪ The SMTP provides a two way communication between the client and the server (remote)
MTA.
▪ The client MTA sends commands to the server MTA, which turns, sends replies back to the
clientMTA.
▪ SMTP refers to the exchange of SMTP commands and replies between two hosts as mail
transactions.
Data Format:
▪ ASCII only – must convert binary to an ASCII representation to send viae-mail.
Example:
Date: Sat, 27 Jan 02 13:26:24 GMT
From:
gang@gmail.comTo:
gang2@yahoo.comSubj
ect: meeting
Let’s get together Monday at 1pm.
R 220 gang2@yahoo.com SMTP service at 29 Jan 02 05:17:11 GMT
S HELOgang@gmail.com
R 250gang2@yahoo.com
S mail from: <gang@gmail.com>
R 250 mail Accepted
S RCPT TO: <gang2@yahoo.com>
R 250 Recipient Accepted
Sender DATA
R 354 start mail input; end with <CRLF>. <CRLF>
S Date: Sat, 27 Jan 02 13:26:21 GMT
S From:
gang@gmail.comS To:
gang2@yahoo.comS
Subject: meeting
S
S Let’s get together Monday at 1pm.
S
R 250 OK
S QUIT
R 221 gang2@yahoo.com service closing transmission channel
▪ Post Office Protocol Version3 (POP3) is used to retrieve e-mail from an internetmailbox.
▪ POP3 is used to retrieve mail for a single user; typically the POP server has access to a database
of email messages created by an SMTPserver.
▪ POP3 is used to download messages from theserver.
▪ POP3 connections require authentication in the form of a secret (i.e.,) shared by the user and the
POP server (apassword)
▪ POP3 sessionpasses
✓ Authentication
✓ Transaction
✓ Update
▪ In the authorization state, the client identifies itself to theserver.
▪ If the authorization is successful, the server opens the client’s mailbox and the session enters the
transactionstate.
▪ In this state, the client requests the POP3 server provide information or perform anaction.
▪ When it enters the update state, the connectionterminates.
POP commands:
▪ POPcommandsandrepliesareformattedasASCIIlinesandallrepliesstartwitheither “+OK”
or“-ERR”.
Command Description
USER Requires a name that identifies the user (Specify username).
PASS Specify password for the user/server.
STAT Get mailbox status (no. of messages in the mailbox).
LIST Get a list of messages and size, one per line, termination line contains a period.
RETR Retrieves message from mailbox.
DELE Marks a message for deletion.
LAST The server returns the highest message no accessed.
RSET Unmarks all messages marked for deletion.
QUIT Remove marked messages and close the TCP connection.
QPOP3
char “popmessage[]”
{
“USER your_mailbox_id\r\n”,
“PASS your_password\r\n”,
“STAT\r\n”,
“LIST\r\n”,
“RETR\r\n”,
“DELE\r\n”,
“QUIT\r\n”,
NULL
};
▪ MIME transforms non-ASCII data at the sender site to NVT ASCII data and delivers them to
the client MTA to be sent through theInternet.
▪ The message at the receiving side is transformed back to the originaldata.
▪ NVT→(Network VirtualTerminal)
MIME Headers:
The 5 header fields to internet e-mail messages.
1. MIMEversion
2. Contenttype
3. Content transferencoding
4. Contentid
5. Contentdescription
2. Contenttype:
▪ This header defines the type of data used in the body of themessage.
▪ The content type and the content subtype are separated by aslash.
▪ Depending on the subtype, the header may contain otherparameters.
Content-Type : < type / sub-type >
2. Content–Transfer:
▪ This header defines the method used to encode the messages into 0’s and 1’s fortransport.
Content -Transfer – Encoding: < type >
4. Content-Id:
▪ This header uniquely identifies the whole message in a multiple-messageenvironment.
Content-Id: id = < content-id >
5. Content-Description:
▪ This header defines whether the body is image, audio, orvideo.
Content-Description: <description>
▪ The feature of IMAP is the mail messages remain on the server, instead of being downloaded to a
computer.
▪ Checking the mail with a client or web-based environment using theprotocol.
▪ IMAP supports the use of folders for mail organization, but instead of organizing the messages on
the local computer, these folders are kept on theserver.
▪ IMAP is quicker access to mail.
▪ The message headers are initially downloaded so the user can choose to download, open and
read only thismessage.
▪ Using IMAP and saving messages on the server is that the user will berestricted.
The Namespace
▪ The namespace is the structure of the DNSdatabase.
✓ An inverted tree with the root node at thetop.
▪ Each node has alabel.
✓ The root node has a null node written as ““.
Root Node
Labels
▪ Each node in the tree must have alabel
✓ A string of upto 63(8 bitbytes)
▪ Legal characters are a-z &A-Z
▪ Sibling nodes must have uniquelabel
▪ The null label is reserved for the rootnode
Root
1. GenericDomains:
▪ The generic domains define registered host according to their genericbehavior.
▪ Each node in the tree defines a domain, which is an index to the domain namespacedatabase.
▪ It represents as 3 character labels.
▪ Ex: com,edu.
Sub-Domain
▪ One domain is a sub domain of another if its apex node is a descendant of the others apex
node.
▪ One domain is a sub domain of another if its domain name is in the other’s domainname.
▪ Ex: sales.google.com is a subdomainof
✓ google.com
✓ com
▪ Administrators can create subdomains to grouphosts.
▪ The parent domains retain links to the delegatedsubdomains.
Zones
▪ The subdomain and its parent domain can now be administrated independently. These units
are calledzones.
▪ The boundary between zones is a point of delegates in thenamespace.
univ
3. InverseDomain:
▪ The inverse domain is used to map an address to aname.
▪ For ex, when a server has received a request from a client to do atask.
▪ The server has a file that contains a list of authorized clients; the server lists only the IP
address of theclient.
▪ If the client is on the authorized list, it can send a query to the DNS server and ask for a
mapping of address toname.
▪ Infrastructure domains as
✓ IPv4 reverse (address to name)lookups
✓ IPv6 reverselookups
▪ DNS root server get approximately 3000 queries persecond.
WEB BROWSER:
Although browsers are primarily intended to use the World Wide Web, they can also be used to
access information provided by web servers in private networks or files in file systems. A web browser
is a software program that enables you to view andinteract with any information available on the Web.
Web comprises of a number of text files generally written in HTML language that are linked to each
other is a specific manner and these text files are called HTML Web pages. These web pages can be
viewed with the help of a software program known as web browsers. Web browsers acts as a user
interface for users to navigate in the web pages, read content and perform actions such as click buttons,
click on hyperlinks to another web page, select text, enter URL (uniform resource locator) of a web page
to access etc.
Web Browser is an application software that allows us to view and explore information on the web.
User can request for any web page by just entering a URL into address bar.
Web browser can show text, audio, video, animation and more. It is the responsibility of a web
browser to interpret text and commands contained in the web page.
Earlier the web browsers were text-based while now a days graphical-based or voice-based web
browsers are also available.
Browser Vendor
Internet Explorer Microsoft
Google Chrome Google
Mozilla Firefox Mozilla
Netscape Navigator Netscape Communications Corp.
Opera Opera Software
Safari Apple
Sea Monkey Mozilla Foundation
K-meleon K-meleon
Architecture:
There are a lot of web browser available in the market. All of them interpret and display information on
the screen however their capabilities and structure varies depending upon implementation. The most
basic component that all web browser are
1. Controller/Dispatcher
2. Interpreter
3. ClientPrograms
Web server is a computer where the web content is stored. Basically web server is used to host
the web sites but there exists other web servers also such as gaming, storage, FTP, email etc.
Web site is collection of web pages while web server is a software that respond to the request for web
resources.
Web Server Working
Web server respond to the client request in either of the following two ways:
• Sending the file to the client associated with the requestedURL.
• Generating response by invoking a script and communicating withdatabase.
Architecture:
Web Server Architecture follows the following two approaches:
1. ConcurrentApproach
2. Single-Process-Event-DrivenApproach.
Concurrent Approach
Concurrent approach allows the web server to handle multiple client requests at the same time. It can
be achieved by following methods:
✓ Multi-process
✓ Multi-threaded
✓ Hybridmethod
Multi-processing
▪ In this a single process (parent process) initiates several single-threaded child processes and
distribute incoming requests to these child processes. Each of the child processes are
responsible for handling singlerequest.
▪ It is the responsibility of parent process to monitor the load and decide if processes should be
killed orforked.
Multi-threaded
▪ Unlike Multi-process, it creates multiple single-threadedprocess.
Hybrid
It is combination of above two approaches. In this approach multiple process are created and each
process initiates multiple threads. Each of the threads handles one connection. Using multiple threads
in single process results in less load on systemresources.
Server:
Server Name Foundation
1 ApacheHTTPServer Apache SoftwareFoundation
2 Internet Information Services (IIS) Microsoft
3 JigsawServer World Wide WebConsortium
4 Sun Java System Web Server SunMicrosystems
5 Lighttpd lighttpd
▪ DynamicHyperTextMarkupLanguage(DHTML)isatechniqueofdynamicallychangingthe
rendering content of the HTMLcode.
▪ DHTML is the ability to create visually outstanding HTML documents that interact with the user,
without relying on server side programs or complicated set of HTML pages to achieve special
effects.
▪ It makes possible for the web pages to react to the user actions or to thechanges.
▪ Theimagecanbeanimatedwhenthemousemovesoveritorcertainpartofthedocumenta
separate design can beapplied.
▪ In DHTML, we can hide text and images of a document for a given period of time, create timers
that automatically refresh the content of a document with the latest data, create a form which
can be readily filled up with data, which can be processed and accessedimmediately.
▪ The 3 different technologies in DHTMLare
1. Client side scripting (JavaScript or VBScript)
2. Cascading Style Sheets(CSS)
3. Document Object Model(DOM)
DHTML
Introduction to (CSS):
▪ CSS stands for Cascading StyleSheets
▪ CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
▪ CSS saves a lot of work. It can control the layout of multiple web pages all atonce
▪ External style sheets are stored in CSSfiles.
▪ CSS are rules or styles for organizing the layout of an HTML document including its color,
typefaces, margins, links and other formattingelements.
▪ Style sheets make it easier to create an index because indexing software has only to read the
structural elements rather than full contentpage.
▪ User includes multiple set of style sheetinformation.
▪ It contains rules, composed of selectors and declarations that define how styles areapplied.
▪ The selector (HTML element, class name or ID name) is the link between the HTML document
and thestyle.
✓ HTML elementtags
✓ Attributes (class, ID name)
Rule or Syntax:
A CSS rule set consists of a selector and a declaration block:
Selector { property1: value1; property2: value2; } or tagname {style_attribute value:}
h1 {color : blue; font-size:12px; }
▪ The selector points to the HTML element you want tostyle.
▪ The declaration block contains one or more declarations separated bysemicolons.
▪ Each declaration includes a property name and a value, separated by acolon.
Example 1:
A CSS declaration always ends with a semicolon, and declaration groups are surrounded by curly
braces:
p{
color:red;
text-align:center;
}
Example 2:
<html>
<head>
<style type="text/css" >
body {background-color:yellow;}
h1 {font-size:36pt;}
Example 3:
<style>
body{font: 10pt times; color: black; margin-left: 1in; margin-right: 1in}
</style>
▪ An external style sheet to a document or documents on a site. To link a page to this style sheet
use the linkelement.
▪ Ex: <link ref=style type=”text/css”href=”http://www.google.com/mystyle.css”>
Property Values:
▪ em – overall height of current font <style = font-size:2em>
▪ px – pixels < style = font-size:8px>
▪ in – inches < style = font-size:-5in>
▪ pt – pointsize < style = font-size:8pt>
URL:
▪ WhenURLareusedas apropertyvalue,specifythekeywordURLfollowedbytheactualURL
insideparenthesis.
▪ Ex: <body style=”background-image: url(….)”>
Image:
A Cascading Style Sheets (CSS) file can contain positioning, layout, font, colors and style
information for an entire web site. The file can be referenced by each html file on the site.
CSS is a means of separating the content of an html document from the style and layout of that
document.
File Size
Probably the mostly useful feature of CSS is that all of the style and layout is removed from
the html, so the html page size is very much smaller. The CSS file is downloaded just once by the
visitor's browser and re-used for different pages on a web site. This reduces the bandwidth
requirements for your server and also ensures a faster download for your visitors.
Search Engines
A search engine robot will normally consider the content in the start of your html code is
more important than the text towards the end of the code. For a table based page the contents of the
navigation bar will normally show up as the page description in search engine results. With a CSS
page the navigation can be moved to the bottom of the source code, so the search engine displays
your content instead of your navigation.
Accessibility
Separating style from content makes life very easy for visitors who prefer to view only the
content of a web page, or to modify the content. These could be blind or partially sighted people who
might use a screen reader to interpret a page.
Consistency
Layout and position of navigation can be completely consistent across a site. This was
previously possible only using frame.
Easy maintenance
To change the style of an element looks across the whole site, you only have to make an edit in
one place.
Browser Compatibility
Browser compatibility is very important and CSS addresses this issue nicely. When you
decide to use CSS, you will find that it will improve the characteristic of your website while securing
your visitors with the capacity to view your website as precisely as you have designed it tobe.
Appearance
CSS makes it easy to improve the appearance of a website by allowing you to create a much
more stylish website since CSS offers a wide array of expressive style capableness. With CSS, you will
actually obtain more control over your website's visual aspect. Now, designers can orchestrate the
styles and design of several web pages in a flash.
Bandwidth Savings
Once CSS takes apart your websites content from its design language, you will trim down
your file transfer magnitude significantly. These Bandwidth savings are considerable figures of
insignificant tags that are distracted from a multitude of pages. This will leave less, but more
significant captions, listings and paragraphs.
CSS Selectors:
▪ CSS selectors allow you to select and manipulate HTMLelements.
▪ CSS selectors are used to "find" (or select) HTML elements based on their id, class, type,
attribute, grouping andmore.
1. The elementSelector:
▪ The element selector selects elements based on the elementname.
▪ You can select all <p> elements on a page like this (in this case, all <p> elements willbe
center-aligned, with a red textcolor):
Example:
p{
text-align: center;
color: red;
}
2. The idSelector:
▪ The id selector uses the id attribute of an HTML element to select a specificelement.
▪ An id should be unique within a page, so the id selector is used if you want to select a single,
uniqueelement.
▪ To select an element with a specific id, write a hash character, followed by the id of the
element.
▪ The style rule below will be applied to the HTML element withid="para1":
Example:
#para1 {
text-align: center;
color: red;
}
3. The classSelector:
▪ The class selector selects elements with a specific classattribute.
▪ Toselectelementswithaspecificclass,writeaperiodcharacter,followedbythenameofthe class:
Syntax:
<style type=”text/css”>
.classname {style_attribute: value;}
</style>
Example1:
.center{
text-align: center;
color: red;
}
▪ You can also specify that only specific HTML elements should be affected by aclass.
▪ In the example below, all <p> elements with class="center" will becenter-aligned:
Example 2:
p.center{
text-align: center;
color: red;
}
4. GroupingSelectors:
▪ Size of the style sheets can be reduced usinggrouping
▪ One can group selectors in comma-separateslist.
If you have elements with the same style definitions, like this:
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
▪ You can group the selectors, to minimize thecode.
▪ To group selectors, separate each selector with acomma.
In the example below we have grouped the selectors from the code above:
Con-textual Selectors:
▪ Setting all style properties one can create defaults and then list theexpectations.
▪ ‘em’ elements within ‘H1’ a different color specify as H1 {color: blue} em {color: red} or H1,
em {color: red}
▪ Em elements within H1 should turn red and the colorformat.
▪ Several contextual selectors can be grouped together as: H1 B, H2 B, H1 em, H2 em {color:
red}
1. CSS [attribute]Selector:
▪ The [attribute]selector is used to select elements with a specifiedattribute.
▪ The following example selects all <a> elements with a target
attribute: a[target]{
background-color:yellow;
}
2. CSS [attribute="value"]Selector:
▪ The [attribute="value"]selector is used to select elements with a specified attribute and
value.
▪ The following example selects all <a> elements with a target="_blank" attribute:
a[target="_blank"]{
background-color:yellow;
}
3. CSS [attribute~="value"]selector:
▪ The [attribute~="value"]selector is used to select elements with an attribute value
containing a specifiedword.
▪ The following example selects all elements with a title attribute that contains a space-
separated list of words, one of which is"flower":
[title~="flower"] { border:
5px solid yellow;
}
5. CSS [attribute^="value"]Selector:
▪ The [attribute^="value"]selector is used to select elements whose attribute value begins
with a specifiedvalue.
▪ The following example selects all elements with a class attribute value that begins with
"top": [class^="top"]{
background:yellow;
}
6. CSS [attribute$="value"]selector:
▪ The [attribute$="value"] selector is used to select elements whose attribute value ends
with a specifiedvalue.
▪ Thefollowingexampleselectsallelementswithaclassattributevaluethatendswith "test":
[class$="test"]{
background:yellow;
}
7. CSS [attribute*="value"]selector:
▪ The [attribute*="value"]selector is used to select elements whose attribute value contains
a specifiedvalue.
▪ The following example selects all elements with a class attribute value that contains
"te": [class*="te"]{
background:yellow;
}
▪ Anexternalstylesheetcanbewritteninanytexteditor.Thefileshouldnotcontainanyhtml tags.
The style sheet file must be saved with a .cssextension.
An example of a style sheet file called "myStyle.css", is shown below:
body {
background-color: lightblue;
}
h1 {
color:navy;
margin-left:20px;
}
Example:
style.css
/*External Style Sheet*/
body {font-family: arial}
a.node {text-decoration: none}
a.hover {text-decoration: underline}
li em {font-weight: bold}
h1, em {text-decoration: underline}
ul {margin-left: 20px}
.ul {font-size: .8em;}
Output:
Example 1:
<head>
<style type="text/css" >
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
Example 2:
<html>
<head>
<title>Style Sheet</title>
<!-- Style Sheet -->
<style type="text/css">
em {font-weight: bold; color: blue}
h1 {font-family: times}
p {font-size: 12px; font-family: arial}
.special {color: blue}
</style>
</head>
<body>
<!-- Class Attribute -->
<h1 class="special"> Web Technology </h1>
<p> Deitel </p>
<h1> Client </h1>
<p class="special"> Server
side<em>Computing</em></p> </body>
</html>
Example:
The example below shows how to change the color and the left margin of a <h1> element:
<h1 style="color: blue; margin-left: 30px ;"> This is a heading. </h1>
What is JavaScript?
JavaScript is a scripting language mainly used for writing dynamic Web pages. When a script
written in JavaScript is embedded in a Web page, it will be executed by the Web browser on the
client machine.
JavaScript supports functions as first-class functions - Functions are really objects. Like regular
objects, functions can be created during execution, stored in data structure, and passed to other
functions as arguments.
▪ JavaScript is a client – side scripting language for the World Wide Web that is similar to the
syntax of the Java programminglanguage.
▪ JavaScript is designed to provide limited programmingfunctionality.
Why JavaScript?
▪ By executing more web functionality on the user’s machine, webmasters can optimize their
servers to serve more pages.
▪ The decrease in traffic from constant interaction with the server can also improve a server's
performance.
▪ Becausethelocalmachineisdoingthescriptprocessing,theusercanviewwebpagesmuch faster.
JavaScript Syntax:
A simple JavaScript program:
<html>
<head>
<Title> Hello World </Title>
</head>
<body>
<script language=“javascript”>
document.write(“Hello,World wide web”);
</script>
</body>
</html>
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
▪ JavaScript is a lightweight, interpreted programminglanguage.
▪ Designed for creating network-centricapplications.
▪ Complementary to and integrated withJava.
▪ Complementary to and integrated withHTML.
▪ Open andcross-platform
Client-side JavaScript:
▪ Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
▪ It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTMLcontent.
▪ The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
▪ The JavaScript code is executed when the user submits the form, and only if all the entries
are valid, they would be submitted to the WebServer.
▪ JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly orimplicitly.
Advantages of JavaScript:
Limitation s of JavaScript:
The JavaScript as a full-fledged programming language. It lacks the following important features
▪ Client-side JavaScript does not allow the reading or writing of files. This has been kept for
securityreason.
▪ JavaScript cannot be used for networking applications because there is no such support
available.
▪ JavaScript doesn't have any multithreading or multiprocessorcapabilities.
▪ JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTMLpages.
JavaScript Syntax:
▪ JavaScript can be implemented using JavaScript statements that are placed withinthe
<script>... </script> HTML tags in a web page.
▪ Youcanplacethe<script>tags,containingyourJavaScript,anywherewithinyouwebpage, but it
is normally recommended that you should keep it within the <head>tags.
▪ JavaScript can be placed in the <body> and the <head> sections of an HTMLpage.
▪ The <script> tag alerts the browser program to start interpreting all the text between these
tags as ascript.
The sample example to print out "Hello World". We added an optional HTML comment that
surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add
that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code.
Next, we call a function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language="Javascript" type="text/Javascript">
document.write("Hello World!")
</script>
</body>
</html>
But when formatted in a single line as follows, you must use semicolons −
Case Sensitivity:
▪ JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent
capitalization ofletters.
▪ So the identifiers Time and TIME will convey different meanings inJavaScript.
Comments in JavaScript:
JavaScript supports both C-style and C++-style comments.
▪ Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
▪ Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
▪ JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the //comment.
▪ The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as//-->.
MARKS)JavaScript Variables:
▪ JavaScript variables are containers for storing datavalues.
▪ You can place data into these containers and then refer to the data simply by naming the
container.
▪ Before you use a variable in a JavaScript program, you must declareit.
You can also declare multiple variables with the same var keyword as follows –
<script type="text/javascript">
var money, name;
</script>
JavaScript Identifiers:
▪ All JavaScript variables must be identified with uniquenames.
▪ These unique names are calledidentifiers.
▪ JavaScript identifiers arecase-sensitive.
▪ Identifiers can be short names (like x and y), or more descriptive names (age, sum,
totalVolume).
Storing a value in a variable is called variable initialization. You can do variable initialization at
the time of variable creation or at a later point in time when you need thatvariable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
var name = "Ali";
var money;
money =2000.50;
</script>
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 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 itautomatically.
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.
Output:
This produces the following result –
local
JavaScript is a dynamic type language, means you don't need to specify type of the variable because
it is dynamically used by JavaScript engine. You need to use var here to specify the data type. It can
hold any type of values such as numbers, strings etc.
For example:
▪ vara=40; // holdingnumber
▪ varb="Rahul"; // holdingstring
There are five types of primitive data types in JavaScript. They are as follows:
Example:
var carName ="VolvoXC60"; // Using double quotes
var carName ='VolvoXC60'; // Using singlequotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example:
var answer = "It's alright"; // Single quote inside doublequotes
var answer = "He is called 'Johnny'"; // Single quotes inside doublequotes
var answer = 'He is called "Johnny"'; // Double quotes inside singlequotes
Example:
var x1 =34.00; // Written with decimals
var x2=34; // Written withoutdecimals
Extra-large or extra small numbers can be written with scientific (exponential) notation:
Example:
var y= 123e5; //12300000
var z= 123e-5; //0.00123
Example:
var x = true;
var y = false;
(iv) Undefined:
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.
Example:
var person; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
(v) EmptyValues
▪ An empty value has nothing to do withundefined.
▪ An empty string variable has both a value and atype.
Example:
var car= ""; // The value is "", the typeof is string
Example:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
The following code declares (creates) an array called cars, containing three items (car names):
Example:
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
Syntax:
/pattern/modifiers;
Example:
var patt = /w3schools/i
▪ /w3schools/i is a regularexpression.
▪ w3schools is a pattern (to be used in asearch).
▪ i is a modifier (modifies the search to becase-insensitive).
Conditional statements are used to perform different actions based on different conditions.
The if Statement:
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax:
if (condition)
{
block of code to be executed if the condition is true
}
Example:
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18)
{
greeting = "Good day";
}
Syntax:
if (condition)
{
block of code to be executed if the condition is true
}
else
{
block of code to be executed if the condition is false
}
Example:
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
Syntax:
if (condition1)
{
block of code to be executed if condition1 is true
}
else if (condition2)
{
block of code to be executed if the condition1 is false and condition2 is true
}
Example:
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a "Good evening": if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
Arithmetic Operators:
Arithmetic operators are used to perform arithmetic on numbers (literals or variables).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Comparison Operators:
JavaScript supports the following comparison operators.
Operator Description
== Equal
!= Not Equal
> Greater than
< Less than
>= Greater than or Equal to
<= Less than or Equal to
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Not
<< Left Shift
>> Right Shift
>>> Right shift with Zero
Assignment Operators:
JavaScript supports the following assignment operators.
Operator Description
= x=y
+= x+=y
-= x-=y
*= x *= y
/= x /= y
%= x %= y
Miscellaneous Operator:
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
Output:
((a > b) ? 100 : 200) =>200
((a < b) ? 100 : 200) =>100
typeof operator:
▪ The typeof operator is a unary operator that is placed before its single operand, which can
be of any type. Its value is a string indicating the data type of theoperand.
▪ The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on theevaluation.
▪ The list of the return values for the typeofOperator.
Output:
Result => B is String
Result => A is Numeric
String literals:
A string literal is zero or more characters, either enclosed in single quotation (') marks
or double quotation (") marks. You can also use + operator to join strings. The following are
the examples of string literals:
i. string1 ="w3resource.com"
ii. string1 ='w3resource.com'
iii. string1 ="1000"
iv. string1 = "google" +".com"
Inadditiontoordinarycharacters,youcanincludespecialcharactersinstrings,asshowninthe
followingtable.
string1 = "First line. \n Second line."
Character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\' Single quote
\" Double quote
\\Backslash character (\)
Array literals
In Javascript an array literal is a list of expressions, each of which represents an array
element, enclosed in a pair of square brackets ' [ ] '.
When an array is created using an array literal, it is initialized with the specified values as
its elements, and its length is set to the number of arguments specified. If no value is supplied it
creates an empty array with zerolength.
Integer literals:
An integer must have at least one digit (0-9).
▪ No comma or blanks are allowed within aninteger.
▪ It does not contain any fractionalpart.
▪ It can be either positive or negative, if no sign precedes it is assumed to bepositive.
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-
").
Example:
▪ 8.2935
▪ -14.72
▪ 12.4e3 [ Equivalent to 12.4 x 103]
▪ 4E-3 [ Equivalent to 4 x 10-3 => .004]
Object literals:
An object literal is zero or more pairs of comma separated list of property names and associated
values, enclosed by a pair of curly braces.
Syntax rules:
Object literals maintain the following syntax rules:
▪ There is a colon (:) between property name andvalue.
▪ A comma separates each property name/value from thenext.
▪ There will be no comma after the last property name/valuepair.
▪ A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modularcodes.
▪ Functions allow a programmer to divide a big program into a number of small and manageable
functions.
▪ A JavaScript function is a block of code designed to perform a particulartask.
▪ A JavaScript function is executed when "something" invokes it (callsit).
Function Invocation:
The code inside the function will execute when "something" invokes (calls) the function:
▪ When an event occurs (when a user clicks abutton)
▪ When it is invoked (called) from JavaScriptcode
▪ Automatically(self-invoked)
Function Return:
▪ When JavaScript reaches a return statement, the function will stopexecuting.
▪ Ifthefunctionwasinvokedfrom astatement,JavaScriptwill"return"toexecutethecodeafter the
invokingstatement.
▪ Functions often compute a return value. The return value is "returned" back to the"caller":
function myFunction(a, b) {
return a*b; // Function returns the product of a andb
}
Calling Function:
To invoke a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Output:
Click the following button to call the function
Example:
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then
try...</p> </body>
</html>
Output:
Click the following button to call the function
Function starts with the function keyword and code of the function is enclosed in {..} brackets.
Functions are written inside the head section of the html document, because function does not execute
when the page loads. The alert function displays the message "How are you", when you clicked on the
button ("Click Here").
The confirm() built-in function display the confirmation dialog box and
confirm()
ask the user to determine from the two option .
The focus() built -in function built the pointed object active and put the
focus()
curser on the text field.
The prompt() built -in function display the prompt dialog box.
prompt()
Inquiring the user for input.
select() The select() built -in function used to select the pointed object.
write() The write() built in function used to write something on the document.
Function arguments:
Through variable you can pass argument to function. The output of the function looks on the
arguments given by you.
Example:
<html>
<head>
<script language="javascript">
function myfunction(text)
{
confirm(text)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction('Do you want to delete it!')" value="Delete">
<input type="button" onclick="myfunction('Do you want to save it!')" value="Save">
</form>
</body>
</html>
Object Properties:
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Object Definition:
You define (and create) a JavaScript object with an object literal:
Example:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
Example:
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Syntax:
objectName.propertyName
(or)
objectName["propertyName"]
Example:
person.lastName;
person["lastName"];
Syntax:
objectName.methodName()
Example:
name = person.fullName();
Example:
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title> User-defined objects </title>
<script type="text/javascript">
var book =newObject(); // Create theobject
book.subject="Perl"; //Assignpropertiestotheobject
book.author ="Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output:
Book name is : Perl
Book author is : Mohtashim
Creating an Array:
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
Example:
var cars = new Array("Saab", "Volvo", "BMW");
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Examples:
var x=cars.length; // The length property returns the number of elements in cars
var y=cars.sort(); // The sort() method sort cars in alphabeticalorder
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruitsis
4
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) tofruits
New element can also be added to an array using the length property:
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length]="Lemon"; // adds a new element (Lemon) to fruits
Adding elements with high indexes can create undefined "holes" in anarray:
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[10]="Lemon"; // adds a new element (Lemon) tofruits
(i) MathObject:
▪ The Math object allows you to perform mathematicaltasks.
▪ The Math object includes several mathematicalmethods.
Example:
Math.min(0, 150, 30, 20,-8,-200); // returns-200
Method Description
abs(x) Returns the absolute value of x
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
Syntax:
var mystring = new String(“Hello World”);
Or
var mystring = “Hello World”;
Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified
value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified
value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and
returns the matches
replace() Searches a string for a specified value, or a regular expression, and
returns a new string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and
returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts the characters from a string, beginning at a specified start
position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
substring() Extracts the characters from a string, between two specified indices
Method Description
anchor() Creates an anchor
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fixed() Displays a string using a fixed-pitch font
fontcolor() Displays a string using a specified color
fontsize() Displays a string using a specified size
italics() Displays a string in italic
link() Displays a string as a hyperlink
small() Displays a string using a small font
strike() Displays a string with a strikethrough
sub() Displays a string as subscript text
sup() Displays a string as superscript text
(iii) Dateobject:
▪ JavaScript’s Date object provides methods for date and timemanipulations.
▪ Date objects are created with newDate().
▪ Date and time processing can be performed based on the computer’s local time zone or based on
World Time Standard’s Coordinated Universal Time (UTC) - formerly called Greenwich Mean
Time(GMT).
There are four ways of instantiating a date:
1. var d = newDate();
2. var d = new Date(milliseconds);
3. var d = new Date(dateString);
4. var d = new Date (year, month, day, hours, minutes, seconds,milliseconds);
Date Methods:
▪ When a Date object is created, a number of methods allow you to operate onit.
▪ Date methods allow you to get and set the year, month, day, hour, minute, second, and
millisecond of objects, using either local time or UTC (universal, or GMT)time.
Boolean Methods:
Method Description
toString() Converts a boolean value to a string, and returns the result
valueOf() Returns the primitive value of a boolean
(v) Numberobjects:
▪ JavaScript has only one type ofnumber.
▪ Numbers can be written with, or without,decimals:
Number Methods:
Method Description
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a number to a string
valueOf() Returns the primitive value of a number
(vi) Arrayobject:
The Array object is used to store multiple values in a single variable:
var cars = ["Saab", "Volvo", "BMW"];
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns it's position
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns it's position
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
Syntax:
var patt=new RegExp(pattern,modifiers);
(or)
var patt=/pattern/modifiers;
▪ pattern specifies the pattern of anexpression
▪ modifiers specify if a search should be global, case-sensitive,etc.
Modifiers:
Modifiers are used to perform case-insensitive and global searches:
Method Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multilinematching
Brackets:
Brackets are used to find a range of characters:
Method Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified
Method Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx
Quantifiers:
Method Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
Method Description
global Specifies if the "g" modifier is set
ignoreCase Specifies if the "i" modifier is set
lastIndex The index at which to start the next match
multiline Specifies if the "m" modifier is set
source The text of the RegExp pattern
Method Description
compile() Compiles a regular expression
exec() Tests for a match in a string. Returns the first match
test() Tests for a match in a string. Returns true or false
(viii) Documentobjects:
▪ When an HTML document is loaded into a web browser, it becomes a documentobject.
▪ The document object is the root node of the HTML document and the "owner" of all othernodes:
✓ elementnodes,
✓ textnodes,
✓ attributenodes,
✓ and commentnodes
▪ The document object provides properties and methods to access all node objects, from within
JavaScript.
Method Description
document.close() Closes the output stream previously opened with
document.open()
document.cookie Returns all name/value pairs of cookies in the document
document.domain Returns the domain name of the server that loaded the
document
document.getElementById() Returns the element that has the ID attribute with the
specified value
document.getElementsByName() Returns a NodeList containing all elements with a specified
name
document.getElementsByTagName() Returns a NodeList containing all elements with the specified
tag name
document.lastModified Returns the date and time the document was last modified
document.open() Opens an HTML output stream to collect output from
(ix) Windowobjects:
▪ The window object represents an open window in abrowser.
▪ If a document contain frames (<iframe> tags), the browser creates one window object for the
HTML document, and one additional window object for eachframe.
Method Description
alert() Displays an alert box with a message and an OK button
close() Closes the current window
blur() Removes focus from the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
setInterval() Calls a function or evaluates an expression at specified intervals (in milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of
milliseconds
stop() Stops the window from loading
JavaScript Debugging:
▪ A mistake in a program or a script is referred to as abug.
▪ The process of finding and fixing bugs is called debugging and is a normal part of the
developmentprocess.
▪ It is difficult to write JavaScript code without adebugger.
▪ It contains syntax errors, or logical errors, that are difficult todiagnose.
▪ When JavaScript code contains errors, nothing will happen. There are no error messages, and
you will get no indications where to search forerrors.
JavaScript Debuggers:
▪ Searching for errors in programming code is called codedebugging.
▪ Debugging is not easy. But fortunately, all modern browsers have a built-indebugger.
▪ Built-in debuggers can be turned on and off, forcing errors to be reported to theuser.
▪ With a debugger, you can also set breakpoints (places where code execution can be stopped),
and examine variables while the code isexecuting.
▪ Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your
browser with the F12 key, and select "Console" in the debuggermenu.
Example:
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b =6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Example:
<script>
var x = 15 * 5;
debugger;
document.write(x);
</script>
The most basic way to track down errors is by turning on error information in your browser. By
default, Internet Explorer shows an error icon in the status bar when an error occurs on the page.
Double-clicking this icon takes you to a dialog box showing information about the specific error that
occurred.
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show
the Error dialog box whenever an error occurs.
To enable this option, select Tools → Internet Options → Advanced tab. and then finally check
the "Display a Notification About Every Script Error" box option as shown below.
Chrome
✓ Open thebrowser.
✓ From the menu, selecttools.
✓ From tools, choose developertools.
✓ Finally, selectConsole.
Internet Explorer
✓ Open thebrowser.
✓ From the menu, selecttools.
✓ From tools, choose developertools.
✓ Finally, selectConsole.
Syntax:
var patt=new RegExp(pattern,modifiers);
or
var patt=/pattern/modifiers;
RegExp Modifiers:
i. Modifiers are used to perform case-insensitive and globalsearches.
ii. The i modifier is used to perform case-insensitivematching.
iii. The g modifier is used to perform a global match (find all matches rather than stopping after the
firstmatch).
Example 1:
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
The marked text below shows where the expression gets a match:
W3Schools
Example 2:
Do a global search for "is":
var str="Is this all there is?";
var patt1=/is/g;
The marked text below shows where the expression gets a match:
Is this all there is?
test ():
▪ The test () method searches a string for a specified value, and returns true or false, depending on
theresult.
The following example searches a string for the character "e":
Example:
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life arefree"));
Since there is an "e" in the string, the output of the code above willbe:
true
exec():
▪ The exec() method searches a string for a specified value, and returns the text of the found value.
If no match is found, it returnsnull.
Example:
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");
function search1()
{
var str1 = document.getElementById("string1").value;
var str2 = document.getElementById("string2").value;
var len = str1.length;
var count=0;
var search = str1.indexOf(str2);
for(i=0;i<len;i++)
{
if(parseInt(search)!= -1)
{
count++;
var search = str1.indexOf(str2,parseInt(search)+1);
}
}
document.getElementById("ans").value= str2 + " Occurs " + count + " times";
}
// -->
</script>
</head>
<body>
<table style="width:100%" border="0" cellpadding="0"
cellspacing="0"> <tr>
<td valign="top"> </td>
<h1> Count the No.of Occurrence using String Methods </h1> <p>
This is a program to determine the number of occurrences of the character in the text </p>
<form name = "search">
<table border = "1">
<caption> Search </caption>
<html>
<head>
<title> TO FIND SMALLEST AND LARGEST
</title> </head>
<script language="javascript">
document.write("<center> <h1> <font color=red> FINDING THE LARGEST AND THE
SMALLEST INTEGERS IN THE GROUP </font> </h1> </center>"); var no,no1;
var count=0,large=0,small=999999;
while(count<5)
{
no=prompt(" Enter the First Five numbers ","");
no1=parseInt(no);
document.writeln("<center> <h3><font color=blue> Number " + count + " = " +
no1 + " </font> </h3> </center> <br>");
if(no1>large)
large=no1;
if(no1<small)
small=no1;
count++;
}
document.writeln("<center><h2><font color=red> The Largest Number is=" + large + "
</font> </h2></center> <br>");
document.writeln("<center><h2><font color=green> The Smallest Number =" + small + "
</font> </h2></center>");
</script>
<body>
</body>
</html>
Output:
<html>
<head>
<title> AREA OF CIRCLE </title>
<script language="javascript">
function doArea()
{
var radius,result;
radius=window.prompt("Enter the radius of a
circle",""); result= (3.14 *radius*radius); alert("The Area
of a circle is "+result);
}
</script>
</head>
<body>
<center>
<form>
<h1>Calculating radius of the circle</h1>
<h3>find the area of circle below and give a clap now</h3>
<input type="button" name="findarea" value="circle area" onClick="doArea()">
</form>
<center>
</body>
</html>
2 MARKS
1. List out the different functions of Web Browser? (APR 2016) (Ref.Qn.No.15,Pg.no.7)
2. State the uses of IP? (APR 2016) (Ref.Qn.No.9,Pg.no.6)
3. How to create Arrays in Java Script? (APR 2016) (Ref.Qn.No.69,Pg.no.21)
4. What is SMTP? Mention any one use of it. (NOV 2016) (Ref.Qn.No.35,Pg.no.13)
5. Define literal in Java script. Give an example. (NOV 2016) (Ref.Qn.No.64,Pg.no.20)
6. Name the elements of WWW. (APR 2016) (Ref.Qn.No.19,Pg.no.8)
7. State the purpose of IMAP and MIME protocol. (APR 2017) (Ref.Qn.No.37&39,Pg.no.13&14)
8. Define Java script statement and give an example. (APR 2017) (Ref.Qn.No.60,Pg.no.19)
9. Mention array creation in Java script with example. (APR 2017) (Ref.Qn.No.69,Pg.no.21)
10. Define “Markup Language”. (NOV 2017) (Ref.Qn.No.77,Pg.no.23)
11. Write short notes on MIME. (NOV 2017) (Ref.Qn.No.37,Pg.no.13)
11 MARKS