Web Tech PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 148

CHRIST COLLEGE OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Subject Name:WEBTECHNOLOGY Subject Code: CST63

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.

2. Define web site and webpage?


A website is a set of related web pages that are addressed with a common domain name or IP
address. A website is hosted on a machine called web server, which should be accessible via a
network.
The web pages of a web site are accessed using URLs (Uniform Resource Locator). The web pages are
organized into a hierarchy. They contain hyperlinks that guide the visitors navigating the website.

3. What is meant by webapplications?


Web applications are applications that are accessed via web browsers usually through networks. Web
applications run on a server called web server. Each web applications is identified by a Uniform
Resource Locator.

4. List types of webapplications?


There are two types of web applications are
▪ Service oriented webapplication
▪ Presentation oriented webapplication

5. What is a service-oriented webapplication?


The service-oriented web applications implement web services and are typically coded using server-
side technologies such as CGI, JSP, ASP, etc.

6. What is a presentation-oriented webapplication?


The presentation-oriented web applications are usually clients of service-oriented applications. They
are coded in browser supported languages such as HTML, XML, JavaScript, etc. These applications
generate interactive web pages.

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.

8. What is meant by IPAddress?


Internet Protocol in the TCP/IP protocol suite assigns a unique address called Internet Protocol
(IP) Address to each device participating in a computer network.

9. State the usesofIP? (APR2016)


The used of Internet Protocol address
▪ Identifying a host/networkinterface
▪ Addressing
▪ Routing
▪ DataEncapsulation
▪ Formatting/Packaging
▪ Fragmentationand
▪ Re-Assembly

10. Define proxyservers?


Proxy servers are related to firewalls prevents hosts on a network from making direct connections to
the outside world; a proxy server can act as a go-between. Thus a machine that is prevented from
connecting to the external network by a firewall would make a request for a web page from the local
proxy server instead of requesting the web page directly from the remote web server.

11. List the types of Internetservers?


▪ Mailservers
▪ Webservers
▪ FTPservers
▪ News server
▪ DNSservers

12. What is meant by webserver?


Collection of web pages is stored in a computer for publishing is called web server. Any computer can
act as a web server if it is connected to the network. ISP (Internet Service Protocol) is used to connect
a system to network.

13. What are types of webserver?


▪ Applicationserver
▪ E-mailserver
▪ Database server
14. What is meant by web browser? List out anyfour?

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.

15. List out the different functions ofWebBrowser? (APR2016)


▪ Web browser functions are to provide the resources or information to the user when asked by
them.
▪ It processes the user inputs in the form of URL like http://www.google.com in the browser and
allows the access to thatpage.
▪ URL is used to identify the resources and fetch them from the server and displays it to theclient.
▪ It allows the user to interact with the web pages and dynamic content like surveys, forms,etc.
▪ Italsoallowstheusertonavigatethroughthecompletewebpageandseeitssourcecodeinthe
HTMLformat.
▪ It provides security to the data and the resources that are available on the web that is by using
the securemethods.

16. What is meant by webhosting?


A web hosting is a type of Internet hosting service that allows individuals and organizations to make
their own website accessible via the World Wide Web. Web hosts are companies that provide space
on a server they own or lease for use by their clients as well as providing Internet connectivity,
typically in a datacenter.

17. List out the services provided by theInternet?


▪ Electronic Mail
▪ World WideWeb
▪ FTP
▪ Telnet
▪ Gopher andChat

18. What do you mean by World Wide Web(WWW)?


World Wide Web (WWW) is a distributed system of inter linked pages that include text, pictures,
sound and other information. It enables easy access to the information available on the internet.
WWW is a repository of information (called resource) distributed all over the world, is defined as a
world-wide networks of networks.
19. Name the elementsof WWW? (APR2016)
▪ Client &server
▪ Web languages &protocols
▪ Webpages
▪ Home page
▪ Web browsers and Websites

20. What is meant byHTML?


▪ HTML stands for Hyper Text MarkupLanguage.
▪ It is a markup language for describing web documents (webpages).
▪ A markup language is a set of markuptags.
▪ HTML documents are described by HTMLtags.
▪ Each HTML tag describes different documentcontent.

21. Write the format of htmlprogram?


<HTML>
<HEAD>
<TITLE> This is the Title </TITLE>
</HEAD>
<BODY>
Type the body of the program
</BODY>
</HTML>

22. How do you make a graphic alink?


<A HREF="http://www.snowhawk.com/wildlife.html"> <IMG SRC="leopard.jpg" WIDTH="25"
HEIGHT="25" ALIGN="top" BORDER="0" ALT="link to wildlife"> </A>

23. Mention some text formatting tags?


▪ <p> </p> - is used for introducing variousparagraphs.
▪ <br> - this tag is used for giving an empty blankline.
▪ HEADING TAGS - <h1> </h1> ….. <h6> </h6> is used to introduce variousheadings.
▪ <h1> is the biggest and h6 is the smallest headingtag.
▪ <HR> TAG – is used to draw lines and horizontalrules.
▪ <B>, <I>, <U> for bold, italic and underlinerespectively.
24. Explain about list tag?
Types ofLists
1. Unorderedlists
2. Orderedlists

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>

Attributes of table tag:


▪ ALIGN Horizontal alignment is controlled by the ALIGN attribute. It can be set to LEFT, CENTER,
or RIGHT VALIGN Controls the vertical alignment of cell contents. It accepts the values TOP,
MIDDLE or BOTTOM WIDTH Sets the WIDTH of a specific number of pixels or to a percentage of
the available screenwidth.
▪ BORDER - controls the border to be placed around thetable.
▪ CELLPADING - This attribute controls the distance between the data in a cell and the boundaries
of thecell
▪ CELLSPACING- Controls the spacing between adjacentcells.
▪ COLSPAN- Used to spilt the single cell to one or morecolumns.
▪ ROWSPAN- Used to spilt the single cell to one or morerows.
▪ ALIGN: ALIGN = TOP, MIDDLE, ANDBOTTOM.
▪ BORDER: Specifies the size of the border to place around theimage.
▪ WIDTH: Specifies the width of the image inpixels.
▪ HEIGHT: Specifies the height of the image inpixels
▪ HSPACE: Indicates the amount of space to the left and right of theimage
▪ VSPACE: Indicates the amount of apace to the top and bottom of theimage.

26. Mention the different types of links?


HTML allows linking to other HTML documents as well as images. There are 3 attributes that can be
introduced in BODY tag.
a) LINK – Changes the default color of a Hyperlink to whatever color is specified with thistag.
b) ALINK – Changes the default color of a hyperlink that is activated to whatever color is specified
with this tag.
c) VLINK – Changes the default color of a hyperlink that is already visited to whatever color is
specified with thistag.
Note: User can specify the color name of a hyperlink or an equivalent hexadecimal number.
27. Explain image maps with itssyntax?
When a hyperlink is created on an image, clicking on any part of the image will lead to opening of the
document specified in the <A HREF TAG>.
Linked regions of an image map are called hot regions and each hot region is associated with a
filename.html.

Syntax:
<MAP NAME = “map name”>

Attributes of Image Maps:


▪ COORDS: Each of the above shapes takes different coordinates asparameters.
▪ Rectangle – 4 coordinates (x1, y2, x3,y2)
▪ POLYGON: 3 or morecoordinates.
▪ HREF – Takes the name of the .html file that s linked to the particular area on theimage.
<MAP NAME = “fish.jpg”>
<AREA SHAPE = “rect” COORDS = “52, 65, 122, 89” HREF = “sct.html”>
</MAP>

28. Explain about Html form tag with itsattributes?


HTML form provides several mechanisms to collect information from people viewing your
site. The syntax of the form is
<FORM METHOD = “GET|POST” ACTION = “filename”>
▪ The METHOD attribute indicates the way the web server will organize and send you the form
output.
▪ Use METHOD = “post” in a form that causes changes to server data, for example when updatinga
database.
▪ The ACTION attribute in the FORM tag is the path to this script; in this case, it is a common script
which emails form data to an address. Most Internet Service Providers will have a script like this
on theirsite.

29. Mention the various Formelements?


The various elements or controls can be created in FORM using <INPUT> tag. They are
▪ Label
▪ Textbox
▪ TextArea
▪ Radiobutton
▪ Checkbox
▪ Listbox
▪ Commandbutton
▪ Scrollbars
30. What is the use of frames in html give the syntax ofFrames?
Frames are used to call many html files at the same time. This can be done using <FRAMESET>
</FRAMESET> tags.

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>

31. What are the different types of HTMLprotocols?


The different types of HTML protocols are
➢ Hyper Text Transfer Protocol(HTTP)
➢ Simple Mail Transfer Protocol(SMTP)
➢ Post Office Protocol Version 3(POP3)
➢ Multi-Purpose Mail Extension(MIME)
➢ Internet Message Access Protocol(IMAP)

32. What is meant byHTTP?


HTTP (Hyper Text Transfer Protocol) is an application layer protocol in the TCP/IP protocol suite.
HTTP was originally developed to transfer files and data in distributed, collaborative, hypermedia
information systems.
The primary purpose of HTTP is to transfer web pages from one computer (web server) to another
computer (web client). The basic idea of the protocol is that a browser will request a page from a
server.
33. What are the elements of HTTP URL? The
four elements of a URL specificationare
1) Method(Protocol)
2) Host (Local hostname or IPaddress)
3) Port (Port number for contactingserver)
4) Path (Path name of the resourcefile)

34. List the steps functions of HTTPprotocol?


HTTP is a standard protocol for communication between the web browsers and the web servers. It is
a stateless protocol that specifies
1) how a client and a server establish aconnection,
2) how the client request data to theserver,
3) how the server responds to the clientand
4) finally how the connection isclosed.

35. What is SMTP? Mention any one useofit. (NOV2016)


The TCP/IP protocol that supports electronic mail on the internet is called the Simple Mail Transfer
Protocol (SMTP). SMTP is the protocol used by mail servers to exchange email messages. It is a
system for sending messages to other computer users based on e-mail addresses.

1. Sending a single message to one or morerecipients.


