You are on page 1of 71
Programming the Web 06CS73 INTRODUCTION AND OVERVIEW Dr. Kavi Mahesh, PESIT, Bangalore Textbook: Programming the

Programming the Web

06CS73

INTRODUCTION AND OVERVIEW

Dr. Kavi Mahesh,

PESIT, Bangalore

Textbook: Programming the World Wide Web

Robert W. Sebesta

4 th Edition Pearson Education

Introduction:

Internet and World-Wide Web

Internet History

Internet Protocols

Toolkit for Web Programming

Internet History:

The Internet originated in the form of ARPAnet in the late 1960s and early 1970s primarily for ARPA-funded research organizations. Later, BITnet and CSnet came up in the late 1970s and early 1980s. Email and file transfer for other institutions started with NSFnet in 1986 which initially connected five supercomputer centers. By 1990, it had replaced ARPAnet for non-military uses and became the network for all (by the early 1990s). NSFnet eventually became known as the Internet.

What is the Internet

A world-wide network of computer networks

At the lowest level, since 1982, all connections use TCP/IP

TCP/IP hides the differences among devices connected to the Internet

Internet Protocols:

Internet Protocol (IP) Addresses

Every node has a unique numeric address

Form: 32-bit binary number

New standard, IPv6, has 128 bits (1998)

Problem: By the mid-1980s, several different protocols had been invented (Telnet,

FTP, Usenet, mailto, …)

IP Addresses:

IP Addresses consist of four 8 bit numbers separated by periods. Organizations are assigned blocks

IP Addresses consist of four 8 bit numbers separated by periods. Organizations are assigned blocks of IP’s which in turn assign to machines that need internet access. Eg: 191.57.126.0 to 191.57.126.255.

Internet Protocols:

Domain names

Server-name portion of the URL is resolved into an IP address using the global, distributed Internet DB known as the domain name system, or DNS

First domain is the smallest; last domain is the largest.

The second domain name gives the domain of which the first domain is a part.

Last domain specifies the type of organization

DNS servers or name servers - convert fully qualified domain names to IPs

Eg: vtu.ac.in

vtu is hostname, which is a part of ac (academic) domain, which is a part of .in (India) domain.

All document requests from browsers are routed to the nearest name server.

Fully qualified domain names must be unique.

Hostname:

The hostname is the name of the server computer that stores the document. Note: URL’s can never have embedded spaces. Eg: If San Jose is a domain name, it must be typed as

San%20Jose.

The World Wide Web:

A possible solution to the proliferation of different protocols being used on the Internet

Origins

Tim Berners-Lee at CERN proposed the Web in 1989

Purpose: to allow scientists to have access to many databases of scientific work

Document form: hypertext

Pages? Documents? Resources?

We’ll call them documents

Hypermedia – more than just text – images, sound, etc.

Web or Internet:

The Web uses one of the protocols, http, that runs on the Internet--there are several others (telnet, mailto, etc.).

Client-Server:

Client-Server: • Clients and Servers are programs that communicate with each other over the Internet •

Clients and Servers are programs that communicate with each other over the Internet

A Server runs continuously, waiting to be contacted by a Client

Each Server provides certain services

Services include providing web pages

A Client will send a message to a Server requesting the service provided by that server

The client will usually provide some information, parameters, with the request

Web-based systems:

• Server

• Web server

• E.g., Apache or IIS

• Client

• Web browser

• E.g., IE, FireFox, …

Web Browser:

Browsers are clients - always initiate, servers react (although sometimes servers require responses)

Mosaic - NCSA (Univ. of Illinois), in early 1993

First to use a GUI, led to explosion of Web use

Initially for X-Windows, under UNIX, but was ported to other platforms by late 1993

Most requests are for existing documents, using HyperText Transfer Protocol (HTTP)

But some requests are for program execution, with the output being returned as a document

Web Server:

Provide responses to browser requests, either existing documents or dynamically built documents

Browser-server connection is now maintained through more than one request- response cycle

All communications between browsers and servers use Hypertext Transfer Protocol (HTTP)

Operation:

Operation: • Web servers run as background processes in the operating system. – Monitor a communications

• Web servers run as background processes in the operating system.

– Monitor a communications port on the host, accepting HTTP messages when they appear Note: Default port is 80

• Web servers have two main directories:

1. Document root (servable documents)

2. Server root (server system software)

• Document root is accessed indirectly by clients

– Its actual location is set by the server configuration file

– Requests are mapped to the actual location

• Virtual document trees, Virtual hosts, Proxy servers

• Web servers now support other Internet protocols

• Apache (open source, fast, reliable)

– Directives (operation control):

ServerName

ServerRoot

ServerAdmin,

DocumentRoot

Alias

Redirect

DirectoryIndex

UserDir

Proxy Server

The file structure of web server has 2 directives

Document root and server root.

The secondary areas from which documents can be served are called Virtual document trees.

Secondary hosts are called virtual hosts.

Some servers can serve documents that are in the document root of other machines called as PROXY SERVER.

Internet Information Server:

• IIS

- Operation is maintained through a program with a GUI interface

URL • General form: • scheme:object-address • The scheme is often a communications protocol, such

URL

General form:

scheme:object-address

The scheme is often a communications protocol, such as telnet or ftp

For the http protocol, the object-address is:

fully qualified domain name/doc path

For the file protocol, only the doc path is needed

Host name may include a port number, as in zeppo:80 (80 is the default)

URLs cannot include spaces or any of a collection of other special characters

(semicolons, colons,

)

The doc path may be abbreviated as a partial path

The rest is furnished by the server configuration

If the doc path ends with a slash, it means it is a directory

HyperText Transfer Protocol:

The protocol used by ALL Web communications. It has a Request Phase with a Form:

HTTP method domain part of URL HTTP ver. Header fields blank line Message body An example of the first line of a request:

GET /degrees.html HTTP/1.1

HTTP Methods:

GET - Fetch a document POST - Execute the document, using the data in body HEAD - Fetch just the header of the document PUT - Store a new document on the server DELETE - Remove a document from the server

HTTP Headers:

There are four categories of header fields: General, request, response and entity.