2. Sending messages that include text, audio, video format or graphicsfile.
3. Sending messages to users on networks outside theinternet.

36. What isPOP3?


POP3 stands for Post Office Protocol Version3. It is used to retrieve e-mail from Internet
mailboxes. Mail access starts with the client when the user needs to download e-mail from the
mailbox on the mail server. It then sends its user name and password to access the mailbox. The user
can then list and retrieve the mail messages, one byone.

37. What is the useofMIME? (APR, NOV 2017)


Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format
ofemail tosupport:
Text in character sets other than ASCII.
▪ Non-text attachments: audio, video, images, application programsetc.
▪ Message bodies with multipleparts.
▪ Header information in non-ASCII charactersets.
38. List the predefined MIME contenttypes?
The predefined MIME content types are
▪ Text
▪ Multipart
▪ Message
▪ Image
▪ Audio
▪ Video
▪ Model
▪ Application

39. DefineIMAP? (APR2017)


The Internet Message Access Protocol (IMAP) is an Internet standardprotocolused by e-
mailclientsto retrieve e-mailmessages from a mail serverover a TCP/IPconnection. IMAP is used to
access the messages in email that are in mail server. It also used for manipulation of stored messages
on server.

40. What is meant byDNS?


Domain Name System (DNS) is an application level protocol for message exchange between client
andserver.
DNS is a hierarchical naming system for computer services for any resources connected to internet
or private network. The important work of DNS protocol is to convert the computer host name into
IPaddress.
DNS is a system for naming computers and network services that is organized into a hierarchy of
domains. DNS naming is used in TCP/IP networks, such as the Internet, to locate computers and
services through user-friendly names.

41. What are the properties of


DNS? The properties of DNSare:
▪ Each label in the domain can contain up to 63characters.
▪ The full domain name should not exceed the length of 253characters.
▪ The domain name should follow ‘LDH’rule.

42. What is DomainName?


Each host computer on the Internet has a unique number called IP address. And also have a name
know as host name. The name of each host computer consists of a series of words separated by dots.
43. What are domain & mention different types of domains?
Domain is a place where information is available. Domain name extensions are
▪ .edu – Servers that provide Educationalservices
▪ .gov – About the government of acountry.
▪ .mil – Servers that provide militaryinformation.
▪ .org – Provide information about the organizations in theworld.
▪ .com – Servers providing commercial services on theInternet.

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”.

45. What is meant byCSS?


▪ CSS stands for Cascading StyleSheets.
▪ CSS is a style sheet language that describes the presentation of an HTML (or
XML)document.
▪ It describes how HTML elements are to be displayed on screen, paper, or in othermedia.
▪ CSSsaves alotofwork.Itcancontrolthelayoutofmultiplewebpages
allatonceExternalstyle sheets are stored in CSSfiles.

46. What is the syntax ofCSS?


A CSS rule set consists of a selector and a declaration block:
selector { property1: value1; property2: value2;}
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.

47. List the features ofCSS?


The various features of CSS are
▪ Selectors
▪ BoxModel
▪ Backgrounds andBorders
▪ Image Values and ReplacedContent
▪ TextEffects
▪ 2D/3DTransformations
▪ Animations
▪ Multiple ColumnLayout
▪ UserInterface

48. What is meant by selectors inCSS?


▪ 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, universal, descendant, and childselectors.

49. What is meant by id selector inCSS?


▪ 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 theelement.
▪ The style rule below will be applied to the HTML element withid="para1":

Example:
#para1 {
text-align: center;
color: red;
}

50. What is meant by class selector inCSS?


▪ The class selector selects elements with a specific classattribute.
▪ To select elements with a specific class, write a period character, followed by the name of the
class:

Example:
All HTML elements with class="center" will be red and center-aligned:
.center {
text-align:center;
color:red;
}

51. What is meant by grouping selector inCSS?


▪ In CSS, you can group the selectors, to minimize thecode.
▪ To group selectors, separate each selector with acomma.
Example:
h1, h2, p {
text-align: center;
color: red;
}
52. Explain the various attributes inCSS?
It is possible to style HTML elements that have specific attributes or attribute values.
1. The [attribute]selector is used to select elements with a specified attribute.
The following example selects all <a> elements with a targetattribute:
a[target] { background-
color: yellow;
}

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

54. What is client sideprogramming?


Client side programming has mostly to do with the user interface, with which the user interacts.
In web development it's the browser, in the user's machine, that runs the code, and it's mainly done
in JavaScript, flash, etc. This code must run in a variety of browsers. The examples are JavaScript,
VBScript, HTML, andCSS.

55. What is meant byJavaScript?


▪ JavaScript is an object-oriented programming language commonly used to create interactive
effects within webbrowsers.
▪ JavaScript is the programming language of HTML and theWeb.
▪ JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications.
▪ It is open andcross-platform.
▪ JavaScript inserted into HTML pages, can be executed by all modern webbrowsers.

56. Write the syntax of JavaScriptprogram?


JavaScript code may be placed anywhere in an HTML file. It is interpreted in the order in which it
appears.
<html>
<head>
<script language = “JavaScript” (or)
language=”text/JavaScript”> //function declaration
</script>
</head>
<body>
<script language = “JavaScript”>
//function call //other JavaScript statements
</script>
</body>
</html>

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;

58. What are local and global variables inJavaScript?


▪ A variable can be a local orglobal.
▪ A local variable is declared in a function using the keywordvar.
▪ Variables declared without the var keyword is alwaysglobal.

59. List the various data types inJavaScript?


JavaScript variables support the following data types:
▪ String,
▪ Number,
▪ Boolean,
▪ Arrayand
▪ Object.

60. Define Java script statement and giveanexample. (APR2017)


▪ In HTML, JavaScript statements are "instructions" to be "executed" by the webbrowser.
▪ This statement tells the browser to write "Hello Dolly." inside an HTML element
withid="demo":

Example:
document.getElementById("demo").innerHTML = "Hello Dolly.";

61. List the various conditional Statements inJavaScript?


Conditional statements are used to perform different actions based on different conditions.
i. ifstatement
ii. elsestatement
iii. else ifstatement
iv. switchstatement

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

63. List the types of JavaScriptliterals?


The various JavaScript literalsare
▪ Stringliterals
▪ Arrayliterals
▪ Integerliterals
▪ Floating pointingliterals
▪ Booleanliterals
▪ Objectliterals

64. Define literal in Java script. Givean example. (NOV2016)


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 zero length.

Example:
Creating an array with four elements.
var fruits = ["Orange", "Apple", "Banana", "Mango"]

65. Explain the functions inJavaScript?


▪ A JavaScript function is a block of code designed to perform a particulartask.
▪ A JavaScript function is executed when "something" invokes it (callsit).
▪ A JavaScript function is defined with the function keyword, followed by a name, followed by
Parentheses().

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).

67. What is meant by JavaScriptobjects?


▪ An object is a collection of related properties andmethods.
▪ JavaScript objects are different from C++/Javaobjects.
▪ The properties and methods can be added at any time even after the creation of anobject.

68. How to access properties and methods in


JavaScript? Accessing ObjectProperties:
You can access object properties in two ways:
objectName.propertyName
(or)
objectName["propertyName"]

Accessing Object Methods:


You access an object method with the following
syntax: objectName.methodName()

69. What is a JavaScriptarray?


An array is a special variable, which can hold more than one value at a time. In
Javascript array may contain heterogeneous items. These arrays are similar to structure
variables, except that they can be accessed randomly with the array name and the index.

70. How to create an arrayin JavaScript? (APR 2016,2017)


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"];

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:

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

72. What is meant by JavaScriptDebugging?


▪ Searching for errors in programming code is called codedebugging.
▪ It is difficult to write JavaScript code without adebugger.
▪ Your code might contain syntax errors, or logical errors, that are difficult todiagnose.
▪ Often, when JavaScript code contains errors, nothing will happen. There are no error messages,
and you will get no indications where to search forerrors.

73. What is meant by JavaScriptDebuggers?


▪ 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.

74. What is regular expression inJavaScript?


▪ A regular expression is a sequence of characters that forms a searchpattern.
▪ When you search for data in a text, you can use this search pattern to describe what you are
searchingfor.
▪ A regular expression can be a single character, or a more complicatedpattern.
▪ Regular expressions can be used to perform all types of text search and text replaceoperations.

75. Write the syntax for regular expression?


Syntax:
/pattern/modifiers;

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).

76. What are the methods in regularexpression?


▪ In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
1. The search() method uses an expression to search for a match, and returns the position of the
match.
2. The replace() method returns a modified string where the pattern isreplaced.

77. Define“MarkupLanguage”. (NOV2017)


Markup languages are designed for the processing, definition and presentation of text. The language
specifies code for formatting, both the layout and style, within a text file. The code used to specify
the formatting are called tags. HTML is an example of a widely known and used markup language.

P a g e | 23WEB TECHNOLOGY
11 MARKS

1. Explain the basic conceptsinInternet? (5MARKS)

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

LAN R WAN R LAN

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

2.Explain the historyofInternet? (6 MARKS)

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.

Goals for ARPANET:


▪ The Primary goal of ARPANET is to allow multiple users to send and receive information
simultaneously over the same communication paths (e.g., Phonelines).
▪ The network operated with a technique called packet switching, in which digital data was sent in
small bundles calledpackets.
▪ The packets contained address, error control and sequencinginformation.
▪ The address information allowed packets to be routed to theirdestination.
▪ The sequencing information helped in reassembling thepackets;
▪ Packets from different senders were intermixed on the samelines.
▪ This packet switching technique greatly reduced transmission costs, as compared with the cost
of the dedicated communicationlines.

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.

3. Write a short noteson WWW? (5 MARKS) (APR

2016)History of World WideWeb:


▪ The World Wide Web (WWW) allows computer users to locate and view multimedia – based
documents over the internet.
▪ In 1989, Tim Berners – Lee of CERN (The European organization for Nuclear Research) began to
develop a technology for sharing information via a hyperlinked textdocuments.
▪ Berners – Lee called his invention the Hyper Text MarkupLanguage(HTML).
▪ He also wrote communication protocols to form the backbone of his new information system,
which he called the World WideWeb.
▪ The Hyper Text Transfer protocol (HTTP) – a communication protocol used to send information
over theweb.
▪ Web use exploded with the availability in 1993 of the mosaic browser, which featured a user –
friendly graphicalinterface.
▪ Mark Andreesen, whose team at NCSA developed mosaic, went on to found Netscape with
initiating the explosive internet economy late1990’s.
▪ In September 1194, Berners-Lee founded the World Wide Web Consortium (W3c), which is the
well-known standard making for free software’s all over theworld.
▪ The WWW became commercially viable during 1996-98 when a large number of dot-com
companies used it for placing their services on theweb.
▪ In past, most computer applications run on computers that were not connected to one another,
whereas today’s applications can be written to communicate among the world’scomputers.

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.

4. Explain the various conceptsinHTML? (11MARKS)


▪ Hyper Text Markup Language (HTML) is a tag – based language and these tags are added to the
pages, there by instructing the web browser about the format in which the page has to be
displayed.
▪ The source code passed, the browser read web pages serially in the textformat.
▪ HTML was display static content like text, with user specificformatting.

Fundamental HTML elements:


▪ HTML tags are usually used inpairs.
▪ All tags are enclosed between the angle brackets (<>).
▪ The start tag is usually between angle brackets, while the end also has a forwarding slash
preceding the text (< />).
▪ The element content is everything between the start and the endtag.
▪ Most HTML elements can have theirattributes.
▪ HTML elements have emptycontent.
▪ Empty elements are closed in the starttag
▪ HTML tags are casesensitive.

The types of section are


1. Headsection
2. Bodysection

Elements for the head section:


The HTML tags
<HTML>
………
</HTML>
are the first and last tags in a page. All the content in HTML goes within these tags, which tell the
browser, or any other program reading that page that the file is a web page.

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>

Elements for the body section:


▪ The body tags <BODY> …. </BODY> contain the actual pagecontent.
▪ All page’s text, images, forms links and other HTML come in the bodyblock.
▪ The body tag has 3 commonly usedattributes
1. BGCOLOR
2. TEXT
3. LINK
▪ BGCOLOR specifies the background color for thepage.
▪ TEXT specifies the color of the text on thepage.
▪ LINK specifies the color of the hyperlink on thepage.

HTML named colors:


Color values are represented in either hexadecimal numbers or color names. User can specify only 16 by
names. It can specify any color by its hexadecimal values.
▪ White -#FFFFFF
▪ Yellow -#FFFF00
▪ Red -#FF00FF
▪ Green -#008000
▪ Blue -#0000FF
▪ Black -#000000
The default background, text and link colors for the web page are white, black and blue.

P a g e | 29WEB TECHNOLOGY
The various types of tags in HTML are

Comments in web pages:


▪ Comments make the web page code more readable and documentation iseased.
▪ Comments are enclosed within the comments tag <!- and --> and are simply ignored by the
browsers.
▪ Browsers simply interpret the comment begin tag and stop display until the end comment tag is
encountered.

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:
▪ &nbsp 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:

India is one of the developing country

Web Technology
Internet Programming

Welcome to web technology laboratory

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

P a g e | 32WEB TECHNOLOGY DEPARTMENT OF CSE


Definition List (DL) tag:
▪ Definition list are also commonly used to display information in the form of definitions which
have common use to convey information tousers.
▪ A definition has twoparts
1. A term(DT)
2. A definition(DD)
▪ Definition list tag <DL>……</DL> - create a definitionlist
▪ Within these tags, user can use the definition term tag <DT> - for each list itemterm.
▪ Definition data tag <DD> - for each list item’sdata.
▪ Both the <DT> and <DD> tag have no associated endtags.

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>

P a g e | 33WEB TECHNOLOGY DEPARTMENT OF CSE


Linking:
▪ The most important capability of the HTML is its ability to create hyperlinks to documents and
make the World Wide Web as a collection of linkeddocuments.
▪ The links are created using anchor <a>…..</a>element.
▪ <a href = “location ofthepage”> </a>
▪ It is used to hyperlink the webpage.
▪ <Img src = “s.jpg” width =”25” height = ”25” align=“top”> ……. </img>
▪ Thiselementrequiresanattributetomarkthelocationoftheobjecttogetlinked.Theaddressof the
object is specified using hrefattribute.
▪ The href attribute of the tag tells the browser to get another html document of theweb.

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>

Link will appear as


1. An unvisited link is underlined and blue incolor.
2. A visited link is underlined and purple incolor.
3. An active link is underlined and red incolor.

Output:

My favorite search sites

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

P a g e | 34WEB TECHNOLOGY DEPARTMENT OF CSE


Syntax:

To create name the following tag isused


<aname=”location”> </a>
▪ To refer to the locationuse
<a href = “#name”> text </a>

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

P a g e | 35WEB TECHNOLOGY DEPARTMENT OF CSE


Embedding Images:
▪ Images can be embedded into the web page. To add images as a background for the wholeweb
page, the following format isused,
<body background = “bg.gif”>
▪ To include the image as a normal figure in the web page the <img> tag isused.
▪ The image tag has the followingattributes
✓ src
✓ height
✓ width
✓ border
✓ align
✓ alt
▪ The src attribute is used to specify the location of the image, height and width, specify thesize.
▪ alt attribute which is provided for browsers that have images turned off or that cannot have
images.
▪ The value of alt attribute will appear on screen in the place of theimages.

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.

P a g e | 36WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
<frameset rows = “value” cols = “value”>
▪ The attribute rows – The window is to be divided in horizontalstripes.
▪ The attribute cols – The window is to be divided in verticalstripes.

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>

VerticalFrames(Cols) Horizontal frames(Rows)

Other tags:
▪ &amp – 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”>

P a g e | 37WEB TECHNOLOGY DEPARTMENT OF CSE


Tables:
▪ This form tag is the HTMLs best way of arranging information in space and controllinglayout
▪ Table element to format atable
▪ The various tag in tableas
<table>……</table>
align = left, center, right
border = make a border around the table & its cells
1. The <tr> element (table row) inserts a row in thetable.
2. The <td> element (table detail) inserts a cell within arow
3. The <th> element (table header) to add headings to the rows and columns of thetable.

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>

P a g e | 38WEB TECHNOLOGY DEPARTMENT OF CSE


<tr>
<td> apples</th>
<td> celery</th>
</tr>
<tr>
<td> oranges</th>
<td> carrots</th>
</tr>
</table>

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>

P a g e | 39WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
<table border = “2”>
<tr>
<th rowspan = 3> Tic Tac Games </th>
</tr>
<tr>
<td> X</td>
<td> O</td>
<td> X</td>
</tr>
</table>
▪ The bgcolor = attribute sets the color used to fill the background of the cell before text and images
are drawn.
▪ The border color = attribute sets the color of the borders drawn around the table, row orcell.

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>

Control spacing within a table:


▪ Cellspacing attribute determines the amount of space between two adjacent cells or between a side
of a cell and border of thetable.
▪ Cellpadding determines the amount of space between the content of cell and edge of thecell.

P a g e | 40WEB TECHNOLOGY DEPARTMENT OF CSE


5. Explain HTML forms in detail along with form elements, attributes and methods and Write an
HTML document to provide a form that collect name and telephone numbers. (11 MARKS) (APR
2016, 2017)

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.

HTML FORM ELEMENTS:

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>

P a g e | 41WEB TECHNOLOGY DEPARTMENT OF CSE


The output is
First name: SMVEC
Last name:
IFET

▪ The default width of a text field is 20characters.

2. PasswordField:
<input type=”password”> defines a password field.

Example:
<form>
Password: <input type=”password” name=”pwd”>
</form>

The output will be displayed as


Password:

*******
▪ 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>

P a g e | 42WEB TECHNOLOGY DEPARTMENT OF CSE


The output is
Bike
Car

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>

How the HTML code above looks in a browser:

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

Text Area Element:


▪ This tag sets up a multiple line input textwindow.

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.

P a g e | 43WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
Give the comments here <br>
<textarea name=”comments” rows=10 cols=20>
</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:

P a g e | 44WEB TECHNOLOGY DEPARTMENT OF CSE


Button Element:
▪ The <button> element defines a clickablebutton:

Example:
<button type="button" onclick="alert('Hello World!')"> Click Me! </button>

Output:

Click Me!

HTML FORM ATTRIBUTES:


The form tag can be used in the HTML code.
<form name=”form_name” action=” filename“ accept-charset="ISO-8859-1 method=”get|post”
target=”_response_frame”>
</form>

ATTRIBUTE VALUE DESCRIPTION


Specifies the character encodings that are to be used for the form
accept-charset character_set
submission
action URL Specifies where to send the form-data when a form is submitted
get
method Specifies the HTTP method to use when sending form-data
post
name text Specifies the name of a form
_blank
_self Specifies where to display the response that is received after
target
_parent submitting the form
_top

HTML FORM METHODS:


▪ The form tag can be used in the HTMLcode.
<form name=”form_name” action=” filename “accept-charset="ISO-8859-1 method=”get|post”
target=”_response_frame”>
</form>

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").

P a g e | 45WEB TECHNOLOGY DEPARTMENT OF CSE


GET Method:
▪ Appends form-data into the URL in name/valuepairs.
▪ The length of a URL is limited (about 3000characters).
▪ Never use GET to send sensitive data! (will be visible in theURL).
▪ Useful for form submissions where a user want to bookmark theresult.
▪ GET is better for non-secure data, like query strings inGoogle.

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>

P a g e | 46WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

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>

P a g e | 47WEB TECHNOLOGY DEPARTMENT OF CSE


Give the comments here <br>
<textarea name="comments" rows=10 cols=20> </textarea>
<input type="button" value="check" OnClick="validate()"><br>
<input type="submit" value="login" OnClick="submit()">
<input type="reset" value="clear"
OnClick="clear"> </form>
</body>
</html>

Output:

P a g e | 48 WEB TECHNOLOGY DEPARTMENT OF CSE