Common request fields: Accept: text/plain, Accept: text/*, If-Modified_since: date

Common response fields: Content-length: 488, Content-type: text/html

- Can communicate with HTTP without a browser

- > telnet blanca.uccs.edu http GET /respond.html HTTP/1.1 Host: blanca.uccs.edu

HTTP Response Form:

Status line Response header fields blank line Response body

Status line format:

HTTP version

status code

explanation

Status line format: HTTP version status code explanation Example: HTTP/1.1 200 OK (Current version is 1.1)

Example: HTTP/1.1 200 OK (Current version is 1.1) Status code is a three-digit number; first digit specifies the general status

Status Code

1 => Informational

2 => Success

3 => Redirection

4 => Client error

5 => Server error

HTTP Response: Example HTTP/1.1 200 OK Date: Tues, 18 May 2004 16:45:13 GMT Server: Apache (Red-Hat/Linux) Last-modified: Tues, 18 May 2004 16:38:38 GMT Accept-ranges: bytes Content-length: 364 Connection: close Content-type: text/html, charset=ISO-8859-1

Note: Both request headers and response headers must be followed by a blank line

Web Programmer’s Toolbox

Document languages and programming languages:

XHTML

Plug-ins

Filters

XML

Javascript

Java, Perl, Ruby, PHP

XHTML

XHTML • To describe the general form and layout of documents • XHTML document is a

To describe the general form and layout of documents

XHTML document is a mix of content and controls

Controls are tags and their attributes

Tags often delimit content and specify something about how the content should be arranged in the document

Attributes provide additional information about the content of a tag

Creating XHTML Documents

XHTML editors - make document creation easier

Shortcuts to typing tag names, spell-checker,

WYSIWYG XHTML editors

Need not know XHTML to create XHTML documents

Plugins and Filters

Plug ins

Integrated into tools like word processors, effectively converting them to WYSIWYG XHTML editors

Filters

Convert documents in other formats to XHTML

Advantages of both filters and plug-ins:

Existing documents produced with other tools can be converted to XHTML documents

Use a tool you already know to produce XHTML

Disadvantages of both filters and plug-ins:

XHTML output of both is not perfect - must be fine tuned

XHTML may be non-standard

You have 2 versions of the doc: difficult to synchronize

Multipurpose Internet Mail Extensions (MIME)

Originally developed for email

Used to specify to the browser the form of a file returned by the server (attached by the server to the beginning of the document)

Type specifications

Form:

type/subtype

Examples: text/plain, text/html, image/gif,

image/jpeg

MIME was developed to allow different kinds of documents to be sent using internet mail.

• Server gets type from the requested file name’s suffix (.html implies text/html) • Browser

Server gets type from the requested file name’s suffix (.html implies text/html)

Browser gets the type explicitly from the server.

Type/subtype. A list of MIME specifications is stored in the configuration files of every web server.

Overview of Toolkit

XHTML

XML

Javascript

Perl

Java

PHP

TCL, JSP, ASP.Net, etc.

XML

A meta-markup language

Used to create a new markup language for a particular purpose or area

Because the tags are designed for a specific area, they can be meaningful

No presentation details

A simple and universal way of representing data of any textual kind

JavaScript

A client-side HTML-embedded scripting language

Only related to Java through syntax

Dynamically typed and not object-oriented

Provides a way to access elements of HTML documents and dynamically change them

Java

General purpose object-oriented programming language

Based on C++, but simpler and safer

Our focus is on applets, servlets, and JSP

Perl

Provides server-side computation for HTML documents, through CGI

Perl is good for CGI programming because:

Direct access to operating systems functions

Powerful character string pattern-matching operations

Access to database systems

Perl is highly platform independent

Perl is not just for CGI

PHP

PHP • A server-side scripting language • An alternative to CGI • Similar to JavaScript •

A server-side scripting language

An alternative to CGI

Similar to JavaScript

Great for form processing and database access through the Web

Web Programming

• How is it different from regular programming?

• Client-Server architecture

• Browser is the client

• Server may be remote

• Stateless programming

• Event-driven programming

Client-Server Systems

• Server

• Stores data, files, content

• Takes input and requests from client

• Applies business logic to compute

• Sends results to client

• But, cannot contact client!

• Client

• Interacts with user

• Provides a GUI

• Accepts user input

• Validates input

• Displays results

• Interacts with server using a protocol

• Implications

• Program context in two possible parts

• Client-side and server-side

• Link may be broken

• Response may be delayed

• “world wide wait”

• Different platforms, etc.

Browser as GUI

• Implications

• Limited graphic abilities

• Easy to build GUI

• Many browsers

• Many versions

• Many idiosyncratic extensions

Implications of Remote Server

• Implications

• Cost of server loop

• E.g., validation of user input

• Client-side validation

• Populating lists, menus, etc. in browser

• E.g., auto-completion

• Pre-fetching of data: AJAX

Implications of Stateless Programming

• Implications

• Server does not maintain status

• Server cannot contact client!

• Session maintenance

• “Session expired”

• Client-side session data: unsafe!

Implications of Event-Driven Programming

• Implications

• Server cannot wait in a loop

• User may not respond as expected

• User may “navigate out” at any point!

• No well-defined control structure

out” at any point! • No well-defined control structure • User events trigger requests to servers

• User events trigger requests to servers

• Button click, menu selection, on-load, on-unload, etc.

Enterprise Web Applications

• 3-tier/4-tier architecture

• Web server

• Browser client

• Database server

• Applications server

• Applications server • Provides scalability by performing computations, data validations, session maintenance, etc.

• Provides scalability by performing computations, data validations, session maintenance, etc.

Security in Web Applications

Encryption

• HTTPS://

• Cookies, history, etc.

• Phishing

• Virtual keyboards

• Data security

• Security issues in B2B

Server-Side Programming

XHTML and XML

Perl and CGI

PHP

Java Server Pages/Servlets

ASP

ASP.Net / C#.Net / …

TCL

Running Server-Side Programs

CGI: one process per request

Containers and components

COM objects

.Net Run-time

Java Servlets

Java Beans / EJBs

Application Servers

Client-Side Programming

XHTML

Plug-ins

Filters

XML

Javascript

Flash, etc.

HTML: The Mother Tongue of the Web

Standard formatting language

Very simple

Highly portable

“Learn HTML in 21 Minutes’’

Need not know syntax

Simplification of SGML

Not extensible (only predefined tags)

Very forgiving: e.g., missing closing tags

No separation between data and rendering

Text structure:

<h1>, <table>, <p>, …

Rendering:

<b>, <em>, <style>, …

Inconsistent syntax?

<br> for new line

&nbsp; for space character

Database Access

ODBC / JDBC

Embed SQL statements in server-side code

DB login / connect string: security issue

Safer option: exec stored procedures

statements in server-side code • DB login / connect string: security issue • Safer option: exec
JavaScript and XHTML Prof. D. Krupesha, PESIT, Bangalore Why is JavaScript Important? It is simple

JavaScript and XHTML

Prof. D. Krupesha,

PESIT, Bangalore

Why is JavaScript Important? It is simple and lots of scripts available in public domain and easy to use. It is used for client-side scripting. It is important for web because it can promptly validate user input. It can update the web page without post back to server. It allows page to react to user actions other than pushing a “submit” button more interactively.

It increases Server efficiency. Since the client processes the script, which saves internet time and server time. Web pages can contain JavaScript programs executed inside the browser.

It is supported by all major browsers. User may disable JavaScript due to security reasons.

What is JavaScript? An interpreted scripting language for web. It was introduced by Netscape with Netscape 2.0 in 1995. Microsoft version is called Jscript. Language is case- sensitive. It can be embedded within HTML tags or separately. Tightly integrated with browser. It can handle many types of events generated by the normal interaction between user and browser.

When not to use JavaScript? When you need to access other resources such as:

- Files

- Programs

- Databases.

When you are using sensitive or copyrighted data or algorithms.

Java versus JavaScript

Java supports OOP. JavaScript does not support OO software development paradigm Java is strongly-typed. JavaScript is dynamically-typed. JavaScript syntax is same as java. Constructs like expressions, assign statements and control statements are same as in Java.

Where to place JavaScript code?

1.

Inline JavaScript It can be placed on the event handler attributes of input controls of a form.

2. Internal / Embedded JavaScript It can be enclosed in script tags either in the

2. Internal / Embedded JavaScript It can be enclosed in script tags either in the header or the document body. 3. External JavaScript It can be placed in a separate file. Enclosed in script tags in the header with ‘src’ attribute. This method is good for maintenance due to modularization.

How is JavaScript executed? It is almost always executed at client-side. Script tags in the header are executed in the order in which they appear, before any of the body is processed.

Script tags in the body are executed as the body is rendered.

Script in the event handlers are executed whenever the appropriate event occurs. Script in functions executed triggered by browser events. - built-in java script - user-defined functions (declared in the header)

All properties are visible to all scripts ( no information hiding). Global variables are properties of the Window object. There can be more than one Window object. Global variables depend on which Window is the context. The Document object represents the document displayed.

Why DOM?

Portability is the major issue while using the JavaScript. The standard DOM has to

provide a specification that would make Java programs and JavaScript scripts that deal with XHTML documents portable among various browsers. DOM Levels

• DOM 0: informal, early browsers

• DOM 1: XHTML/XML structure

• DOM 2: event model, style interface, traversal

• DOM 3: content model, validation

DOM specifications describe an abstract model of a document.

• Interfaces describe methods and properties

• The interfaces describe a tree structure

• Different languages will bind the interfaces to specific implementations

The internal representation may not be tree-like. In JavaScript, data are represented as properties and operations as methods. Nodes of the tree will be JavaScript objects.

Attributes of elements become named properties of element node objects.

• <input type=“text” name=“address”>

The object representing this node will have two properties. Type property will have value “text” and name property will have value “address”.

The following XHTML document and its corresponding DOM tree illustrate the relationship between them. <html

The following XHTML document and its corresponding DOM tree illustrate the relationship between them.

<html xmlns = http://www.w3.org/1999/xhtml> <head> <title> A simple document</title> </head> <body> <table> <tr> <th> Breakfast</th> <td>0 </td> <td>1 </td> </tr> <tr> <th> Lunch</th> <td>1 </td > <td> 0 </td> </tr> </table> </body> </html>

Elements in XHTML document correspond to objects in JavaScript. Objects can be addressed in several ways:

1. forms and elements array defined in DOM 0.

• Individual elements are specified by index.

• The index may change when the form changes.

2. Using the name attributes for form and form elements

• A name on the form element causes validation problems.

• Names are required on form elements providing data to the server.

3. Using getElementById with id attributes.

• id attribute value must be unique for an element.

Consider this simple form:

<form action = ""> <input type ="button“ name = “pushMe"> </form> The input element can be referenced as document.forms[0].element[0].

• All elements from the reference element up to, but not including, the body must have a name attribute.

• This violates XHTML standards in some cases. Example:

<form name = "myForm" action = ""> <input type ="button“ name="pushMe"> </form>

• Referencing the input

document.myForm.pushMe

• Set the id attribute of the input element <form action = ""> <input type="button" id=“turnItOn"> </form>

• Then use getElementById

document.getElementById(“turnItOn")

use getElementById document.getElementById(“turnItOn") Event-driven Programming involves execution based on

Event-driven Programming involves execution based on user’s action. (ex: User’s selection in a web page.)

Event-driven Programming: Instead of user synchronizing with the program, the

program synchronizes with, or reacts to, the user. All communication from user occurs via events. An event is an action that happens in the system. For example,

- A mouse button pressed or released

- A keyboard key is hit

- A window is moved, resized, closed, etc.

Event-driven Programming: Typically two different classes of events.

1. User-initiated events

Events that result directly from a user action. e.g., mouse click, button press, move mouse. 2. System-initiated events Events created by the system, as it responds to a user action e.g., scrolling text, re-drawing a window.

There is no top-down flow of control, i.e., Main program defining the sequential Flow. Code fragments are associated with events and invoked when events occur. The order of execution is decoupled with the code. Don’t have to deal with order of events. This is especially helpful when the order is unknown!

Event-driven programming is a style of programming in which pieces of code, event handlers, are written to be activated when certain events occur.

Events represent activity in the environment including, especially, user actions such as moving the mouse or typing on the keyboard.

An event handler is a program segment designed to execute when a certain event occurs. Events are represented by JavaScript objects. Registration is the activity of connecting a script to a type of event. Assign an event attribute an event handler. Assign a DOM node an event handler.

Event

Tag Attribute

blur

onblur

change

onchange

click

onclick

focus

onfocus

load

onload

mousedown

onmousedown

mousemove

onmousemove

mouseout

onmouseout

mouseover

onmouseover

mouseup

onmouseup

select

onselect

submit

onsubmit

unload

onunload

onselect submit onsubmit unload onunload Particular events are associated to certain attributes. The

Particular events are associated to certain attributes. The attribute for one kind of event may appear on different tags allowing the program to react to events affecting different components. A text element gets focus in three ways:

• When the user puts the mouse cursor over it and presses the left button

• When the user tabs to the element

• By executing the focus method Losing the focus is blurring.

Using an attribute, a JavaScript command can be specified:

<input type=“button” name=“myButton” onclick= “alert(‘You clicked the button!’)”/>

A function call can be used if the handler is longer than a single statement. <input type=“button” name=“myButton” onclick=“myHandler()”/>

An event can be registered for this tag in two ways:

<input type=“button” name=“freeOffer” id=“freeButton”/>

• Using an event attribute <input type=“button” name=“freeOffer” id=“freeButton” onclick=“freeButtonHandler()”/>

• Assigning to a property of the element node

document.getElementById(“freeButton”).onclick = freeButtonHandler

– Note that the function name, a reference to the function, is assigned.

– Writing freeButtonHandler() would assign the return value of the function call as the handler (possible, but unlikely).

Note that the no parameters are passed to the function when called by the JavaScript System. The handler code must identify the element that caused the call.

The handler call can be enclosed in an anonymous function – dom.elements[0].onclick = function() {planeChoice(152)};

The handler call can be enclosed in an anonymous function

– dom.elements[0].onclick = function() {planeChoice(152)};

Assigning to an attribute is more flexible, allowing passing parameters without having to create an anonymous function. Assigning to a node property helps separate HTML and code. Assigning to a node property allows reassignment later if the handler needs to be changed.

By manipulating the focus event the user can be prevented from changing the amount in a text input field. This is possible to work around:

– Copy the page but leave out the validation code.

– Simulate an HTTP request directly with socket-level programming.

– If the validity of data is important, the server needs to check it.

Validating data using JavaScript provides quicker interaction for the user. Validity

checking on the server requires a round-trip for the server to check the data and then to respond with an appropriate error page. Handling a data validity error:

– Put the focus in the field in question

– Highlight the text for easier editing

If an event handler returns false, default actions are not taken by the browser. This

can be used in a Submit button event handler to check validity and not submit if there are problems. The name is First, Last, Middle-Initial, each part capitalized.

– /^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/

The phone is ddd-ddd-dddd where d is a digit.

– /^\d{3}-\d{3}-\d{4}$/

Each pattern uses the ^ and $ anchors to make sure the entire string matches.

DOM 2 is defined in modules.

The Events module defines several sub modules.

– HTML Events and Mouse Events are common.

An event object is passed as a parameter to an event handler.

– Properties of this object provide information about the event.

– Some event types will extend the interface to include information relevant to the subtype. For example, a mouse event will include the location of the mouse at the time of the event.

DOM 2 defines a process for determining which handlers to execute for a particular event. The process has three phases:

The event object representing the event is created at a particular node called the target node. In the capturing phase each node from the document root to the target node, in order, is examined.

– If the node is not the target node and there is a handler for

– If the node is not the target node and there is a handler for that event at the node and the handler is enabled for capture for the node, the handler is executed. Then all handlers registered for the target node, if any, are executed.

In the bubbling phase each node from the parent of the target node to the root node, in order, is examined.

– If there is a handler for that event at the node and the handler is not enabled for capture for the node, the handler is executed.

– Some event types are not allowed to bubble: load, unload, blur and focus among the HTML event types.

As each handler is executed, properties of the event provide context.

– The currentTarget property is the node to which the handler is registered.

– The target property is the node to which the event was originally directed.

One major advantage of this scheme over DOM 0 is that event handling can be

centralized in an ancestor node.

For example, a calculator keyboard will have a number of digit buttons.

– In some GUI frameworks, a handler must be added to each button separately.

– In DOM 2, the buttons could be organized under a single node and the handler placed on the node.

As each handler is executed, properties of the event provide context.

– The currentTarget property is the node to which the handler is registered

– The target property is the node to which the event was originally directed Handlers are called listeners in DOM 2.

addEventListener is used to register a handler, it takes three parameters.

– A string naming the event type,

– The handler,

– A Boolean specifying whether the handler is enabled for the capture phase or not.

The navigator object indicates which browser is being used to view the XHTML document. The appName property of the navigator object gives the name of the browser. The appVersion property of the navigator object gives the browser version. Each element in an XHTML document has a corresponding ELEMENT object in the DOM representation. The ELEMENT object has methods to support.

– Traversing the document, that is, visiting each of the document nodes.

– Modifying the document.

For example, removing and inserting child nodes. Various properties of Element objects are related nodes. parentNode references the parent node of the Element. previousSibling and nextSibling connect the children of a node into a list. firstChild and lastChild reference children of an Element. These would be text nodes or element nodes contained in the Element.

The insertBefore(newChild, refChild) method places the newChild node before the refChild node. The replaceChild(newChild,

The insertBefore(newChild, refChild) method places the newChild node before the refChild node. The replaceChild(newChild, oldChild)method places the oldChild node with the newChild node.

The removeChild(oldChild) method removes oldChild node from the DOM structure. The appendChild(newChild) method adds the given node to the end of the list of the siblings of the node through which it is called.

The highest levels of the execution environment of client-side JavaScript are represented with the Window and Document objects.

The Document object includes a forms array property, which includes references to all forms in the document. Each element of the forms array has an elements array, which includes references to all elements in the form.

The DOM is an abstract interface whose purpose is to provide language independent way to access the elements of an XHTML document.

XHTML tags are represented in JavaScript as objects, tag attributes are represented as properties.

Dynamic Documents wih JavaScript Introdcution Dynamic XHTML is not a technology in and of itself,

Dynamic Documents wih JavaScript

Introdcution

Dynamic XHTML is not a technology in and of itself, but rather is a combination of three technologies: XHTML, Cascading Style Sheets (CSS) and Scripting. It usually involves using scripting like JavaScript to change tag attribute, tag contents or CSS property of an XHTML element . In modern browsers, most CSS properties can be modified dynamically ie changes can be made after the document has been and is still being displayed . This can be done by changing an individual style of element (using the style property of the element) or by changing the class name assigned to the element (using the className property).

Advantages of Dynamic XHTML

(1) Dynamic XHTML makes documents dynamic. Dynamic documents :

o

Allow the designer to control how the HTML displays Web pages’ content.

o

React and change with the actions of the visitor.

o

Can exactly position any element in the window, and change that position after

the document

o Can hide and show content as needed.

has loaded.

(2) Dynamic XHTML allows any HTML element (any object on the screen that can be controlled independently using JavaScript) to be manipulated at any time, turning plain HTML into dynamic HTML (3) With DHTML, changes occur entirely on the client-side (4) Using DHTML gives the author more control over how the page is formatted and how content is positioned on the page

Positioning Elements

Cascading Style Sheets (CSS) Positioning defines the placement of elements on a page and is an extension of cascading style sheets as specified in the W3C on Positioning HTML with CSS. By default, elements flow one after another in the same order as they appear in the HTML source, with each element having a size and position that depends on the type of element, the contents of the element, and the display context for the element as it will render on the page. This default flow model for HTML layout doesn't allow a high level of control over the placement of elements on the page. By applying a small set of CSS attributes to the elements that are defined for the page, CSS can control the precise position of elements by giving exact coordinates. It is also possible to specify placement relative to the position of other objects on the page.

Just like any other HTML or CSS attribute, the CSS attributes used to control an element's position are available for scripting. The position of these elements on the page can thus be dynamically changed with script. As a result, the position of these elements

can be recalculated and redrawn after the document is loaded without reloading the page from

can be recalculated and redrawn after the document is loaded without reloading the page from the server. It usually involves using JavaScript to change a positioning style properties of an HTML elements. position, top, left are the three properties that dictate the position of the elements. position specifies the reference point for the placement of the elements. top and left specify the distance from top and left of reference point where element is to appear. absolute, relative and static are the three possible values for the position property.

Absolute Positioning

A element can be placed at specific position in the document using absolute value for the position styling property. Absolute positioning defines the x and y coordinates of an element with reference to the top left corner of the browser page or the containing block and the position attribute is set to absolute. With absolute positioning elements are placed without regard to the positions of other elements. For example, if you want place an image 100 pixels from the top and 100 pixels from the left of the document display window, it can be placed as following statements:

<img src="earth.jpg" style="position:absolute; left:100px; top:100px" />

Use of Absolute positioning

Places elements at specific position in the document display.

Can be used superimpose text over the ordinary text to create effect similar that watermark on page. The following example illustrates the usage of absolute positioning to position five elements at specific different positions in the document display.

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<! - - abpos.html - - >
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Absolute positioning </title>
<style type = "text/css">
.s1 {position: absolute; top: 45px; left: 50px; }
.s2 {position: absolute; top: 45px; left: 300px; }
.s3 {position: absolute; top: 175px; left: 50px; }
.s4 {position: absolute; top: 175px; left: 300px; }
.s5 {position: absolute; top: 100px; left: 175px; }
</style>
</head>
<body>
<p>Positioning 5 instances same image at 5 different positions
<img class="s1" src="smiley.gif" />
<img class="s2" src="smiley.gif" />
<img class="s3" src="smiley.gif" />
<img class="s4" src="smiley.gif" />
<img class="s5" src="smiley.gif" />
Output </p>
</body> </html>
/> Output </p> </body> </html> When an element is absolutely positioned inside another

When an element is absolutely positioned inside another positioned element, the top and left property values are measured from the upper-left corner of the enclosing element. The following example illustrate the nested element placement. When an element is absolutely positioned inside another positioned element, the top and left property values are measured from the upper-left corner of the enclosing element.

The following example illustrate the nested element placement

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"> < -- nestedap.html --> <head> <body> <div id="someDiv" style="position:absolute; left:100px; top:50px"> Hello. <span id="someSpan" style="position:absolute; left:10px; top:30px"> Hello, again!!!!!. </span> And now it's time to say goodbye. </div> </body> </html>

Output

Hello. And now it's time to say goodbye Hello, again!!!!!.

In the above example we insert a span element inside the div element. Positioning attributes for the span element place it 10 pixels in from the left and 30 pixels down from the top of its positioning context—the div element in this case.

Relative Positioning

Relative positioning means an element is placed relative to its natural position in the document's flow. When you use relative positioning, an element is positioned relative to where it would regularly be. If the top and left properties are given, then relative positioning displace the element by the specified amount from the natural position.

The top property defines how far from the top of its usual position we want the top of element to appear. If we use a positive value, then our element is moved down from the usual position, whereas a negative value would move our element up from the usual position.

The left property defines how far from its usual position we want the left of our element to appear. Positive values will move the element right, and negative values will move it left the usual position.

If the top and left properties are not specified then element is positioned as if like the it is statically positioned. However, such an element can be moved later.

Relative positioning is used for creating different effects in the document. It can be used to highlight the special words in the text. The following example highlight the word “red” in line of text.

Output

Output <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
Output <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!—relative.html -- > <html xmlns = "http://www.w3.org/1999/xhtml"> <body style = "font-family: Times; font-size: 24pt;"> <p> Roses are <span style = "position: relative; top: 10px; font-family: Times; font-size: 48pt; font-style: italic; color: red;"> red </span> in color. </p> </body> </html>

Roses are red in color.

Relative positioning can be used to create superscripts. For example the following can be used to place “xyz” 10 pixels above the natural baseline of the text.

<p> The superscript in this name<span style=”position: relative; top:-3px” > xyz </span> is “xyz”.</p>

Static Positioning

'Static' positioning is identical to normally rendered HTML. These elements cannot be positioned or repositioned, nor do they define a coordinate system for child elements. This is the default value for 'position', except for the <BODY> element, which, while it cannot be positioned, does define a coordinate system for child elements.

Moving Elements

Dynamic movement of 'relative'ly /’absolute’ly positioned elements can provide animation effects in scripting environments. Element position is going to be changed by modifying the left and top properties of the element's style property. If position is set to absolute, the element moves to the new values of top and left, if its position is set to relative, it moves from its original position by distances given by the new values of top and left. The following example demonstrates this

</head> <body onload="init();"> <form> <input type="button"
</head> <body onload="init();"> <form> <input type="button"
</head>
<body onload="init();">
<form>
<input type="button" value="Left" onclick="moveH('divBlock',-10);">
<input type="button" value="Right" onclick="moveH('divBlock',10);">
<input type="button" value="Up" onclick="moveV('divBlock',-10);">
<input type="button" value="Down" onclick="moveV('divBlock',10);">
</form>
<div id="divBlock"></div>
</body>
</html>

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"> <! – move.html -- > <title>Position</title> <style type="text/css"> #divBlock { position:relative;

height:100px;

width:100px;

top:100px;

left:100px;

background-color:red;

}</style>

<script type="text/javascript"> function init(){ document.getElementById("divBlock").style.top = "100px"; document.getElementById("divBlock").style.left = "100px";

}

function moveH(elem, distance){ var objElem = document.getElementById(elem); var curLeft = parseInt(objElem.style.left);

objElem.style.left = (curLeft + distance) + "px";

}

function moveV(elem, distance){ var objElem = document.getElementById(elem);

var curTop = parseInt(objElem.style.top); objElem.style.top = (curTop + distance) + "px";

}

</script>

curTop = parseInt(objElem.style.top); objElem.style.top = (curTop + distance) + "px"; } </script> 26

Output

Output In the output user can move the square in the 4 different directions by clicking
Output In the output user can move the square in the 4 different directions by clicking

In the output user can move the square in the 4 different directions by clicking the appropriate button.

The init() function set the top and left properties of the divBlock div, thus making the properties accessible to JavaScript.

The moveH() function uses parseInt() to cut off the units (e.g, px) from the value of the left property of the div and assign the resulting integer to the curLeft variable. It then modifies the left property of the element by adding the value passed in for distance.

The moveV() function does the same thing, but it modifies the top property rather than the left property.The functions are triggered with onclick event handlers.

Element Visibility

Document elements can be specified to be visible or hidden with the values if their visibility property. The two possible values for the visibility are – visible and hidden.

The following example displays the 4 table elements and allows the user to toggle each table element causing the element to appear and disappear in the document display.

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Showing and Hiding Elements with JavaScript</title> </head> <!—vis.html --> <script type="text/javascript">

function changeVisibility(TR){ if (document.getElementById(TR).style.visibility=="hidden") { document.getElementById(TR).style.visibility = "visible"; } else { document.getElementById(TR).style.visibility = "hidden";

}

}

</script> <body> <h1>Hiding and Showing Elements</h1> <table > <tr id="tr1"><td>tableElem Row 1</td></tr> <tr id="tr2"><td>tableElem Row 2</td></tr> <tr id="tr3"><td>tableElem Row 3</td></tr> <tr id="tr4"><td>tableElem Row 4</td></tr> </table> <form>

<h2>visibility</h2>

<input type="button" onclick="changeVisibility('tr1')" value="TR1"> <input type="button" onclick="changeVisibility('tr2')" value="TR2"> <input type="button" onclick="changeVisibility('tr3')" value="TR3"> <input type="button" onclick="changeVisibility('tr4')" value="TR4"> </form> </body> </html>

Output

Changing Colors and Fonts The background and foreground colors of the document display and font
Changing Colors and Fonts The background and foreground colors of the document display and font

Changing Colors and Fonts

The background and foreground colors of the document display and font properties of the text can be changed dynamically.

Changing the Color

Document colors can be set dynamically, although it is questionable whether this is a good idea. Your colors were chosen because they best presented your page contents. If, though, you wish to provide color alternatives, you can make these colors user selectable. In the following example, a range of background and foreground colors can be chosen by clicking radio buttons.

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"> <!—color.html -- >

<head>

<script type="text/javascript">

function ChangeBackground(Color) {

document.body.style.backgroundColor = Color

}

function ChangeForeground(Color) {

document.body.style.color = Color

}

</script>

</head> <body> <P class=head2>Scripting Document Colors</P> <P>Some of these document properties have style sheet equivalents. For instance,the <SPAN class=code><B>bgColor</B></SPAN> and <SPAN class=code><B>fgColor</B></SPAN> properties are equivalent to the <SPAN class=code>background-color</SPAN> and <SPAN class=code>color</SPAN> style properties, respectively. Still, it is always preferable to use CSS style properties when scripting style changes for compatibility with standards.</P><P>Document colors can be set dynamically, although it is questionable whether this is a good idea. Supposedly, your colors were chosen because they best presented your page contents. If, though, you wish to provide color alternatives, you can make these colors user selectable. In the following example, a range of background and foreground colors can be chosen by clicking radio buttons.</P>

(continued on next page)

<b>Background Color:</b><br/> <input type="radio" name="BG"

<b>Background Color:</b><br/> <input type="radio" name="BG" onclick="ChangeBackground('red')"/>Red <input type="radio" name="BG" onclick="ChangeBackground('green')"/>Green <input type="radio" name="BG" onclick="ChangeBackground('blue')"/>Blue <input type="radio" name="BG" onclick="ChangeBackground('black')"/>Black <input type="radio" name="BG" onclick="ChangeBackground('white')"/>White

<br/><br/> <b>Foreground Color:</b><br/> <input type="radio" name="FG" onclick="ChangeForeground('red')"/>Red <input type="radio" name="FG" onclick="ChangeForeground('green')"/>Green <input type="radio" name="FG" onclick="ChangeForeground('blue')"/>Blue <input type="radio" name="FG" onclick="ChangeForeground('black')"/>Black <input type="radio" name="FG" onclick="ChangeForeground('white')"/>White </body> </html>

In the above example functions ChangeBackground( ) and ChangeForeground( ) are called whenever user clicks the radio buttons of different colors to change the background and foreground color of the document respectively.

Changing font

Web users are accustomed to having links in documents change color when the cursor is placed over them. Any property of a link can be changed by using the mouse event, ‘ mouseover ‘ to trigger JavaScript event handlers. Thus the font style and font size, as well as the color, can be changed when the cursor is placed over a link. The link can be changed back to its original form when an event handler is triggered with the ‘ mouseout ‘event. In the following example, the only element is a sentence with an embedded link. The foreground color for the document is the default black. The link is presented in blue. When the mouse cursor is placed over the link, its color changes to red and its font style changes to italic.

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!-- link.html --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Dynamic fonts for links </title> <style type = "text/css"> .regText {font: Times; font-size: 16pt;}

</head> <body> <p class = "regText">The subject <a style = "color: blue;" onmouseover = "this.style.color = 'red'; this.style.font = 'italic 16pt Times';" onmouseout = "this.style.color = 'blue'; this.style.font = 'normal 16pt Times';"> Web Programming </a> is very interesting </p> </body> </html>

</style>

31

Output

Output Display of link,html with the cursor not over the link The subject Web Programming Is

Display of link,html with the cursor not over the link

The subject Web Programming Is very interesting

Display of link,html with the cursor over the link

The subject Web Programming Is very interesting

Dynamic Content

Using JavaScript we can change the content of the different document elements like contents of text box, document title , table contents dynamically. In the following example HTML tables can be created and manipulated dynamically with JavaScript. Each table element contains a rows array and methods for inserting and deleting rows:

insertRow() and deleteRow(). Each tr element contains a cells array and methods for inserting and deleting cells: insertCell() and deleteCell(). The following example shows how these objects can be used to dynamically create HTML tables.

The body of the page contains a table with an id of formName. The table contains a single row of headers.

Below the table is a form that allows the user to enter a first and last name. When the "Add Name" button is clicked, the addRow() function is called and passed in the id of the table (tblPeople) and a new array containing the user-entered values.

The addRow() function uses the insertRow() method of the table to add a new row at the end of the table and then loops through the passed-in array, creating and populating one cell for each item. The function also returns the new row. Although the returned value isn't used in this example, it can be useful if you then want to manipulate the new row further.

The above example display the document with empty table. Whenever user press the Add Name button a new row is added to the table.

33
33
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

< ! -- dynamic.html -- > <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Manipulating Tables</title>

<script type="text/javascript"> function addRow(tableId, cells){ var tableElem = document.getElementById(tableId); var newRow = tableElem.insertRow(tableElem.rows.length); var newCell; for (var i = 0; i < cells.length; i++) { newCell = newRow.insertCell(newRow.cells.length); newCell.innerHTML = cells[i];

}

return newRow;

}

</script>

</head>

<body> <table id="tblPeople" border="1"> <tr> <th>First Name</th> <th>Middle Name</th> <th>Last Name</th> </tr> </table> <hr> <form name="formName"> First Name: <input type="text" name="FirstName"> Middle Name: <input type="text" name="MiddleName"> Last Name: <input type="text" name="LastName"> <br /> <br /> <center><input type="button" value="Add Name" onclick="addRow('tblPeople', [this.form.FirstName.value,this.form.MiddleName.value, this.form.LastName.value] );"> </center> <hr> </form> </body> </html>

Stacking Elements The multiple elements can occupy the same space in the document, one is

Stacking Elements

The multiple elements can occupy the same space in the document, one is considered to be on top and is displayed. The top element hides the parts of the lower elements on which it is imposed. When multiple elements occupy the same space on the document, then comes the question of which element is to be placed on the top of other elements. So for this we have to consider the third dimension of the document. Although the display is restricted to two dimensions, the effect of the third dimension is possible through the concept of stacked element. The placement of element in this third dimension is controlled by the z-index attribute of element. An element whose z-index is greater than that of element in the same space will be displayed over the other element, effectively hiding the element with smaller z-index value. The JavaScript property associated with the z-index attribute is zIndex.

In the following example, three images are placed on the display so that they overlap. In XHTML description of this, each image tag includes an onclick attribute, which is used to trigger the execution of JavaScript handler function. First the function defines DOM addresses the last top element and the new top element. Then the function sets the zIndex value of the two elements so that the old top element has the value of 0 and the new top element has the value 10, effectively putting it at the top. The script keeps track of which image is currently on top with the global variable top, which is changed every time a new element is moved to the top with the toTop function.

This example displays all 3 overlapping images. Whenever user clicks on the particular image,that image will be displayed on top of other two images.

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">

<! – satck.html -->

<head>

<title> Dynamic stacking of images </title>

<script type = "text/javascript"> var top = "i1"; function toTop(newTop) { domTop = document.getElementById(top).style; domNew = document.getElementById(newTop).style; domTop.zIndex = "0"; domNew.zIndex = "10"; top = newTop;

}

</script>

35

<style type = "text/css"> .img1 {position: absolute; top: 0; left: 0; z-index: 0;} .img2 {position:

<style type = "text/css">

.img1 {position: absolute; top: 0; left: 0; z-index: 0;}

.img2 {position: absolute; top: 50px; left: 110px;

z-index: 0;}

.img3 {position: absolute; top: 100px; left: 220px; z-index: 0;} </head> <body>

</style>

<p>

<img class = "img1" id = "i1"

src = "image1.jpg"

onclick =

"toTop('i1')" /> <img class = "img2" id = "i2" "toTop('i2')" />

src = "image2.jpg"

onclick =

<img class = "img3" id = "i3" "toTop('i3')" />

src = "image3.jpg"

onclick =

</p>

</body>

</html>

= </p> </body> </html> Locating the Mouse Cursor An event is a notification about

Locating the Mouse Cursor

An event is a notification about something specific that has occurred because of browser user action, such as mouse click on a form button, radio button etc. Strictly speaking event is an object that is implicitly created by the browser and the JavaScript system in response to something happened. Event object includes information about the event. For example mouse-click is one such event. Whenever user mouse-click on the document, event object is created which includes information like where and on which element event has occurred. A mouse-click event defines two pairs of properties that give geometric coordinates of the position of the element in the display that created the event. One pair of the coordinates, clientX and clientY gives the coordinates of the document display relative to the upper-left corner of the browser display window, in pixels. The other pair, screen and screenY gives coordinates of the element but relative client computer’s screen.

In the following example, every time user clicks the mouse button an alter box displays the clientX, clientY, screenX and screen coordinates. The handler show_coords with event as parameter is triggred by the onclick attribute of the body element.

coordinates. The handler show_coords with event as parameter is triggred by the onclick attribute of the
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!—mouse.html -- > <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> function show_coords(event)

{

x=event.clientX; y=event.clientY;

x1=event.screenX;

y1=event.screenY;

alert("ClientX coords: " + x + ", ClientY coords: " + y + ",ScreenX coords:

" + x1 + ", ScreenY coords: " + y1);

}

</script>

</head>

<body onclick="show_coords(event)"> <p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html>

of the cursor.</p> </body> </html> Reacting to a Mouse Click In the following example mousedown

Reacting to a Mouse Click

In the following example mousedown and mouseup events are used to show and hide the image on the display under the mouse cursor whenever the mouse button is clicked. Whenever user clicks the mouse button ie. onmousedown event handler displayIt( ) is called with event as parameter and whenever user leaves the mouse button ie. onmouseup event handler hideIt() is called.

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!—reacting.html Display a image when the mouse button is pressed,

--> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Sense events anywhere </title>

= "http://www.w3.org/1999/xhtml"> <head> <title> Sense events anywhere </title> 37

37

<script type = "text/javascript"> function displayIt(evt) { var dom =
<script type = "text/javascript"> function displayIt(evt) { var dom =

<script type = "text/javascript"> function displayIt(evt) { var dom = document.getElementById("image"); dom.style.left = (evt.clientX - 30) + "px"; dom.style.top = (evt.clientY - 25) + "px"; dom.style.visibility = "visible";

}

function hideIt() { document.getElementById("image").style.visibility = "hidden";

}

</script> </head> <body onmousedown="displayIt(event);" onmouseup = "hideIt();"> <div id= "image" style = " visibility: hidden; position: relative"> <img src = "smiley.gif" /> </div> </body> </html>

Slow Movements of Elements

With JavaScript we can not only move the elements instantly, we can also move element slowly from one place to another. The one way to move an element slowly is to move it by small amount many times, with moves separated by small amounts of time. Such slow movement of elements is accomplished by using two window methods available in JavaScript: setTimeout and setInterval.

The setTimeout method has two parameters -- first one is string of JavaScript code to be executed and second parameter is number of mseconds of delay before executing the given script.

The setInterval method has two forms. One takes two parameter with first specifying the script code to be executed and second specifying the interval in mseconds between executions. The second form takes variable number of parameters. First one is the name of the function to be called, the second is the interval in mseconds between the calls to the function and remaining parameter are used as actual parameters to the function being called.

In the following example, image is moved slowly from position(50,100) to a new position (700,100). The move is accomplished by using the setTimeout method to call a

move function every msecond until the final position is reached. Example includes separate html file

move function every msecond until the final position is reached. Example includes separate html file and JavaScript file.

Initial position of the element is set with initImage( ) function. The onload attribute of the body element is used to call this function.

The moveImage( ) function is used to move the image. It moves the image 1 pixel towards the final position and then calls itself with the new coordinates using the setTimeout.

/* moveImage.js JavaScript to move image*/