6. Explain theInternetProtocols? (4MARKS)
▪ A protocol is a set of rules or an agreement that specifies a common language that computer on a
network use for communication with othercomputers.
▪ Itspecifiestheconditionsunderwhichaparticularmessageshouldbesentorrespondandthe
particular method of doingit.
▪ It specifies on how the computer talk with eachother.
▪ The various protocolsare
✓ Hyper Text Transfer Protocol(HTTP)
✓ Simple Mail Transfer Protocol(SMTP)
✓ Post Office Protocol Version 3(POP3)
✓ Multipurpose Internet Mail Extension(MIME)
✓ File Transfer Protocol(FTP)
✓ Internet Protocol(IP)
✓ Transport Control Message(TCP)
✓ Internet Message Access Protocol(IMAP)

7. Explain brieflyaboutHTTP? (11MARKS)


▪ Hyper Text Transfer Protocol (HTTP) is a communication protocol used to send information over
theweb.
▪ HTTP protocol is used by the World Wide Web(WWW).
▪ HTTP defines how messages are formatted and transmitted and what actions web servers and
browsers should in response to variouscommands.
▪ Example:WhenyouenteraURLinyourbrowser,this actuallysends anHTTPcommandtothe web
server directing it to fetch and transmit the requested webpage.
▪ It is a standard protocol for communication between the web browsers and the webservers.
▪ Itis astatelessprotocolthatspecifieshowaclientandaserverestablishaconnection,howthe client
request data to the server, how the server responds to the client and finally how the
connection isclosed.
▪ Sending a request in the form of ACSII string and expects a reply(ASCII).

The basic structures of HTTP communications are:


1. RequestModel
2. ResponseModel

P a g e | 49WEB TECHNOLOGY DEPARTMENT OF CSE


Figure: Request-Response Model
1. HTTP RequestMessage:
▪ A client sends an HTTP request to serverby
✓ Clicking a link on the webpage
✓ Submitting aform
✓ Typing a web page address in the browser’s addressfield
▪ The browser uses the URL (Uniform Resource Locator) to create the requestmessage.

Figure: HTTP Request Message

The HTTP request message consists of


▪ Request / startline
▪ Request header / headerfield
▪ Blankline
▪ Request / message body(optional)

P a g e | 50WEB TECHNOLOGY DEPARTMENT OF CSE


a. Start Line / Request Line
It consists of 3 parts
i. Request Method (Example:GET)
ii. Request URI Portion of WebAddress
iii. HTTP Version (Example:HTTP/1.1)

Sample Request / Start Line

“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.

ii. A Resource Identifier (RequestURI)


▪ Uniform Resource Identifier (URI) is a string of characters used to identify a name or a resource
on theinternet.
▪ Such identification enables interaction with representations of the resource over a network
(WWW) using a specificprotocols.
▪ URI are composed of alpha-numeric names (punctuation characters are permitted) delimited by
the character“/”.
▪ URL(UniformResourceLocator)isusedforspecifyinganykindofinformationavailableonthe
internet.

P a g e | 51WEB TECHNOLOGY DEPARTMENT OF CSE


The four elements of a URL specification are
▪ Method(Protocol)
▪ Host (Local hostname or IPaddress)
▪ Port (Port number for contactingserver)
▪ Path (Pathname of the resourcefile)

URL
Format:E
xample:
Method: //host: port/path/filename
http://www.google.com:80/icuse/cs336/syllabus.pdf

iii. HTTP VersionIdentifier


▪ It specifies the version of the HTTP that the clientunderstands.
▪ The string starts with the prefix HTTP / and is followed by a versionnumber.
▪ Example:HTTP/1.1

Example of HTTP Request


▪ <method> <Request-URI><HTTP-Version>
▪ <Request options> CRLF →Request line & header must all end with<CR><LF>
▪ Get/foobar/indexHTTP/1.1
▪ GET/mypage.html HTTP/1.1CRLF
▪ Host: www.example.comCRLF
▪ HEAD/ HTTP/1.1
▪ POST/www.yahoomail.com/signup?=name=......&address=....... HTTP/1.1
▪ HTTPheadercontainstheadditionalinformationabouttheclientortherequestthatthe
server may provide aresponse.

The predefined fields are

Field Name Field Value


User agent Internet Explorer browser
From foobar@cs.man.edu
Referrer http://....
Accept */*
Cookie favourite

P a g e | 52 WEB TECHNOLOGY DEPARTMENT OF CSE


2. HTTP ResponseMessage:
▪ A server response is followed by a blank, status line and text of the requestedpage.

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.

P a g e | 53WEB TECHNOLOGY DEPARTMENT OF CSE


Status Code:

The status codes returned by the server are:

1xx Informational Request received, continuing process


2xx Success The action was successfully
200 OK Received, understood and accepted
201 Created
202 Accepted
204 No content
3xx Redirection Further action must be taken in order to complete
301 The request
304 Move permanently
4xx Client error The request contains bad syntax or cannot be fulfilled
400 Bad request
401 Unauthorized
402 Payment Required
404 Not found
410 Gone
5xx Server Error The server failed to fulfill the valid request
500 Internal server error
503 Service not available

8. What are variouse-mailProtocols? (2MARKS)


▪ The e-mail (electronic mail) protocols are very popular web based e-mailsystem.
▪ The various typesare
i. SMTP
ii. POP3
iii. IMAP
iv. MIME

P a g e | 54WEB TECHNOLOGY DEPARTMENT OF CSE


9. Explain in detailaboutSMTP? (11MARKS) (NOV 2016) (APR2017)
▪ The TCP/IP protocol that supports electronic mail on the internet is called the Simple Mail
Transfer Protocol(SMTP).
▪ SMTP is the protocol used by mail servers to exchange emailmessages.
▪ It is a system for sending messages to other computer users based on e-mailaddresses.

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.

Fig: SMTP Concept


SMTP client and server has 2 components
a) User Agent(UA)
b) Mail Transfer Agent(MTA)
▪ The UA prepares the message, create the envelope and puts the message in theenvelope.
▪ The MTA transfers the mail across theinternet.

Fig: UA and MTA

P a g e | 55WEBTECHNOLOGY DEPARTMENT OFCSE


▪ A mail gateway which is a relay MTA that can receive mail prepared by a protocol other than
SMTP and transform it to SMTP format before sendingit.
▪ It can also receive mail in SMTP format and change it to another format before sendingit.

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

Address of the mailbox The domain name of the


on the local site destination

P a g e | 56WEB TECHNOLOGY DEPARTMENT OF CSE


Local Part
▪ The local part defines the name of a special file called the user mailbox, where all of the mail
received for a user is stored for retrieval by the useragent.

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

2. Mail Transfer Agent(MTA):

▪ The actual mail transfer is done through mail transfer agent(MTA).


▪ To send mail, a system must have a client MTA and to receive mail, a system must have a
server MTA.
▪ Client sends command and server responds with command statusmessage.
▪ Status messages include ASCII encoded numeric status code and textstring.

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.

The major SMTP request commands are


Commands Descriptions
HELO Establishes SMTP connection, identify the sender (client).
MAIL FROM e-mail address of the sender.
RCPT TO e-mail address of the recipients.
BODY Body of the mail.
Sender ready to transmit a series of lines of text, each ends with \r\n.
DATA
A line containing only a period ‘.’ Indicates the end of the data.
VRFY Verify that an e-mail address is valid.
EXPN Expands an alias (group e-mail address).
RSET Aborts current transaction.

P a g e | 57WEB TECHNOLOGY DEPARTMENT OF CSE


SOML Send or mail (if recipient is logged in, display message on terminal, otherwise E-mail).
SAML Send and mail (delivers mail data to one or more terminals or mailboxes).

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

P a g e | 58WEB TECHNOLOGY DEPARTMENT OF CSE


SMTP Replies:

▪ SMTP reply code has specialsignificance.


ReplyCode Description
211 Systemstatus
214 Helpmessage
220 Service ready<domain>
221 Service closing transmissionchannel
250 Requested mail action OK orcompleted
421 Service notavailable
451 Requested actionaborted
452 Requested action nottaken
501 System (or) syntaxerror
554 Transactionfailed
500 Syntax error in parameter orarguments
503 Bad sequence ofcommands

Size Limitations for SMTP:

SMTP Object Size Limitation


User The max-length of a username is 64 characters
Domain The max-length of a domain name or number is 64 characters
The max-length of reverse path or forward path, including the
Path
punctuation and element separates is 256 characters
The max-length of a command line, including the command word and
Command Line
<CRLF>
Reply Line The max-length of a reply line is 512 characters
Text Line 1000 characters
Recipients Buffer The maximum number of buffered recipients is 100

P a g e | 59WEB TECHNOLOGY DEPARTMENT OF CSE


10. Explain in detail about POP3? (6MARKS)

▪ 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”.

The various POP commands are

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.

▪ “+OK” is a positive success indicator similar to an ACKmessage


▪ The text “-ERR” is a negative success indicator similar to a NAKmessage

P a g e | 60WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
QSMTP
char “mailmessage[]”
{
“HELO user: host\r\n”;
“MAIL FROM: userid@host.domain\r\n”;
“RCPT TO: recipient@comp.host\r\n”;
“DATA\r\n”;
“This is my friend\r\n\r\n”;
“QUIT\r\n”
NULL
};

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
};

▪ SMTPorPOP3basedclientprogramestablishesaconnection;itsendsacommandandwaits for the


server torespond.
▪ SMTP to transfer mail messages across the internet and POP3 to retrieve mail from the
internet.
▪ The two protocolsare
✓ QSMTP
✓ QPOP3
▪ QSMTP used for send mail to send e-mail messages usingSMTP
▪ QPOP3 – get mail to retrieve e-mail messages usingSMTP

P a g e | 61WEB TECHNOLOGY DEPARTMENT OF CSE


POP3 and SMTP:

11. Explain in detailaboutMIME? (11MARKS) (NOV2016)

▪ MIME is an acronym of Multipurpose Internet Mailextensions.


▪ It is an international standard that deals with the format of messages exchanged between
different e-mailsystems.
▪ It is a specification for formatting non – ASCII messages so that they can be sent over the
internet.
▪ Manye-mailclientsnowsupportMIME,whichenablesthemtosendandreceivegraphics,audio and
video files via the internet mailsystem.
▪ MIME supports messages in character set other thanASCII.
▪ MIME was defined in 1992 by the internet engineering task force(IETF).
▪ A new version called s/MIME supports encryptedmessage.
▪ The format of Internet mail to allow Non – US – ASCII textual messages, non – textual messages,
multipart message bodies and non – US – ASCII information in messageheaders.

Need for MIME:


✓ Messages contain only ASCIIcharacters.
✓ Messages with only 1000characters.
✓ Messages should not exceed certainlength.

P a g e | 62WEB TECHNOLOGY DEPARTMENT OF CSE


Features of MIME:

MIME allow mail messages to have


✓ Multiple objects in a singlemessage.
✓ Message with any no. of lines or unlimited overalllength.
✓ Characters other than ASCII, allowing non – Englishmessages.
✓ Multi – fontmessages.
✓ Binary or application specificfiles.
✓ Images, audio, video and multipartmessages.

▪ 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

P a g e | 63WEB TECHNOLOGY DEPARTMENT OF CSE


1. MIME-Version:
▪ This header defines the version of MIME used.
▪ The current version is1.1
MIME-Version: 1.1

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 >

Data Types and Subtypes in MIME

2. Content–Transfer:
▪ This header defines the method used to encode the messages into 0’s and 1’s fortransport.
Content -Transfer – Encoding: < type >

P a g e | 64WEB TECHNOLOGY DEPARTMENT OF CSE


Base-64

Base-64 Converting Table

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>

P a g e | 65WEB TECHNOLOGY DEPARTMENT OF CSE


12. Write a short noteonIMAP? (5MARKS)
▪ IMAP stands for Internet Message Accessprotocol.
▪ This protocol is used to access the messages in e-mail or electronic bulletin board that are in mail
server
▪ It is an application layer Internet protocol that allows e-mail client to access e-mail on a remote
mailserver
▪ The current version IMAP4 is defined byRFC3501.
▪ IMAP server on well-known portno.143

The objectives of IMAP are


1. Compatible with internet messaging standards Ex:MIME
2. Allow message access from multiplecomputers.
3. It supports for online, offline and disconnected accessnodes.
4. Support for concurrent access to sharedmailboxes.
5. Client software needs no knowledge about the servers file storeformat.

▪ 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 protocols includes operations for


✓ Creatingmailboxes.
✓ Deletingmailboxes.
✓ Renamingmailboxes.
✓ Checking for newmessages.
✓ Permanently removingmessages.
✓ Setting and clearingflags.
✓ Selective fetching of message attributes, text and portion ofefficiency.

P a g e | 66WEB TECHNOLOGY DEPARTMENT OF CSE


13. Explain in detailaboutDNS? (6 MARKS) (APR2016)

Domain Name System (DNS)


▪ To identify an entity, TCP/IP protocols use the IP address which uniquely identifies the
connection of a host to theinternet.
▪ We prefer to use names instead ofaddress.
▪ We need a system that can map a name to an address and conversely an address to a name.
In TCP/IP, this is the domain name system(DNS).
▪ What internet users use to reference anything by the name of theinternet?
▪ The mechanism by which Internet software translates name toaddresses.

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

Top Level Node Top Level Node Top Level 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

Top 1 Top 2 Top 3

foo foo foo foo

P a g e | 67WEB TECHNOLOGY DEPARTMENT OF CSE


DNS in the Internet:
▪ A domain name is the sequence of labels from a node to the root separated by dots (“.”’s),
read left toright.
✓ The namespace has a maximum depth of 127levels.
✓ Domain names are limited to 64 characters inlength.
▪ A node’s domain name identifies its position in thenamespace.
▪ DNS is a protocol that can be used in differentplatforms.
In the internet, the domain namespace (tree) is divided onto 3 different sections.
1. Genericdomains
2. Countrydomains
3. Inversedomains

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.

P a g e | 68WEB TECHNOLOGY DEPARTMENT OF CSE


The generic domain labels are

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.

“ Root univ.edu domain

.com .edu .org

univ

anna anna.univ.edu zone

P a g e | 69WEB TECHNOLOGY DEPARTMENT OF CSE


2. CountryDomain:
▪ The county domain section follows the same format as the generic domains but uses two
characters countryabbreviations
▪ Ex: .us(United States),.in(India)

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.

P a g e | 70WEB TECHNOLOGY DEPARTMENT OF CSE


14. Explain about the Web Browser andWebServers? (11MARKS)

WEB BROWSER:

A web browser (commonly referred to as a browser) is a software applicationfor retrieving,


presenting, and traversing information resources on the World Wide Web.An information resource is
identified by a Uniform Resource Identifier(URI/URL) and may be a web page,image, video or other
piece of content. Hyperlinkspresent in resources enable users easily to navigate their browsersto
relatedresources.

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 has two main functions namely:


1. To make a request for a page. This is done by typing in the URL of the web page concerned in
the address bar of the web browser. Similarly, when a hyperlink is clicked the URL of the
hyperlink gets automatically populated in the address bar of thebrowser.
2. To interpret the HTML page sent to the user from the web server. The formatting is done on
the browser and displayed to the user in a readable form. The actual page on the web server is in
ASCII form. HTML along with Cascading Style Sheets (CSS) are used to present the web pages in
webbrowser.

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.

P a g e | 71WEB TECHNOLOGY DEPARTMENT OF CSE


Following are the most common web browser available today:

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

P a g e | 72WEB TECHNOLOGY DEPARTMENT OF CSE


▪ Controller works as a control unit in CPU. It takes input from the keyboardor mouse, interpret it
and make other services to work on the basis of input itreceives.
▪ Interpreter receives the information from the controller and execute the instruction line by line.
Some interpreter are mandatory while some are optional For example, HTML interpreter
program is mandatory and java interpreter isoptional.
▪ Client Program describes the specific protocol that will be used to access a particular
service. Following are the client programs that are commonlyused:
✓ HTTP
✓ SMTP
✓ FTP
✓ NNTP
✓ POP
WEB SERVERS:
A web server is a computer system that processes requests via HTTP,the basic networkprotocol
used to distribute information on the World Wide Web. The term can refer to the entire system, or
specifically to the software that accepts and supervises the HTTPrequests.

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.

P a g e | 73WEB TECHNOLOGY DEPARTMENT OF CSE


▪ When client sends request for a web page, the web server search for the requested page if
requested page is found then it will send it to client with an HTTPresponse.
▪ If the requested web page is not found, web server will the send an HTTP response: Error 404
Notfound.
▪ If client has requested for some other resources then the web server will contact to the
application server and data store to construct the HTTPresponse.

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

P a g e | 74WEB TECHNOLOGY DEPARTMENT OF CSE


15. Write short notesonDHTML? (5MARKS)

▪ 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

CSS Client side


scripting DOM

The contents of web pages are


1. Hide text and images in document and keep this content hidden until a given time elapses or
the user interacts with thepage.
2. Animate text and images in document, independently moving each element from any starting
point to any endingpoint.
3. Create a timer that automatically refreshes the content of a document with the latest news,
stock quotes, cricket scores,etc.
4. Animated audio and video files (visualchange)
5. Createaformandtheninstantlyread,processandrespondtothedata.Theuserentersinthe form.
6. DHTML canbe
a. Internet Explorer: VB Script and JavaScript bothworks
b. Netscape Navigator:JavaScript
7. Forms processing (validation,calculations)
8. Changing text (moving, scrolling, blinking,etc…)

P a g e | 75WEB TECHNOLOGY DEPARTMENT OF CSE


16. Explain in detail about CascadingStyleSheets? (11MARKS)

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;}

P a g e | 76WEB TECHNOLOGY DEPARTMENT OF CSE


h2 {color:blue;}
p {margin-left:50px;}
</style>
</head>
<body>
<h1>This header is 36 pt</h1>
<h2>This header is blue</h2>
<p>This paragraph has a left margin of 50 pixels</p>
</body>
</html>
▪ To assign more than one kind of style information at the same time, separate the styles with
semicolon.

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:

<img align=top|middle|center|bottom|left|right alt=text border=n class=type controls dynsrc=url


height=n space=n ID=value ismap=image start=start-event>
▪ Alt=text
✓ Specifiestextthatwillbedisplayedinplaceofthepicturesifshowpicturesisturned off
▪ class=type
✓ indicates the class to which the elementbelongs

P a g e | 77WEB TECHNOLOGY DEPARTMENT OF CSE


▪ controls
✓ if a video clip is present, displays a set of controls under theclip
▪ dynsrc=url
✓ specifies the address of a videoclip
▪ id=value
✓ specifies a unique value for the element over thedocument
▪ ismap=image
✓ Identifies the picture as a server-side image map. Clicking the picture transmits the
coordinates of the click back to the server, triggering a jump toanother.
▪ Loop=n
✓ Specifies how many times a video clip will loop whenactivated.
▪ Start=start-event
✓ Specifies when the file specified by the dynsrc=attribute should startplaying
✓ FILEOPEN
✓ MOUSEOPEN

Other Style Properties:


▪ font-style normal | italic |oblique
▪ font-variant normal |small-caps
▪ font-weight normal | bold | bolder | lighter | 100… |900
▪ font-size absolute-size |relative-size
▪ background-image url(“filename”)
▪ background-color color
▪ background-position top | center | bottom | left |right
▪ text-decoration underline | overline | line-through |blink
▪ text-transform capitalize | uppercase |lowercase

P a g e | 78WEB TECHNOLOGY DEPARTMENT OF CSE


17. Write a short note on FeaturesofCSS? (6MARKS)

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.

Making changes to the layout


CSS makes it very easy to change the style of a document. Let's say we wanted to move the
picture in the title of this page to the right by 10 pixels. This would be a nightmare in a table based
design. We would have to open every page and alter the table width manually.
Fortunately we have used CSS, and all we have to do is open our CSS file which stores the
layout of the site, and change the number relating to the position of the image. That will change his
position throughout the whole site.
The look and layout of a site can be changed beyond recognition just by altering the CSS file.
This makes CSS indispensable for large web sites.

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.

P a g e | 79WEB TECHNOLOGY DEPARTMENT OF CSE


CSS saves time
With CSS, you only have to specify these details once for any element. CSS will
automatically apply the specified styles whenever that element occurs.

Pages load faster


Less code means faster download times.

Easy maintenance
To change the style of an element looks across the whole site, you only have to make an edit in
one place.

Superior styles to HTML


CSS was built for styles. HTML was not. While browsers usually display HTML elements in
a certain way, you can override this with CSS.

Search Engine Optimization


CSS features a coding technique that is clear-cut and simple to read. Search engines will no
longer have to struggle to comprehend your website content. The advantage of improved
accessibility of content will allow a broader number of users to locate you on the Internet. Less code
and more content equals search enginesuccess.

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.

P a g e | 80WEB TECHNOLOGY DEPARTMENT OF CSE


18. Explain in detail about SelectorsinCSS? (6MARKS)

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>

P a g e | 81WEB TECHNOLOGY DEPARTMENT OF CSE


In the example below, all HTML elements with class="center" will be red and center-aligned:

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:

P a g e | 82 WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
h1, h2, p {
text-align: center;
color: red;
}

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}

19. Explain in detail about AttributesinCSS? (6MARKS)


It is possible to style HTML elements that have specific attributes or attribute values.

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;
}

P a g e | 83WEB TECHNOLOGY DEPARTMENT OF CSE


4. CSS [attribute|="value"]selector:
▪ 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. 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;
}

P a g e | 84WEB TECHNOLOGY DEPARTMENT OF CSE


20. Explain the various Cascading StyleSheet(CSS)? (11 MARKS) (NOV2017)

There are 4 ways of adding styles to web page


1. Internal style sheet within the head tags of the HTMLdocument
2. Link to an external style sheet from the HTMLdocument
3. Import an external style sheet into thedocument
4. Inline style sheet added into the middle of the HTMLdocument

External Style Sheet:


▪ With an external style sheet, you can change the look of an entire website by changing just
onefile!
▪ Eachpagemustincludeareferencetotheexternalstylesheetfileinsidethe<link>element. The
<link> element goes inside the <head>section:
<head>
<link rel="stylesheet" type="text/css"
href="mystyle.css"> </head>

▪ 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;}

P a g e | 85WEB TECHNOLOGY DEPARTMENT OF CSE


external.html
<html>
<head>
<title> Linking External Style Sheets</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping list for <em> monday</h1>
<ul>
<li>Milk</li>
<li>Bread
<ul>
<li>White Bread</li>
<li>Wheat Bread</li>
</ul>
</li>
<li>Rice</li>
<li>Potato</li>
</ul>
<p><em>Go to the</em>
<a class="nodec" href="http://www.dietel.com">Store</a>
</p>
</body>
</html>

Output:

P a g e | 86WEB TECHNOLOGY DEPARTMENT OF CSE


Internal Style Sheet:
▪ An internal style sheet may be used if one single page has a uniquestyle.
▪ Internal styles are defined within the <style> element, inside the head section of an HTML
page:

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 &nbsp; </p>
<h1> Client </h1>
<p class="special"> Server
side<em>Computing</em></p> </body>
</html>

P a g e | 87WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

Inline Style Sheet:

▪ An inline style may be used to apply a unique style for a singleelement.


▪ Aninlinestylelosesmanyoftheadvantages ofastylesheet(bymixingcontentwith
presentation). Use this methodsparingly!
▪ To use inline styles, add the style attribute to the relevant element. The style attribute can
contain any CSSproperty.

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>

P a g e | 88WEB TECHNOLOGY DEPARTMENT OF CSE


21. Explain briefly about JavaScriptindetail? (5MARKS)

▪ JavaScript is the programming language of HTML and theWeb.


▪ Programming makes computers do what you want them todo.
▪ JavaScript to program the behavior of webpages.
▪ JavaScript is an object-oriented language that allows creation of interactive Webpages.
▪ JavaScript allows user entries, which are loaded into an HTML form to be processed asrequired.

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>

P a g e | 89WEB TECHNOLOGY DEPARTMENT OF CSE


22. Explain the JavaScript in Perspectiveindetail? (6MARKS)

JavaScript is a dynamic computer programming language. It is lightweight and most


commonly used as a part of web pages, whose implementations allow client-side script to interact
with the user and make dynamic pages. It is an interpreted programming language with object-
oriented capabilities.

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:

The merits of using JavaScript are −


▪ Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on yourserver.
▪ Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to entersomething.

P a g e | 90WEB TECHNOLOGY DEPARTMENT OF CSE


▪ Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via thekeyboard.
▪ Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your sitevisitors.

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 Development Tools:


One of major strengths of JavaScript is that it does not require expensive development tools.
You can start with a simple text editor such as Notepad. Since it is an interpreted language inside
the context of a web browser, you don't even need to buy acompiler.
To make our life simpler, various vendors have come up with very nice JavaScript editing tools.
Some of them are listed here −
▪ Microsoft FrontPage − Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with a number of JavaScript tools to assist in the
creation of interactivewebsites.
▪ Macromedia Dreamweaver MX − Macromedia Dreamweaver MX is a very popular HTML
and JavaScript editor in the professional web development crowd. It provides several handy
prebuilt JavaScript components, integrates well with databases, and conforms to new
standards such as XHTML andXML.
▪ Macromedia HomeSite 5 − HomeSite 5 is a well-liked HTML and JavaScript editor from
Macromedia that can be used to manage personal websiteseffectively.

P a g e | 91WEB TECHNOLOGY DEPARTMENT OF CSE


23. Write a short note onJavaScriptSyntax? (6MARKS)

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.

A simple syntax of your JavaScript will appear as follows.


<script…>
JavaScript code
</script>

The script tag takes two important attributes −


▪ Language − This attribute specifies what scripting language you are using. Typically, its
value will be Javascript. Although recent versions of HTML have phased out the use of this
attribute.
▪ Type − This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to"text/javascript".

The JavaScript segment will look like –


<script language="Javascript" type="text/Javascript">
JavaScript code
</script>

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>

P a g e | 92WEB TECHNOLOGY DEPARTMENT OF CSE


Output:
This code will produce the following result –
Hello World!

White Space and Line Breaks:


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use
spaces, tabs, and newlines freely in your program and you are free to format and indent your
programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional:


Simple statements in JavaScript are generally followed by a semicolon character, just as they
are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your
statements are placed on a separate line.
For example, the following code could be written without semicolons.

<script language="javascript" type="text/javascript">


var1 = 10
var2 =20
</script>

But when formatted in a single line as follows, you must use semicolons −

<script language="javascript" type="text/javascript">


var1 = 10; var2 = 20;
</script>

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//-->.

P a g e | 93WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
The following example shows how to use comments in JavaScript.
<script language="javascript" type="text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment inJavaScript
* It is very similar to comments in CProgramming
*/
//-->
</script>