var dom, x, y, finalx = 700;

function initImage() { dom = document.getElementById('image').style;

/* Get the current position of the image */ var x = parseInt(dom.left); var y = parseInt(dom.top);

/* Call the function that moves it */ moveImage(x, y);

}

// A function to move the text from its original

// position to (x, finaly)

function moveImage(x, y) {

/* If the x coordinates are not equal, move x toward finalx */

if (x != finalx) x++;

if ((x != finalx) ) {

dom.left = x + "px"; dom.top = y + "px";

/* Recursive call, after a 1-millisecond delay */

setTimeout("moveImage(" + x + "," + y + ")", 1);

}

}

call, after a 1-millisecond delay */ setTimeout("moveImage(" + x + "," + y + ")", 1);

39

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!-- Illustrates a moving image from one position to another Uses the JavaScript from file moveimage.js --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Moving Image </title>

<script type = "text/javascript"

src = "moveimage.js">

</script> </head> <body onload = "initImage()"> <p> <span id = 'image' style = "position: absolute; left: 50px; top: 100px"> <img src = "smiley.gif" /> </span> </p> </body> </html>

Dragging and Dropping Elements

One of more powerful effects of event handling is allowing the user to drag and drop elements around the display screen. The mouseup, mousedown and mousemove events can be used implement this. By changing the left and top properties, element can be move from one place to another. To illustrate drag and drop, we develop an example that allows the user to drag and drop a rectangle box. In this first we create a box that is to be moved around in document display. There three different handlers for mouseup, mousedown and mousemove events. The mousedown event handler mouseD, takes the event as its parameter. It gets the element to be moved and puts it in global variable so that it is available to the other handlers. Then it determines the coordinates of the current position of the element to be moved and computes the difference between them and the coordinates of the position of the mouse cursor. These two differences , which are used by the handler for mousemove to actually move the element.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Drag and drop</title> <style type="text/css"> body {

background-color: #fff; margin: 0;

p {

}

margin: 80px 0 0 100px;

}