24. Explain theJavaScriptVariables? (6

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.

Variables are declared with the var keyword as follows.


<script type="text/javascript">
var money;
var name;
</script>

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).

P a g e | 94WEB TECHNOLOGY DEPARTMENT OF CSE


The general rules for constructing names for variables (unique identifiers) are:
✓ Names can contain letters, digits, underscores, and dollarsigns.
✓ Names must begin with aletter.
✓ Names can also begin with $ and_.
✓ Names are case sensitive (y and Y are differentvariables).
✓ Reserved words (like JavaScript keywords) cannot be used asnames.

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.

JavaScript Variable Scope:


The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only twoscopes.
1. Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScriptcode.
2. Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to thatfunction.

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.

P a g e | 95 WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
<script type="text/javascript">
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>

Output:
This produces the following result –
local

JavaScript Reserved Words:


▪ A list of all the reserved words in JavaScript are given in the followingtable.
▪ TheycannotbeusedasJavaScriptvariables,functions,methods,looplabels,oranyobject
names.

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

P a g e | 96WEB TECHNOLOGY DEPARTMENT OF CSE


25. Discuss the various data types available inJavaScript. (11 MARKS) (NOV2016)

JavaScript Data Types:


JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.
1. Primitive datatype
2. Non-primitive (reference) datatype

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

1. JavaScript primitive data types:

There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description


String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

(i) JavaScript String:


▪ A string (or a text string) is a series of characters like "JohnDoe".
▪ Strings are written with quotes. You can use single or doublequotes:

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

P a g e | 97WEB TECHNOLOGY DEPARTMENT OF CSE


(ii) JavaScript Number:
▪ JavaScript has only one type ofnumbers.
▪ Numbers can be written with, or withoutdecimals:

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

(iii) JavaScript Boolean:


▪ Booleans can only have two values: true orfalse.
▪ Booleans are often used in conditionaltesting.

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

P a g e | 98WEB TECHNOLOGY DEPARTMENT OF CSE


(vi) Null:
▪ In JavaScript null is "nothing". It is supposed to be something that doesn'texist.
▪ Unfortunately, in JavaScript, the data type of null is anobject.

You can empty an object by setting it to null:


Example:
var person= null; // Value is null, but type is still anobject

You can also empty an object by setting it to undefined:


Example:
var person= undefined; // Value is undefined, type isundefined

2. JavaScript non-primitive datatypes:

The non-primitive data types are as follows:

Data Type Description


Object represents instance through which we can access
members
Array represents group of similar values
RegExp represents regular expression

(i) JavaScript Object:


▪ JavaScript objects are written with curlybraces.
▪ Object properties are written as name:value pairs, separated bycommas.

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.

(ii) JavaScript Array:


▪ JavaScript arrays are written with squarebrackets.
▪ Array items are separated bycommas.

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.

P a g e | 99WEB TECHNOLOGY DEPARTMENT OF CSE


(iii) JavaScript RegExp:
▪ A regular expression is an object that describes a pattern ofcharacters.
▪ Regular expressions are used to perform pattern-matching and "search-and-replace"
functions ontext.

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).

26. Explain theJavaScriptStatements? (6MARKS)

Conditional statements are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:


i. Use if to specify a block of code to be executed, if a specified condition istrue.
ii. Use else to specify a block of code to be executed, if the same condition isfalse.
iii. Use else if to specify a new condition to test, if the first condition isfalse.
iv. Use switch to specify many alternative blocks of code to beexecuted.

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";
}

The result of greeting will be:


Good day

P a g e | 100WEB TECHNOLOGY DEPARTMENT OF CSE


(ii) The elseStatement:
Use the else statement to specify a block of code to be executed if the condition is false.

Syntax:
if (condition)
{
block of code to be executed if the condition is true
}
else
{
block of code to be executed if the condition is false
}

Example:
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";
}

The result of greeting will be:


Good day

(iii) The else ifStatement:


Use the else if statement to specify a new condition if the first condition is false.

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
}

P a g e | 101WEB TECHNOLOGY DEPARTMENT OF CSE


else
{
block of code to be executed if the condition1 is false and condition2 is false
}

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";
}

The result of greeting will be:


Good day

P a g e | 102WEB TECHNOLOGY DEPARTMENT OF CSE


27. Explain the JavaScript Operators withan example? (6MARKS)

JavaScript supports the following types of operators.


1. Arithmetic Operators
2. ComparisonOperators
3. Logical (or Relational)Operators
4. BitwiseOperators
5. AssignmentOperators
6. Conditional (or ternary)Operators

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

Logical (or Relational) Operators:


JavaScript supports the following logical operators.

Operator Description
&& Logical AND
|| Logical OR
! Logical NOT

P a g e | 103WEB TECHNOLOGY DEPARTMENT OF CSE


Bitwise Operators:
JavaScript supports the following bitwise operators.

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:

The two miscellaneous operators are


▪ Conditional operator (?:)
▪ typeofoperator

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.

S.No Operator and Description


? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y

P a g e | 104WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
The following code to understand how the Conditional Operator works in
JavaScript. <html>
<body>
<script type="text/javascript">
var a =10;
var b =20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

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.

Type String Returned by typeof


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

P a g e | 105WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
The following code shows how to implement typeof operator.
<html>
<body>
<script type="text/javascript">
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

Output:
Result => B is String
Result => A is Numeric

P a g e | 106WEB TECHNOLOGY DEPARTMENT OF CSE


28. Explain the JavaScript Literals withanexample? (6MARKS)
The various JavaScript literals are
1. Stringliterals
2. Arrayliterals
3. Integerliterals
4. Floating pointingliterals
5. Booleanliterals
6. Objectliterals

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.

P a g e | 107WEB TECHNOLOGY DEPARTMENT OF CSE


Creating an empty array :
var fruits = [ ];

Creating an array with four elements


var fruits = ["Orange", "Apple", "Banana", "Mango"]

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.

In JavaScript, integers can be expressed in three different bases.


1. Decimal (base10)
Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no
leading zeros.
Example: 123, -20, 12345
2. Hexadecimal (base16)
Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C,
D, E, F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal. Example: 7b, -
14, 3039
3. Octal (base8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the
number is octal.
Example: 173, -24, 30071

Floating pointing literals:


A floating number has the following parts.
▪ A decimalinteger.
▪ A decimal point('.').
▪ Afraction.
▪ Anexponent.

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]

P a g e | 108WEB TECHNOLOGY DEPARTMENT OF CSE


Boolean literals:
The Boolean type has two literal values:
▪ true
▪ false

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.

In JavaScript an object literal is declared as follows:


1. An object literal without properties:
var userObject ={}

2. An object literal with a few properties:


var student ={
First-name : "Suresy",
Last-name : "Rayy",
Roll-No :
12 };

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.

P a g e | 109WEB TECHNOLOGY DEPARTMENT OF CSE


29. Explain the JavaScript Functions withanexample? (11MARKS)

▪ 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).

JavaScript Function Syntax:


▪ A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
▪ Function names can contain letters, digits, underscores, and dollarsigns.
▪ The parentheses may include parameter names separated by commas:(parameter1,
parameter2,...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3)
{
code to be executed
}
▪ Function parameters are the names listed in the functiondefinition.
▪ Function arguments are the real values received by the function when it isinvoked.
▪ Inside the function, the arguments behave as localvariables.

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":

P a g e | 110 WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
Calculate the product of two numbers, and return the result:
var x =myFunction(4, 3); // Function is called, return value will end up inx

function myFunction(a, b) {
return a*b; // Function returns the product of a andb
}

The result in x will be:


12

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

Use different parameters inside the function and then try...


Hello there!

P a g e | 111WEB TECHNOLOGY DEPARTMENT OF CSE


Function Parameters:
There is a facility to pass different parameters while calling a function. These passed parameters
can be captured inside the function and any manipulation can be done over those parameters. A
function can take multiple parameters separated by comma.

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

Use different parameters inside the function and then try...


Zara is 7 years old.

P a g e | 112WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
<html>
<head>
<script language="javascript">
function showmessage()
{
alert("How are you");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click Here!" onclick="showmessage()" >
</form>
</body>
</html>

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").

P a g e | 113WEB TECHNOLOGY DEPARTMENT OF CSE


Built-in functions:
The list of the built-in JavaScript functions:

JavaScript Build inFunction Function Description


alert() The alert() built-in function displays the alert dialog box.

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>

P a g e | 114WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

30. Explain the JavaScript objects withanexample? (6MARKS)

JavaScript is an Object Oriented Programming (OOP) language. A programming language can be


called object-oriented if it provides four basic capabilities to developers
▪ Encapsulation − the capability to store related information, whether data or methods, together
in anobject.
▪ Aggregation − the capability to store one object inside anotherobject.
▪ Inheritance − the capability of a class to rely upon another class (or number of classes) for
some of its properties andmethods.
▪ Polymorphism − the capability to write one function or method that works in a variety of
differentways.

Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of


the object, otherwise the attribute is considered a property.

Object Properties:
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

property Property Value


firstName John
lastName Doe
age 50
eyeColor blue

P a g e | 115WEB TECHNOLOGY DEPARTMENT OF CSE


Object Methods

▪ Methods are actions that can be performed onobjects.


▪ Methods are stored in properties as functiondefinitions.

property Property Value


firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}

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"
};

Accessing Object Properties:


You can access object properties in two ways:

Syntax:
objectName.propertyName
(or)
objectName["propertyName"]

Example:
person.lastName;
person["lastName"];

P a g e | 116WEB TECHNOLOGY DEPARTMENT OF CSE


Accessing Object Methods:
You access an object method with the following syntax:

Syntax:
objectName.methodName()

Example:
name = person.fullName();

The Object() Constructor:


A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object()to build the object. The return value of the Object() constructor is
assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are
not variables and are not defined with the varkeyword.

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

P a g e | 117WEB TECHNOLOGY DEPARTMENT OF CSE


31. Explain the JavaScript Arrays withanexample? (6MARKS)
▪ An array is a special variable, which can hold more than one value at atime.
▪ JavaScript arrays are used to store multiple values in a singlevariable.

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"];

Using the JavaScript Keyword new:


The following example also creates an Array, and assigns values to it:

Example:
var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array:


An array element by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];

Arrays are Objects:


▪ Arrays are a special type of objects. The typeof operator in JavaScript returns "object" forarrays.
▪ But, JavaScript arrays are best described asarrays.

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};

P a g e | 118WEB TECHNOLOGY DEPARTMENT OF CSE


Array Properties and Methods:
The real strength of JavaScript arrays are the built-in array properties and methods:

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

The length Property:


The length property of an array returns the length of an array (the number of array elements).

Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruitsis
4

Adding Array Elements:


The easiest way to add a new element to an array is using the push method:

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

P a g e | 119WEB TECHNOLOGY DEPARTMENT OF CSE


32. Explain the JavaScript Built-in Objects with an example?(11MARKS) (APR, NOV2017)
The various Built-in Objects in JavaScript are
1. Mathobject
2. Stringobject
3. Date object
4. Booleanobjects
5. Numberobjects
6. Arrayobject
7. Regular Expressionobject
8. Documentobject
9. Windowobject