#dObject { border: 2px solid;

border-color: #6c0 #170 #170 #6c0; background-color: red; width: 40px; height: 40px; padding: 0.5em 0.8em; position: absolute; text-align: center; display: none; cursor: default;

}

</style>

<script type="text/javascript">

var dragObject, offsetX, offsetY, isDragging=false; window.onload = init; document.onmousemove = mouseM; document.onmouseup = mouseU;

function init() { var ob = document.getElementById("dObject");

ob.style.left="100px";

ob.style.top="100px";

ob.style.display="block";

}

41

function mouseD(ob,e) { dragObject = ob; if (window.event) e=window.event; var dragX = parseInt(dragObject.style.left);

function mouseD(ob,e) { dragObject = ob; if (window.event) e=window.event;

var dragX = parseInt(dragObject.style.left); var dragY = parseInt(dragObject.style.top); var mouseX = e.clientX; var mouseY = e.clientY;

offsetX = mouseX - dragX; offsetY = mouseY - dragY; isDragging = true;

return false;

}

function mouseU() { if (!isDragging) return; isDragging = false; return false;

}

function mouseM(e) { if (!isDragging) return;

if (window.event) e=window.event;

var newX = e.clientX - offsetX; var newY = e.clientY - offsetY;

dragObject.style.left = newX + "px"; dragObject.style.top = newY + "px";

return false;

}

</script> </head> <body> <p style="position:absolute;left:300px"> Drag and Drop the Box </p> <div id="dObject" onmousedown="mouseD(this,event)"></div> </body> </html>

PERL

PERL PERL is acronym for “Practical Extraction and Report Language”. It is developed by Larry Wall

PERL is acronym for “Practical Extraction and Report Language”. It is developed by Larry Wall in 1987. It is similar to Shell script but lot easier and more akin to the high end programming. It is originally intended to combine and extend the processing functions of several UNIX utilities including awk, sed, grep and sh.

Applications of PERL: PERL can be used anywhere you parse or manipulate text like web servers (CGI scripts), database access and processing. It can also be used anywhere you want to automate file handling and organization. It is generally not the first choice for numeric calculations.

PERL is a semi-interpreted scripting language. Because it uses byte-code representation like Java. But it doesn't store byte code for later re-use.

Advantages: No need to compile and make files. Disadvantages: It can be slower running, not type-safe.

Features of PERL: PERL enables quick development of programs.

no need to define variable types

portable

extensible (module import/export mechanism)

powerful "regular expression" capabilities

simple I/O model

many modules

support for static scoping

built-in debugger

Basics of PERL: PERL files use extension .pl. It can create self executing scripts. It uses system commands. Every statement must end with a semicolon “;”. Comments are prefixed at the start of the line with hash “#” symbol. The PERL variables are assigned a value using the operator “=“. PERL variables are not statically typed, i.e., you do not have to declare what type of data you want to hold in them. PERL variables are declared the first time you initialized them and they can be anywhere in the program. They are interpreted at the point of execution. They do not necessarily have a particular file extension although the .pl extension is used commonly. PERL script starts with the line “!/usr/bin/perl” .

Perl Types: It has three categories of variables/values: scalars, arrays and hashes. Variables for each category are distinguished by the first symbol in the variable name

$ for scalar

@ for array

% for hash

Scalar variables are of three types: numbers, character strings and references. Numbers are stored internally as double-precision floating point numbers.

Note that strings are considered scalars in PERL. Integer literals are a string of digits.

Note that strings are considered scalars in PERL.

Integer literals are a string of digits. Integer literals can be written in hexadecimal, base 16, but beginning the number with 0x or 0X. Floating-point literals have either decimal point or exponent or both like C language. String literals can be delimited by single or double quotes.

Single quote delimiters do not allow any substitutions: no escape characters (other than \’ or \”), no variable interpolation

Double quote delimiters allow substitutions for escape characters and for variable interpolation

The letter q is used to introduce a literal, single quoted string, bounded by an arbitrary character like q$abcdef$. The letter pair qq is used to introduce a literal, double quoted string, bounded by an arbitrary character like qq#abcdef#. If the beginning delimiter is one of (< [{then the matching delimiter must be ) >]}, respectively. Null string is denoted by either ‘’ or “”. Scalar variable names begin with $, followed by letters, digits and/or underscores. It is case sensitive. Conventionally, programmer defined names do not use upper case letters. Scalar variable values are interpolated into double quoted strings. If $x has the value 3 then “Value of x is $x” becomes “Value of x is 3”. Unassigned variables have the value undef. The value undef converts to 0 as a number and the null string as a string.

PERL has a large number of predefined variables. Many are named with special characters, such as $_ and $^.

PERL has arithmetic operators such as +, -, *, and

Other arithmetic operators such as % (Modulus operator), ** (exponentiation), -- and ++.

/. Note that 5/2 is 2.5.

A string is a single unit, a scalar. The period, ‘.’, is used as the concatenation operator. PERL does not overload operators. If $a is “cant” then $a . “aloupe” is “cantaloupe”. The ‘x’ operator indicates repetition, so “*“ x 4 is “****“. Predefined unary operators can be used as functions by simply parenthesizing the operand. Be aware of precedence changes since parentheses are the highest precedence.

The assignment operator, ‘=‘, assigns a value to a variable.The result returned is a reference to the assigned variable. Compound assignment operators are similar to C, C++ and Java. $x *= 3 multiplies the value of $x by 3.

Precedence Table:

Precedence Table: PERL treats all input and output as file input and output. Physical files have
Precedence Table: PERL treats all input and output as file input and output. Physical files have

PERL treats all input and output as file input and output. Physical files have external names, but all files are referred to by internal names called filehandles.

Certain filehandles are predefined

STDIN is console input, usually the keyboard

STDOUT is console output, usually the screen

STDERR is console error output, usually the screen

The execution environment of the PERL script may redirect these predefined handles to take input from other sources (such as a physical file) or put output to other targets. The line input operator, ‘<>’ reads a line of input (including a new line character) from the filehandle. For example, $line = <STDIN> will read one line from standard input and assign it to $line.

Since in most cases the terminating new line character is not desired, the chomp operator is used to remove it:

$x = <STDIN>; chomp($x); This is often abbreviated as chomp($x = <STDIN>); The assignment operator returns a reference to $x which is passed to chomp.

Using <> without a filehandle has a special meaning in PERL.

Each argument on the command line is interpreted as a file name. The lines are

Each argument on the command line is interpreted as a file name. The lines are read from these files in succession. Standard input can be included by using a single hyphen as an argument: ‘-’. The print function takes as an operand a list of one or more strings separated by commas.

There is no new line character provided automatically, it must be literally included. A C- style printf function is available. PERL programs will run independently of browser or server. For example, it could be run from the command line. Perl programs are run from the command line by using the perl interpreter perl file.pl. Command flags can be added:

-w asks that warnings be reported for problematic programming

-c asks for compilation without running

Control statements depend on the value of control expressions to determine execution flow. Control expressions are, conceptually, either true or false.

`

expressions are, conceptually, either true or false. ` The first six operators produce +1 if true

The first six operators produce +1 if true or “” if false. The last operator produces -1 if the first operand is less than the second, +1 if the first operand is greater than the second and 0 if the two operands are the same.

Relational operators are non associative. That is, $a < $b < $c is not syntactically

Relational operators are non associative. That is, $a < $b < $c is not syntactically valid in PERL. PERL provides two forms of boolean operators

! (not), && (and) and || (or) have precendence above the assignment operators but below other operators

and, or and not have precedence below any other operators $a = <> or die “no input” parses as ($a = <>) or (die “no input”).

This causes the program to terminate if no input is read from <>

If there is input, the next line is assigned to $a

$a = <> || die “not input”; parses as $a = (<> || (die “no input”));

This causes the program to terminate if no input is read from <>

This causes $a to be assigned +1 if there is input.

A block of statements in PERL is a sequence of statements enclosed in a pair of curly

braces: { }. Control statements in PERL require blocks of statements as components rather than allowing single statements without the braces.

The if statement syntax

if (control-expression) block

[

elsif( control-expression ) block Repeated elsif clauses ]

[

else block ]

[ ] indicates optional parts. The elsif part may appear 0 or more times. The until statement reverses the sense of the if. An until has neither elsif nor else parts.

The basic repetition uses while:

while ( control-expression ) block

The while executes the block as long as the control-expression is true

The until reverses the sense of the while until ( control-expression ) block

The until executes as long as the control-expression is false

Syntax of the for statement:

for (initial-expression; control-expression; increment-expression ) block The initial and increment expressions can be multiple expressions separated by commas.

The last operator causes the loop to exit immediately. A loop may be provided a label by prefixing a name and a colon to the beginning of the loop.

A last operator can have a loop label as an operand.

– In this case, the operator will cause exit from the loop with the given

In this case, the operator will cause exit from the loop with the given label even if it is not the smallest loop containing the statement executing last

The variable $_ is often an implicit operand for operators in PERL. The statement print;

Using the

<STDIN> input without assigning explicitly to a variable causes the value to be assigned

to $

will print the value of $

The statement chomp; will ‘chomp’ the value of $

Be aware that overuse of $_ can make programs difficult to follow.

An array holds a list of scalar values. Note that an array holds scalars, not other arrays or hashes. Different types of scalar data can be in the same array. Arrays have dynamic size, that is, they can increase and decrease in size as a program executes.

A list literal is given as a pair of parentheses enclosing a list of values separated by

commas. Note that if a ‘sub-list’ is include as in (‘a’, (‘b’, ‘c’), ‘d’), then the list is flattened to (‘a’, ‘b’, ‘c’, ‘d’). References are used to include arrays as elements in arrays. An array is a variable that stores a list. The name of an array variable begins with the

character @. An array variable may be assigned a literal list value. @a = (1, 2, ‘three’, ‘iv’);

An array assignment creates a new array as a copy of the original. @b = @a;

An expression in Perl is evaluated in a context. For example in the assignment

$a = expression;

other hand, in @a = expression;

context. An array or list evaluated in a scalar context evaluates to the length of the list.

The expression on the right is evaluated in a scalar context, On the

The expression on the right is evaluated in a list

A list of values can be assigned to a list of variables.

($a, $b, $c) = (1, 2, “iii”); causes $a to get the value 1, $b to get the value of 2 and $c to get the value “iii”. Note that the right side expression is evaluated before the assignment, so that

($x, $y) = ($y, $x)

actually swaps the values of the two variables.

If the target includes an array variable, all remaining values in the expression list are

assigned to the list variable.

The elements in an array are indexed by integers, beginning with 0. Element with index 1 of list @alist is accessed as $alist[1]. Note that $ is used since the element is a scalar. Note also that there is not relationship between the scalar variable $alist and the list element $alist[1]. Assigning to an array element may cause the array to expand to accommodate the element. @a = (‘a’, ‘b’, ‘c’); $a[20] = ‘outfield’; Causes the array @a to expand to size 21. The last subscript in the array @a is $#a. The foreach allows convenient iterating through the elements of an array or list. The loop foreach executes the body of the loop

for each element of the array @a. In each iteration, $x is an alias for the element. That is,

if $x is changed, the corresponding element of the array is changed.

Four functions are provided by PERL to support stack and queue operations on arrays are:

Four functions are provided by PERL to support stack and queue operations on arrays are: push @a, $x; inserts the value $x at the end of the array @a. pop @a; removes the last value of @a and returns it. shift @a; removes the first value of @a and returns it. All the remaining elements of @a are shifted down one index, hence the name. unshift @a, $x; inserts the value $x at the beginning of the array @a. All the remaining elements of @a are shifted up one index.

The split function breaks strings into parts using a character to separate the parts. The sort function sorts a list using string comparison. A more general usage is presented later.

sort does not alter the parameter but returns a new list.

The qw (quote words) function creates a list of words from a string. The die operator

displays its list operand and then terminates the program execution.

An associative array uses general data, often strings, as indexes.

The index is referred to as a key, the corresponding element as a value.

Since a hash table is often used to implement an associative array, these structures are

known as hashes in PERL. Elements in a Perl hash do not have a natural ordering. When a list of keys is retrieved from a hash there is no definite relationship between the order of the keys and either the values of the keys or the order in which they were entered into the hash.

Hash variables are named beginning with the character %. If an array is assigned to a hash, the even index elements become keys and the odd index elements are the corresponding values. Assigning an odd length array to a hash causes an error. Curly braces are used to ‘subscript’ a hash. If %h is a hash, then the element corresponding to ‘four’ is referenced as $h{‘four’}. Values can be assigned to a hash reference to insert a new key/value relation or to change the value related to a key.

A key/value relation can be removed from a hash with the delete operator. The undef operator will delete all the contents of a hash. The exists operator checks if a key is related to any value in a hash. Just check $h{‘something’} doesn’t work since the related value may be the empty string or 0, both of which count as false.

A hash variable embedded in a string is not interpolated. However, a reference to a hash element is interpolated. The keys operator returns a list of the keys in a hash. The sort operator can also be applied to iterate through the keys in order.

The %ENV variable is defined to be the key/value pairs defined in the environment of the running PERL process. Many of these are inherited from the run-time environment. In Microsoft Windows, environment variables can be set through the command-line set command. In Unix Bourne shell, environment variables may be set by a simple assignment.

A reference is a scalar value giving the address of another value in memory. A

A reference is a scalar value giving the address of another value in memory. A

reference to an existing variable is created by using the backslash operator. References to literal structures can be created

A reference to a list is created by enclosing a list in square brackets, […].

A reference to a hash is created by enclosing a list in curly braces {…}.

For example $a = [1, 2, 3, 4]

For example $h = {‘i’ => 1, ‘v’ => 5, ‘x’ => 10};

Notice the assignment is to a scalar variable. Since the literal value is a reference. To access the value pointed to by a reference, the programmer must explicitly dereference the reference an extra $ sign can be used.

If $a = 5 and $b = \$a then $$b is 5

$$b = 7 changes the value of $a to 7

In a reference to an array, -> can be used between the reference and the index to

indicate a dereference.

If $r = \@list then $$r[3] is the element at index 3 of @list

$r->[3] is also the element at index 3 of @list

$r[3] is the element at index 3 of @r, completely unrelated

Function: A function definition consists of a function header and the body. The body

is a block of code that executes when the function is called. The header contains the

keyword sub and the name of the function. A function declaration consists of the keyword sub and the function name. A declaration promises a full definition somewhere else.

A function call can be part of an expression. In this case the function must return a value that is used in the expression. A function call can be a standalone statement. In this case a return value is not required. If there is one, it is discarded. When a function is called, the body begins executing at the first statement.

A return statement in a function body causes the function body to immediately cease executing. If the return statement also has an expression, the value is returned as the value of the function. Otherwise, the function returns no value. If execution of a function reaches the end of the body without encountering a return statement, the return value is the value of the last expression evaluated in the function.

Variables that are not declared explicitly but simply assigned to have global scope. The my declaration is used to declare a variable in a function body to be local to the function. If a local variable has the same name as a global variable, the global variable is not visible within the function body. PERL also supports a form of dynamic scoping using the local declaration. A my declaration has lexical scope which works like scope rules in C, C++ and Java.

Parameters used in a function call are called actual parameters. Formal parameters are the names used in the function body to refer to the actual parameters. In Perl, formal parameters are not named in the function header.

PERL supports both pass-by-value and pass-by-reference. The array @_ is initialized in a function body

PERL supports both pass-by-value and pass-by-reference. The array @_ is initialized in a function body to the list of actual parameters. An element of this array is a reference to the corresponding parameter. Changing an element of the array changes the corresponding actual parameter. Often, values of @_ are assigned to local variables which corresponds to pass-by-value.

This code causes the variable $a to change. sub plus10 {

plus10($a);

$_[0] += 10;

}

The first line of this function copies actual parameter to local variable. Sub f {

my($x, $y) = @_;

}

The sort function can be called with the first parameter being a block which returns a numeric value based on the comparison of two variables $a and $b.This parameter is not followed by a comma.

For example, using sort{$a <=> $b} @num will sort the array @num using numerical comparison. Using

sort{$b <= > $a} @num will sort in reverse order.

Perl has powerful pattern matching facilities built in. These have been imitated in a number of other systems. The m operator indicates a pattern matching.

This is used with delimiters like q and qq but the enclosed characters form a pattern

If the delimiter is / then the m is not required

A match is indicated by the =~ operator with a string on the left and a pattern on the

right. A pattern alone is matched by default to $

The split function can take a pattern as the first argument rather than a character. The pattern specifies the pattern of characters used to split the string apart.

The s operator specifies a substitution.

s/pattern/new-string/

The new-string will replace the part of a string matched by the pattern. The =~ operator is used to apply the substitution to a string. If the operator is not used, $_ is operated on by default. A g modifier on the substitution causes all substrings matching the pattern to be replaced, otherwise only the first match is changed. The modifier i cause the pattern match to be case insensitive.

tr command: This is written as: tr/ char-list1 / char-list2 / When applied to a

tr command: This is written as: tr/char-list1/char-list2/ When applied to a string it causes each character of the string that appears in the first list to be replaced by the corresponding character in the second list. If the second list is empty, the characters from the first list are deleted from the string.

The =~ operator is used to apply the transliteration. If the operator is not used, $_ is operated on by default. To carry out file input and output, a file handle must be created for each file. The open function is used to create a file handle. The first parameter to open is the name of a file handle. By convention the name is all capital letters. The second parameter to open is a string value naming the file and, optionally, including a character to indicate the mode of opening the file.

< indicates open for input (default), > indicates open for output, deleting the content of an existing file and >> indicates open for output, appending to a file that already exists.

The print function is used to send output to a filehandle.

print OUTHANDLE “data”, “more data”;

Note that there is not comma after the OUTHANDLE

This is important, otherwise the value of the handle will be displayed on the output console The function parameters can indicate that characters are to be stored in the array somewhere other than at the beginning. The seek function can be used to position the filehandle cursor at a different position in the file.

CGI: (Common Gateway Interface)

CGI is a lightweight mechanism for communication between the web server and other

programs (CGI scripts) that can be run on the server. Instead of pointing to an HTML file a URL may request that a CGI program is run on the server. CGI programs (or scripts) are commonly written in:

– Unix - Shell, Perl, Tcl, C,C++, Python, Ruby –Windows - Visual Basic, Perl

– Mac - Applescript, C,C++, Perl

GET method is mainly used for short queries. Input values are part of the URL. POST-will send data as input stream to the program. It is more secure.

Computation is required to support sophisticated web applications. Computation can be done by the server or the client (browser) or both. The Common Gateway interface (CGI) is a protocol describing a standard way of providing server-side active web content. Under circumstances determined by the server, an HTTP request will cause a program to run. The output from the program will be the response returned to the client making the request. Data from forms will be encoded in a request sent to the server. This data can be used by a CGI program.

There are several common ways a web server can use to determine if a web

There are several common ways a web server can use to determine if a web request should cause a CGI program to execute. Usually, the determination is based on the target of the request. Certain directories can be designated as containing CGI programs. Often cgi-bin is used. Certain file extensions can be designated as

signifying a CGI program.

program to executed can be made with a simple link (<a> tag in HTML).

.pl usually identifies a Perl script. A request for a CGI

The usual way for invoking CGI programs is through the action attribute of a form. Data from the form is then encoded and sent with the request. A request for a CGI program to be executed can be made with a simple link (<a> tag in HTML)

This method is limited

Any data sent must be hard-coded into the link

The CGI program generally creates the response by sending output to the standard output stream, Using print in Perl.

The CGI program will usually have to provide the content-type header.

Content-type: text/html

This will be the last line of the response headers and must be followed by a blank

line. The rest of the response is created by printing the HTML code desired to standard output.

Both GET and POST requests under HTTP can be used to carry form data from the browser to the server. The data is formatted into a query string. Each form of request includes the information in a different way. In a GET request, the query string is appended to the URL of the request, with a question mark used to separate it from the first part of the URL.

In a POST request, the query string is sent as the data part of the request. Each unit of data sent is encoded as name = value. The name is usually the value of a name attribute of a form widget. The value is the string representation of the widget value. Several units are combined by separating them with ampersands, &. Special characters in name and value are encoded. The code is a percent sign, %, followed by the hexadecimal code for the character. A space is encoded as %20. Some browsers will encode spaces as +.

When the POST method is used, the query string can be read from standard input The CONTENT_LENGTH environment variable tells how many characters can be read. When The GET method is used, the query string is given by the value of the environment variable QUERY_STRING.

Writing a CGI program from scratch is very tedious. Creating HTML requires numerous print statements. Retrieving data from the query strings is tricky. One of the reasons for PERL’s popularity for CGI programming is the powerful pattern matching facilities which greatly ease the task of parsing a query string.

The Perl module CGI.pm provides numerous functions to help with both of these problems. Shortcut

The Perl module CGI.pm provides numerous functions to help with both of these problems. Shortcut functions return string values containing HTML code. Note, the string must be printed out to actually become part of the response. Some functions take no arguments. print br; puts the tag <br/> into the response.

Some functions can be given a single argument which becomes the content of the tag print h1(“A Header”) puts <h1>A Header</h1> into the response.

Attributes for tags are provided as attribute/value pairs in the argument list of the shortcut function. The arguments are provided in the form of a literal hash. Attribute names are preceded by a hyphen. print textarea(-name => "Description", -rows => "2", -cols => "35"); produces this in the response:

<textarea name="Description" rows="2" cols="35"> </textarea> Attributes and content can both be provided to a shortcut by giving the attributes explicitly as a hash reference print a({-href => "fruit.html"}, Press here for fruit descriptions"); produces this in the response:

<a href="fruit.html"> Press here for fruit descriptions </a>

If an array reference is provided for the content, a tag is created for each item, giving

the tag all the specified attributes. The head shortcut function provides a standard header. The start_html function provides the beginning part of an HTML document, through the <body> start tag. The function takes one argument, the document title.

The param function takes a name as an argument. The function returns the value associated to the name, if any, in the request.

HTTP is a stateless protocol, that is, the server treats each request as completely separate from any other. This, however, makes some applications difficult. A shopping cart is an object that must be maintained across numerous requests and responses. The mechanism of cookies can be used to help maintain state by storing some information on the browser system.

A cookie is a key/value pair that is keyed to the domain of the server. This key/value

pair is sent along with any request made by the browser of the same server. A cookie has a lifetime which specifies a time at which the cookie is deleted from the browser. Cookies are only returned to the server that created them. Cookies can be used to determine usage patterns that might not otherwise be ascertained by a server. Browsers generally allow users to limit how cookies are used. Browsers usually allow users to remove all cookies currently stored by the browser. Systems that depend on cookies will fail if the browser refuses to store them.

The cookie function takes a hash with three keys for the name, value and expiration

time of a cookie. The cookie value produced by this function must be passed to

time of a cookie. The cookie value produced by this function must be passed to the header function using the –cookie key. header(-cookie => $a_cookie) Calling the cookie function with no arguments produces a hash of all cookies from the current request.

Programming the Web

06CS73

SAMPLE QUESTIONS

Programming the Web 06CS73 SAMPLE QUESTIONS Q1a. Explain standard XHTML Document structure Q1b. What is web

Q1a. Explain standard XHTML Document structure

Q1b. What is web server? Name any three web servers

Q2. What is hypertext protocol? Explain the request phase and response phase in

detail?

5

5

10

Q3a. Explain HTML Frames with an example.

5

Q3b. List and explain the purpose of DTD?

5

Q4. Create and validate a XHTML document that defines a table with columns for state, state bird, state flower and state tree. There must be at least five states as rows in the table. You must also include “alt” attribute specifications. Also apply background color and border width for the table.

10

Q5. Explain the usage of character entities in XHTML. List out at least 8 character entities with their meaning.

10

Q6a. Explain HTML Frameset. Create a HTML Program with horizontal and

vertical frameset.

5

Q6b.Write notes on:

5

Name servers

Proxy Servers

• Name servers • Proxy Servers 7. Explain the following tags with examples: 10 • Align

7. Explain the following tags with examples:

10

Align and valign attributes

Cell padding and cell spacing attributes

8a. what is the difference in the effect of a paragraph tag and a break tag? Explain

5

8b. State and explain general Server characteristics

5

Q9a. What are CSS Style sheets? What is the advantage of document-level style sheets over inline style sheets?

5

Q9b. Describe the two ways to embed a JavaScript script in an XHTML

document.

5

Q10. What are the various MYSQL data types available? Explain.

10

Q11a. What is the purpose of a style class selector and generic class?

5

Q11b. Explain for-in loop used in JavaScript with an example?

5

Q12. Explain font and list properties used in CSS with an example.

10

Q13a. Write a note on CSS Box Model.

5

Q13b. Write a note on string properties and methods used in

JavaScript

5

a note on string properties and methods used in JavaScript 5 Q14a.What are pseudo-classes? Write a

Q14a.What are pseudo-classes? Write a CSS file that adds different colors to a

hyperlink

5

Q14b. Write notes on Object creation and Modification with suitable examples

5

15. Given the following table of data about several planets of our solar system,

create a Web page

a button, have the distance and diameter appear either in an alert box or (as extra

credit) in separate fields of the page.

that enables users to enter a planet name and, at the click of

10

Planet Distance from the Sun Diameter

Mercury 36 million miles 3,100 miles

Venus 67 million miles 7,700 miles

Earth 93 million miles 7,920 miles

Mars 141 million miles 4,200 miles

16. Write a Perl program to change the password of user and grant him required

permission.

10

Q17a. What is a query string? How is a query string transmitted to the server with the get and post method.

5

Q17b. Explain the three phases of event processing in the DOM 2 event

model

5

Q18.

Linkage

What is CGI? Write a note on CGI-

10

Q18. Linkage What is CGI? Write a note on CGI- 10 Q19a. What is CGI.pm module?

Q19a. What is CGI.pm module? Give 5 different methods which are used to create html

output and their functions.

5

Q19b. What are events? What is an event handler?

5

Q20. List any 7 Events and their attributes.

10

Q21a. Write a note on Navigator object

5

Q21b. Explain various forms of element positioning in dynamic javascript

5

Q22a. What is the purpose of shortcuts in

CGI.pm?

5

Q22b. Write a note on HTTP Cookies. Where are cookies stored?

5

23. Write a program in javascript to illustrate Changing of colors and fonts

dynamically

10

24. Write a javascript program to illustrate Element visibility property

10

Programming the Web 06CS73 ANSWERS TO SAMPLE QUESTIONS 1a. Every XHTML document must begin with:

Programming the Web

06CS73

ANSWERS TO SAMPLE QUESTIONS

1a. Every XHTML document must begin with:

<?xml version = 1.0?> <!DOCTYPE html PUBLIC -//w3c//DTD XHTML 1.1//EN

http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>

<html>, <head>, <title>, and <body> are required in every document The whole document must have <html> as its root

1b. Provide responses to browser requests, either existing documents or dynamically built documents.

• Web servers run as background processes in the operating system.

WAMP Server

Apache Server

IIS Server.

2. The protocol used by ALL Web communications

• Request Phase

HTTP method domain part of URL HTTP ver. Header fields blank line Message body

• An example of the first line of a request:

GET /degrees.html HTTP/1.1

• Form:

Status line Response header fields blank line Response body

• Status line format:

HTTP version status code explanation

• Example: HTTP/1.1 200 OK

(Current version is 1.1)

(Current version is 1.1) • Status code is a three-digit number; first digit specifies the general

• Status code is a three-digit number; first digit specifies the general status

1 => Informational

2 => Success

3 => Redirection

4 => Client error

5 => Server error

• The header field, Content-type, is required

3a. Frames are rectangular sections of the display window, each of which can display a different document Because frames are no longer part of XHTML, you cannot validate a document that includes frames

The <frameset> tag specifies the number of frames and their layout in the window.

3b.

Some servers can serve documents that are in the document root of other

machines

called as PROXY SERVER. DNS servers or name servers - convert fully qualified domain names to IPs.

4. Program OUTPUT and creation of table using <table> </table> tags. Background and

fore ground color and border width using bgcolor , border-width – property tags.

5. A Collection of special characters that are needed in document, but cannot be typed.

• Eg: small raised circle that represents “degrees”.

• These are names for the characters by the browser.

• An entity in a document is replaced by its associated character by the browser.

Char.

Entity Meaning

&

&amp; Ampersand

<

&lt;

Less than

>

&gt;

Greater than

&quot; Double quote

&apos; Single quote

¼

&frac14;

One quarter

½

&frac12;

One half

¾

&frac34;

Three quarters

°

&deg;

Degree

(space)

&nbsp;

Non-breaking space.

6a. The <frameset> tag specifies the number of frames and their layout in the window

• <frameset> takes the place of <body> – An asterisk after some other specification gives

• <frameset> takes the place of <body>

– An asterisk after some other specification gives the remainder of the height of the window

– Examples:

<frameset rows = "150, 200, 300">

<frameset rows = "25%, 50%, 25%">

<frameset rows = "50%, 20%, *" >

<frameset rows = "50%, 25%, 25%"

cols = "40%, *">

• The <frame> tag specifies the content of a frame

• The first <frame> tag in a <frameset> specifies the content of the first frame, etc.

– Row-major order is used

– Frame content is specified with the src attribute

– Without a src attribute, the frame will be empty (such a frame CANNOT be filled later)

• If <frameset> has fewer <frame> tags than frames, the extra frames are empty.

6b. The doctype declaration should be the very first thing in an HTML document, before the <html> tag.

• The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.

• The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers can render the content correctly.

7. The align attribute controls the horizontal placement of the contents in a table cell

– Values are left, right, and center (default)

– align is an attribute of <tr>, <th>, and <td> elements

• The valign attribute controls the vertical placement of the contents of a table cell

– Values are top, bottom, and center (default)

– valign is an attribute of <th> and <td> elements

SHOW cell_align.html and display it

• The cellspacing attribute of <table> is used to specify the distance between cells in a table

• The cellpadding attribute of <table> is used to specify the spacing between the content of a cell and the inner walls of the cell

8. Paragraph in HTML doesnot insert a new blank line, whereas in XHTML – a new line is considered. It displays the contents, whereas <br> is an empty tag.

• Provide responses to browser requests, either existing documents or dynamically built documents • Browser-server

• Provide responses to browser requests, either existing documents or dynamically built documents

• Browser-server connection is now maintained through more than one request- response cycle

• All communications between browsers and servers use Hypertext Transfer Protocol (HTTP)

• Apache (open source, fast, reliable)

• Directives (operation control):

ServerName

ServerRoot

ServerAdmin,

DocumentRoot

Alias

Redirect

DirectoryIndex

UserDir

9a. CSS stands for Cascading Style Sheets Styles define how to display HTML elements

An inline style loses many of the advantages of style sheets by mixing content

with

presentation. Use this method sparingly!

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. 9b. Two locations for JavaScript server different purposes

• JavaScript in the head element will react to user input and be called from other locations

• JavaScript in the body element will be executed once as the page is loaded 10. Following are the various datatypes available in MYSQL TINY INT SMALL INT MEDIUM INT INTEGER same as INT BIGINT FLOAT DOUBLE DECIMAL. Etc….

11a.

The class Selector With the class selector you can define different styles for the same type of HTML element. Say that you would like to have two types of paragraphs in your document:

one right-aligned paragraph, and one center-aligned paragraph. Used to allow different occurrences of the same tag to use different style specifications

A style class has a name, which is attached to a tag name A generic

A style class has a name, which is attached to a tag name

A generic class can be defined if you want a style to apply to more than one kind

of tag

A generic class must be named, and the name must begin with a period

Example,

.really-big { … }

11b.

Syntax for (identifier in object) statement or compound statement

• The loop lets the identifier take on each property in turn in the object

• Printing the properties in my_car:

for (var prop in my_car) document.write("Name: ", prop, "; Value: ", my_car[prop], "<br />");

Result:

Name: make; Value: Ford Name: model; Value: Contour SVT

12. Font properties are:

font-family

• Value is a list of font names - browser uses the first in the list it has

• font-family: Arial, Helvetica, Courier

• Generic fonts: serif, sans-serif, cursive, fantasy, and monospace (defined in CSS) font-size

• Possible values: a length number or a name, such as smaller, xx-large, etc. font-style

• italic, oblique (useless), normal font-weight - degrees of boldness

• bolder, lighter, bold, normal Could specify as a multiple of 100 (100 – 900) font

• For specifying a list of font properties font: bolder 14pt Arial Helvetica

• Order must be: style, weight, size, name(s)

List properties

list-style-type

Unordered lists Bullet can be a disc (default), a square, or a circle Set it on either the <ul> or <li> tag

On <ul>, it applies to list items Could use an image for the bullets in an unordered list

Example:

<li style = "list-style-image:

url(bird.jpg)"> • On ordered lists - list-style-type can be used to change the sequence values

url(bird.jpg)">

On ordered lists - list-style-type can be used to change the sequence values 13a. The CSS box model is essentially a box that wraps around HTML elements, and consists of: margins, borders, padding, and the actual content. The box model allows us to place a border around elements and space elements in relation to other elements.

it

13b.

One property: length

• Note to Java programmers, this is not a method!

Character positions in strings begin at index 0

CharAt(), indexOf(), substring,toLowercase,toUppercase are the various string methods avaialble

14a. Pseudo classes are styles that apply when something happens, rather than because the target element simply exists

• Names begin with colons

<html> <head> <style type="text/css"> a:link {color:#FF0000}

a:visited {color:#00FF00} /* visited link */

a:hover {color:#FF00FF}

a:active {color:#0000FF} /* selected link */ </style> </head>

/* unvisited link */

/* mouse over link */

<body> <p><b><a href="default.asp" target="_blank">This is a link</a></b></p> <p><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.</p> <p><b>Note:</b> a:active MUST come after a:hover in the CSS definition in order to be effective.</p> </body> </html>

14b. The new expression is used to create an object

• This includes a call to a constructor

• The new operator creates a blank object, the constructor creates and initializes all properties of the object Properties of an object are accessed using a dot notation: object.property Properties are not variables, so they are not declared

• An object may be thought of as a Map/Dictionary/Associative-Storage The number of properties of

• An object may be thought of as a Map/Dictionary/Associative-Storage

The number of properties of an object may vary dynamically in JavaScript

15. Use alert box, create a button and textfield and display the output using alert box()

16. Create Mysql user. Change the MySQL root password when logging in to the server. # mysqladmin password student Access is now denied without password. Use –p switch Login as mysql –u root –p

Also use mysql database and grant privileges for a new user. Mysql>USE mysql; Database changed mysql> GRANT SELECT,INSERT,UPDATE,DELETE ON people.* TO apache@localhost IDENTIFIED BY `LampIsCool`; Apache user can do everything within the database, but cannot delete people database. The user apache can access people database from localhost only. The IDENTIFIED BY clause sets the apache user’s password to LampIsCool. Login as $ mysql –u apache -p

17a. When the POST method is used, the query string can be read from standard input

• The CONTENT_LENGTH environment variable tells how many characters can be read

When The GET method is used, the query string is given by the value of the environment variable QUERY_STRING.

17b. Three traversal phases are defined In the capturing phase each node from the document root to the target node, in order, is examined. If the node is not the target node and there is a handler for that event at the

node and

The handler is enabled for capture for the node, the handler is executed. Then all handlers registered for the target node, if any, are executed.

In the bubbling phase each node from the parent of the target node to the root node, in order, is examined.

18. The Common Gateway Interface (CGI) is a protocol describing a standard way of providing server-side active web content

• Under circumstances determined by the server, an HTTP request will cause a program to run

• The output from the program will be the response returned to the client making

• The output from the program will be the response returned to the client making the request

There are several common ways a web server can use to determine if a web request should cause a CGI program to execute Usually, the determination is based on the target of the request

• Certain directories can be designated as containing CGI programs

• Often cgi-bin is used

• Certain file extensions can be designated as signifying a CGI program

• .pl usually identifies a Perl script.

19a. Writing a CGI program from scratch is very tedious

• Creating HTML requires numerous print statements

• Retrieving data from the query strings is tricky

• One of the reasons for Perl’s popularity for CGI programming is the powerful pattern matching facilities which greatly ease the task of parsing a query string The Perl module CGI.pm provides numerous functions to help with both of these problems 19b. Events represent activity in the environment including, especially, user actions such as moving the mouse or typing on the keyboard

An event handler is a program segment designed to execute when a certain event occurs Events are represented by JavaScript objects Registration is the activity of connecting a script to a type of event

20. Event

Tag Attribute

blur

onblur

change

onchange

click

onclick

focus

onfocus

load

onload

mousedown

onmousedown

mousemove

onmousemove

mouseout

onmouseout

mouseover

onmouseover

mouseup

onmouseup

select

onselect

submit

onsubmit

unload

onunload

Write a note on each of these events.

21a. Properties of the navigator object allow the script to determine characteristics of the browser

21a. Properties of the navigator object allow the script to determine characteristics of the browser in which the script is executing

The appName property gives the name of the browser

The appVersion gives the browser version.

21b. The position property specifies the position mode

• Value is absolute or relative or static

Absolute position specifies where an element appears relative to the containing element

In static position mode, the default, elements are placed left to right, top to bottom

• The top and left properties are ignored for static positioning

Relative position mode allows changing position relative to where the element would be with static positioning This could be used to create superscripts or subscripts by moving text up or down relative to its normal position.

22. Writing a CGI program from scratch is very tedious

• Creating HTML requires numerous print statements

• Retrieving data from the query strings is tricky

• One of the reasons for Perl’s popularity for CGI programming is the powerful pattern matching facilities which greatly ease the task of parsing a query string Shortcut functions return string values containing HTML code

• Note, the string must be printed out to actually become part of the response Some functions take no arguments print br; puts the tag <br/> into the response Some functions can be given a single argument which becomes the content of the tag

print h1(“A Header”)

puts

<h1>A Header</h1> into the response

23. <html>

<head> <title> Dynamic colors </title>

<script type = "text/javascript">

<!--

// ******************************************************** // // The event handler function to dynamically set the

// color of background or foreground

// color of background or foreground function setColor(where, newColor) { if (where == "background")

function setColor(where, newColor) { if (where == "background") document.body.style.backgroundColor = newColor; else document.body.style.color = newColor;

}

// ******************************************************** // // --> </script> </head>

<body> <p style = "font-family: Times; font-style: italic; font-size: 24pt" > This small page illustrates dynamic setting of the foreground and background colors for a document </p>

<form action = ""> <p> Background color:

<input type = "text" name = "background" size = "10" onchange = "setColor('background', this.value)" />

<br /> Foreground color:

<input type = "text" name = "foreground" size = "10" onchange = "setColor('foreground', this.value)" />

<br />

</p>

</form>

</body>

</html>

<!-- This is dynLink.html Illustrates dynamic font styles and colors for links -->

<html> <head> <title> Dynamic fonts for links </title>

<style type = "text/css"> .regText {font: Times; font-size: 16pt;} </style> </head>

<style type = "text/css"> .regText {font: Times; font-size: 16pt;} </style> </head> <body> <p class = "regText"> The state of <a style = "color: blue;" onmouseover = "this.style.color = 'red'; this.style.font = 'italic 26pt Times';" onmouseout = "this.style.color = 'blue'; this.style.font = 'normal 26pt Times';"> Washington </a> produces many of our nation's apples. </p>

</body>

</html>

24. <!-- showHide.html

Illustrates visibility control of elements --> <html> <head> <title> Visibility control </title> <script type = "text/javascript">

<!--

// ******************************************************** // // The event handler function to toggle the visibility

//

of the airplane image

function flipImag() {

dom = document.getElementById("airplane").style;

// Flip the visibility adjective to whatever it is not now

if (dom.visibility == "visible") dom.visibility = "hidden"; else dom.visibility = "visible";

}

// -->

</script>

</head> <body> <form action = ""> <div id = "airplane" style = "position:

</head> <body> <form action = ""> <div id = "airplane" style = "position: relative; visibility: hidden;"> <img src = " /images/c172.gif" alt = "(Picture of airplane)" /> </div> <p> <br /> <input type = "button" value = "Toggle airplane" onclick = "flipImag()" /> </p> </form> </body> </html>