(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

P a g e | 120 WEB TECHNOLOGY DEPARTMENT OF CSE


(ii) Stringobject:
▪ The String object is used to manipulate a storing and manipulatingtext.
▪ String objects are created with newString().

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

P a g e | 121WEB TECHNOLOGY DEPARTMENT OF CSE


String HTML Wrapper Methods:
The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.

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.

P a g e | 122WEB TECHNOLOGY DEPARTMENT OF CSE


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
getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time (four digits)
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
parse() Parses a date string and returns the number of milliseconds since midnight of
January 1, 1970
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
toDateString() Converts the date portion of a Date object into a readable string
toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
valueOf() Returns the primitive value of a Date object

P a g e | 123WEB TECHNOLOGY DEPARTMENT OF CSE


(iv) Booleanobjects:
▪ JavaScript Boolean objects can have one of two values: true orfalse.
▪ ThesewrappersdefinemethodsandpropertiesusefulinmanipulatingBooleanvalues. var
b = new Boolean ( booleanValue);

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

P a g e | 124WEB TECHNOLOGY DEPARTMENT OF CSE


(vii) Regular Expressionobject:
▪ A regular expression is an object that describes a pattern ofcharacters.
▪ Regular expressions are used to perform pattern-matching and "search-and-replace" functions
ontext.

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

P a g e | 125WEB TECHNOLOGY DEPARTMENT OF CSE


Meta-characters:
Meta-characters are characters with a special meaning:

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

P a g e | 126WEB TECHNOLOGY DEPARTMENT OF CSE


RegExp Object Properties:

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

RegExp Object Methods:

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

P a g e | 127WEB TECHNOLOGY DEPARTMENT OF CSE


document.write()
document.write() Writes HTML expressions or JavaScript code to a document
document.writeln() Adds a newline character after each statement

(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

P a g e | 128WEB TECHNOLOGY DEPARTMENT OF CSE


33. Explain in detail aboutJavaScriptdebuggers? (6MARKS)

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.

The console.log() Method:


▪ Ifyourbrowsersupportsdebugging,youcanuseconsole.log()todisplayJavaScriptvaluesinthe
debuggerwindow:

Example:
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b =6;
c = a + b;
console.log(c);
</script>
</body>
</html>

P a g e | 129WEB TECHNOLOGY DEPARTMENT OF CSE


The debugger Keyword:
▪ ThedebuggerkeywordstopstheexecutionofJavaScript,andcalls(ifavailable)thedebugging
function.
▪ This has the same function as setting a breakpoint in thedebugger.
▪ If no debugging is available, the debugger statement has noeffect.
▪ With the debugger turned on, this code will stop executing before it executes the thirdline.

Example:
<script>
var x = 15 * 5;
debugger;
document.write(x);
</script>

Error Message in IE:

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.

P a g e | 130 WEB TECHNOLOGY DEPARTMENT OF CSE


Error Notifications:
Error notifications that show up on Console or through Internet Explorer dialog boxes are the
result of both syntax and runtime errors. These error notifications include the line number at which
the error occurred.

Major Browsers' Debugging Tools:


Normally, you activate debugging in your browser with F12, and select "Console" in the
debugger menu.

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.

P a g e | 131WEB TECHNOLOGY DEPARTMENT OF CSE


34. Explain in detail about Regular ExpressioninJavaScript? (6MARKS)

▪ A regular expression is an object that describes a pattern ofcharacters.


▪ When you search in a text, you can use a pattern to describe what you are searchingfor.
▪ A simple pattern can be one singlecharacter.
▪ A more complicated pattern can consist of more characters, and can be used for parsing, format
checking, substitution andmore.
▪ Regular expressions are used to perform powerful pattern-matching and "search-and-replace"
functions ontext.

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.

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?

P a g e | 132WEB TECHNOLOGY DEPARTMENT OF CSE


Example 3
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
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.

The following example searches a string for the character "e":


Example 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
e

Using String Methods:


In JavaScript, regular expressions are often used with the two string methods:
✓ search()
✓ replace()

The search() method:


▪ It uses an expression to search for a match, and returns the position of thematch.

P a g e | 133WEB TECHNOLOGY DEPARTMENT OF CSE


Example:
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);

The result in n will be:


6

The replace() method:


▪ It returns a modified string where the pattern isreplaced.

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");

The result in res will be:


Visit W3Schools!

P a g e | 134WEB TECHNOLOGY DEPARTMENT OF CSE


35. Write a Java Script that inputs several lines of text and a search character determines the
number of occurrence of the character in the text using suitable string methods. (11 MARKS) (NOV
2016)
<html>
<head>
<title> CountIt </title> <script
type="text/javascript"> <!--

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">&nbsp;</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>

P a g e | 135WEB TECHNOLOGY DEPARTMENT OF CSE


<tr>
<td> Enter any String </td>
<td> <input name = "string1" type = "text" /> </td>
</tr>
<tr>
<td> Enter search Character </td>
<td> <input name = "string2" type = "text" /> </td>
</tr>
<tr>
<td> Search Result </td>
<td> <textarea name="ans"> </textarea> </td>
</tr>
<tr>
<td> <input type = "button" value = "SearchIt" onclick = "search1()" />
</td> </tr>
</table>
</form>
</tr>
</table>
</body>
</html>

P a g e | 136WEB TECHNOLOGY DEPARTMENT OF CSE


OUTPUT:

P a g e | 137WEB TECHNOLOGY DEPARTMENT OF CSE


36. Write a script that reads five integers and determines the largest and the smallest integers in
the group. (APR2012)

<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>

P a g e | 138WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

P a g e | 139WEB TECHNOLOGY DEPARTMENT OF CSE


37. Write a script to find the number of occurrences of a given number in a set of storednumbers.
(APR 2013)
<html>
<head>
<title> Number of Occurrences </title>
<script language="javascript">
function find()
{
var i,a1,count=0;
var set=[50,35,78,12,67,50,50,67];
a1=parseInt(myform.no.value);
for(i=0;i<set.length;i++)
{
if(a1==set[i])
count++;
}
document.writeln("<center><h1><font color=red> The elements in an array </font> </h1> </center>
<br>");
for(i=0;i<set.length;i++)
{
document.write("<center> <h2>" + " Number " + i + " is " + set[i] + "</h2>");
}
document.writeln("<br> <br> <center> <h1> <font color=green> Number of Occurrences of " + a1 + " is "
+ count + " </font> </h1> </center>");
}
</script>
</head>
<body>
<h1 align="center"><font color="green"> Finding the frequency of a number </font>
</h1> <form name="myform">
<table align="center" cellspacing="20%"
cellpadding="10%"> <tr>
<th> <font color="red"> Enter a Number: </font> </th>
<th> <input type="text" name="no" value="" /> </th>
</tr>
<tr>
<th><input type="button" value="SEARCH" onclick="find()" />
</th> <th><input type="reset" value="CLEAR" /> </th>
</tr>

P a g e | 140 WEB TECHNOLOGY DEPARTMENT OF CSE


</table>
</form>
</body>
</html>

Output:

P a g e | 141WEB TECHNOLOGY DEPARTMENT OF CSE


38. Write a Java Script that uses a function Circle Area to prompt the user for the radius of a circle
and to calculate and print the area of that circle. (APR2014)

<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>

P a g e | 142WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

P a g e | 143WEB TECHNOLOGY DEPARTMENT OF CSE


39. Write a script to addtwointegers. (5MARKS)
<html>
<head>
<title>To add two integers</title>
<script language = "javascript">
varno1,no2,no3,no4,result;
no1 = window.prompt( "Enter the first integer","" );
no2 = window.prompt( "Enter the second integer","" );
no3 = parseInt( no1);
no4 = parseInt( no2 );
result = no3 + no4;
document.writeln( "<h3 align=center> The First no is " + no3 + " </h3><br>" );
document.writeln( "<h3 align=center> The second no is " + no4 + " </h3><br>" );
document.writeln( "<h2 align=center> <font color=blue face=arial size=20> The addition
of two integer is " + result + " </font> </h2>" );
</script>
</head>
<body>
</body>
</html>
Output:

P a g e | 144WEB TECHNOLOGY DEPARTMENT OF CSE


40. Write a script that reads integers and determines the square root of the integer using square
root method ofMathobject. (5MARKS)
<html>
<head>
<title> To find square root of an integer </title>
<script language="javascript">
var no,root;
no=window.prompt("Enter the Number","");
no1=parseInt(no);
root=Math.sqrt(no1);
document.write("<h2> The Number = " + no1 + "</h2> <br>");
document.write("<h2> The Square root= " + root + "</h2>");
</script>
</head>
<body>
</body>
</html>

P a g e | 145WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

P a g e | 146WEB TECHNOLOGY DEPARTMENT OF CSE


41. Write a function ‘distance’ which calculates the distance between two points (x1, y1) and (x2,
y2). Incorporate the function into a script that enables the user to enter the coordinates of the
points through anHTMLform. (11MARKS)
<html>
<head>
<title> Distance calculation </title>
<script language="javascript">
function calculate()
{
var a1,a2,a3,a4,r1,r2;
a1=parseInt(cal.x1.value);
a2=parseInt(cal.y1.value);
a3=parseInt(cal.x2.value);
a4=parseInt(cal.y2.value);
r1=a1-a3;
r1=Math.abs(r1);
r2=a2-a4;
r2=Math.abs(r2);
document.write("<h2> The Distance = " + r1 + "," + r2 + "</h2><br>");
}
</script>
</head>
<body>
<h1 align="center"> Finding distance between the coordinates
</h1> <form name="cal">
COORDINATE1<br>
X1<input type="text" name="x1" size="20"><br>
Y1<input type="text" name="y1" size="20"><br>
COORDINATE 2<br>
X2<input type="text" name="x2" size="20"><br> Y2<input
type="text" name="y2" size="20"><br> <br> <br> <input
type="button" value="CALCULATE" onClick="calculate()">
<input type="reset" value="CLEAR" onClick="clear">
</form>
</body>
</html>

P a g e | 147WEB TECHNOLOGY DEPARTMENT OF CSE


Output:

P a g e | 148WEB TECHNOLOGY DEPARTMENT OF CSE


PONDICHERRY UNIVERSITY QUESTIONS

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

APRIL 2016 (REGULAR)


1. (a). Summarize the conceptofDNS? (6Marks) (Ref.Qn.No.13,Pg.no.67)
(b). Write a short notesonWWW. (5Marks) (Ref.Qn.No.3,Pg.no.26)
(OR)
2. Explain HTML forms in detail along with form elements, attributes and methods and Write an HTML
document to provide a form that collect name and telephone numbers. (Ref.Qn.No.5,Pg.no.41)
3. Write a Java Script that inputs several lines of text and a search character determines the number of
occurrence of the character in the text using suitable stringmethods.
(Ref.Qn.No.35, Pg.no.135)

NOV 2016 (ARREAR)


1. Explain thefollowing:
(a) SMTP (Ref.Qn.No.9,Pg.no.55)
(b) MIME (Ref.Qn.No.11,Pg.no.62)
(OR)
2. Discuss the various data types available inJavaScript. (Ref.Qn.No.25, Pg.no.97)

P a g e | 149WEB TECHNOLOGY DEPARTMENT OF CSE


APRIL 2017 (REGULAR)
1. Explain in detail about HTML forms along with form elements, attributes andmethods.
(Ref.Qn.No.5, Pg.no.41)
(OR)
2. With the help of a schematic diagram elucidate the operational scenario of SMTPprotocol.
(Ref.Qn.No.9, Pg.no.55)
3. Mention the types of java script objects. And also explain each with an example. (Ref.Qn.No.32,
Pg.no.120)

NOV 2017 (ARREAR)


4. DefineCSS.WhatarethevarioustypesofCSS?ExplaintheapplicationofCSSwithacasestudyof Online
tutoringwebsite. (Ref.Qn.No.20 ,Pg.no.85)
(OR)
5. Elaborate in detail about Object handling features supported by JavaScript. (Ref.Qn.No.32,
Pg.no.120)

P a g e | 150 WEB TECHNOLOGY DEPARTMENT OF CSE

You might also like