Anda di halaman 1dari 44

B. TECH.

WEB TECHNOLOGIES III YEAR II SEM

UNIT I
Html Common tags
What are the different types of lists?
HTML lists appear in web browsers as bulleted lines of text. There are actually three different types of
HTML lists, including unordered lists (bullets), ordered lists (numbers), and definition lists (think:
dictionaries). Each list type utilizes its own unique list tag, which we'll demonstrate below.
An unordered list (<ul>) signifies to a web browser that all list items contained
inside the <ul> tag should be rendered with a bullet preceding the text. The default
bullet type for most web browsers is a full disc (black circle), but this can be
adjusted using an HTML attribute called type.
<ul [type="disc|circle|square"]>

Example:

Code:
<ul style="list-style-type:square">
<li>Coffee</li>

Ouput

Coffee
Tea
Milk

<li>Tea</li>
<li>Milk</li>
</ul>

An ordered list is defined using the <ol> tag, and list items placed inside of an
ordered list are preceded with numbers instead of bullets.
<ol [type="a|A|i|I" start=n]>

<ol>
<li>M.Tech
<li>B.Tech
<li>Inter

1. Mtech
2. Btech
3. Inter

</ol>
HTML definition lists (<dl>) are list elements that have a unique array of tags and
elements; the resulting listings are similar to those you'd see in a dictionary.

<dl> - opening clause that defines the start of the list

<dt> - list item that defines the definition term

<dd> - definition of the list item

<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

Coffee
Black hot drink
Milk
White cold drink

Explain about the following:


a) Cellpadding
rowspan

b) cellspacing

c) colspan

d)

The HTML table model allows authors to arrange data -- text, preformatted text, images, links, forms,
form fields, other tables, etc. -- into rows and columns of cells. Tables are container elements, and their
sole purpose is to house other HTML elements and arrange them in a tabular fashion.
Each table may have an associated caption that provides a short description of the table's purpose.
Table
rows may
be
grouped
into
a
head,
foot,
and
body
sections,
(via
THEAD, TFOOT and TBODY elements, respectively). Row groups convey additional structural
information and may be rendered by user agents in ways that emphasize this structure. User agents may
exploit the head/body/foot division to support scrolling of body sections independently of the head and
foot sections. When long tables are printed, the head and foot information may be repeated on each page
that contains table data.

Border

Cell padding
o

The thickness of the lines dividing cells.

How much space there is within the cell between the text and the
border of the cell

Cell spacing
o

How much space there is between adjacent cells


As displayed in
browser

HTML
<table cellpadding="5" cellspacing="1" border="1">
<tr>
<td>first</td>
<td>second</td>
</tr>
<tr>
<td>third</td>
<td>fourth</td>
</tr></table>

first

second

third

fourth

The <td> tag has two attributes, rowspan and colspan, that allow you to make cells cross multiple rows
and columns. Essentially, the idea is that cells could be merged together into one.Both attributes take the
number of rows or columns to span as the argument.

HTML

<table border="1">

As displayed in
browser

Notice the error here:

<tr><td colspan="2">first</td>
<td>second</td></tr>
<tr><td>third</td><td>fourth</td></tr>
</table>

first

<table border="1">

first

<tr><td colspan="2">first</td></tr>
<tr>
<td>third</td>
<td>fourth</td>

second

third fourth

Third

fourth

</tr></table>

<body><table border="1"

With cellpadding:

cellpadding="10">

First

Row

<tr> <td>First</td>
<td>Row</td></tr>

Second

Row

<tr> <td>Second</td>
<td>Row</td></tr>
</table></body>

What are the various form element? Create a form for


sending a message to a an email-id.
A webform on a web page allows a user to enter data that is sent to a server for processing. Forms can
resemble paper or database forms because web users fill out the forms using checkboxes, radio buttons,
or text fields. For example, forms can be used to enter shipping or credit card data to order a product, or
can be used to retrieve search results from a search engine.
When a visitor reaches the form, he only needs to fill the fields and send the form, usually with a submit
button. The sent form is received and processed by a processing agent (usually a server side script)
specified in the value of the "action" attribute of the form element.The <form> tag is used to create an
HTML form for user input.
Form attributes are:
name: This is the name of the form.
action: Here you will specify any script URL which will receive uploaded data.
method: Here you will specify method to be used to upload data. It can take various
values but most frequently used are GET and POST.

There are different types of form controls that you can use to collect data from a
visitor to your site.

Text input controls

Buttons

Checkboxes and radio buttons

Select boxes

File select boxes

Hidden controls

Submit and reset button

HTML Forms - Text Input Controls:


There are actually three types of text input used on forms:

Single-line text input controls: Used for items that require only one line of user input, such as
search boxes or names. They are created using the <input> element.

Password input controls: Single-line text input that mask the characters a user enters.

Multi-line text input controls: Used when the user is required to give details that may be longer
than a single sentence. Multi-line input controls are created with the <textarea> element.

The <input> tag specifies an input field where the user can enter data. An <input> element can vary in
many ways, depending on the type attribute. An <input> element can be of type text field, checkbox,
password, radio button, submit button, and more.
Syntax for Input:
<input type=text/password/submit/button/reset/radio/checkbox name=name value=value [size=n]
[maxlength=n]>
Ex: <input type=text name=ename>
Syntax for Textarea:
<textarea name=textarea name cols=n rows=n>
Ex: <textarea name=description cols=30 rows=5> </textarea>

There are 3 types of buttons

submit: This creates a button that automatically submits a form.

reset: This creates a button that automatically resets form controls to their
initial values.

button: This creates a button that is used to trigger a client-side script when
the user clicks that button.

Ex: <input type=submit value=submit>


Checkbox:
Checkboxes are used when more than one option is required to be selected. They
are created using <input> tag as shown below.

Ex: <input type="checkbox" name="course" value="oracle" checked> oracle


<input type="checkbox" name="course" value="java"> Java

Radio button
Radio Buttons are used when only one option is required to be selected. They are created using <input>
tag as shown below:
Ex: <input type="radio" name="branch" value="cse" /> cse
<input type="radio" name="branch" value="ece" /> ece

List box
Drop Down Box is used when we have many options available to be selected but only one or two will be
selected..
Syntax: <select name=name multiple size=n >
<option value=value1>
<option value=valuen>

</select>
Ex: <select name="subjects">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
Form for accepting Firstname and Lastname.
<form action="/cgi-bin/hello_get.cgi" method="get">
First name:
<input type="text" name="first_name" />
<br>
Last name:
<input type="text" name="last_name" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>

How can one view multiple pages at a time?


Frames allow an author to divide a browser window into multiple (rectangular)
regions. Multiple documents can be displayed in a single window, each within its
own frame. Graphical browsers allow these frames to be scrolled independently of
each other, and links can update the document displayed in one frame without
affecting the others. You can't just "add frames" to an existing document. Rather,
you must create a frameset document that defines a particular combination of
frames, and then display your content documents inside those frames. The
frameset document should also include alternative non-framed content in a
NOFRAMES element.
Process for coding frames
1. Code the first page with the layout the windows that subdivide your screen
(frameset command)

2. Name each window. This is refered to as a window-target.


3. Code each separate page (individual files) that will be the content of each
window. These are called the source files.
4. Code a "No Frames" option for noframes browsers.
To make a page use frames, add a <frameset> tag immediately after <head>
This tag takes two attributes, cols and rows, which specify the space taken by each
frame in the form of a comma-separated list. You can specify either the number of
pixels to use, a percentage, or "*" to mean the rest of the space once the other
values have been worked out. For instance,<frameset rows="40,20%,*"> would
divide the window into three rows, the top-most being 40 pixels deep, the middle
one taking 20% of the window, and the bottom one taking the remainder of the
space.
<frameset> has the following attributes

Cols -Specifies no. and size of columns in a frameset either in pixels or % or


*

Rows- Specifies no. and size of rows in a frameset either in pixels or % or *

Once you've specified how the window is to be divided up with the <frameset> tag,
you then describe the contents of each frame using <frame>. This tag takes the
following attributes:

src="URL": specifies the URL of the page to be loaded in this frame.

name="name": specifies the name of this window, to be used


with <a target>.

marginwidth="value", marginheight="value": sets the size of the margin in


the frame. Seriously optional.

scrolling="yes, no or auto": decides whether the frame will scroll. "Auto" is


the default value.

noresize: don't allow the user to resize this frame.

The following special values can also be used as names:

_blank: opens the link in a new unnamed window.

_self: opens the link in the current frame. Useful for overriding a standard
target set in <base>

_parent: opens the link in the current frame's parent <frameset>.

_top: gets rid of all frames; the linked page takes up the entire window.
Especially appropriate if the page you're linking to is an external site, and
hence nothing to do with your frame structure.

Frameset which allows a user to see 3 frames at a time.

<html>
<frameset
cols="25%,*,25%"
>

Output:

Frame A

<frame
src="frame_a.htm
">
<frame
src="frame_b.htm
">
<frame
src="frame_c.htm
">
</frameset></ht
ml>

What are the different ways to create style sheets?


CSS is a style language that defines layout of HTML documents. For example, CSS
covers fonts, colours, margins, lines, height, width, background images, advanced
positions and many other things.
Benefits of CSS

CSS is used for formatting structured content.

CSS is stored in browser cache; therefore it can be used on multiple pages without being
reloaded, increasing download speeds and reducing data transfer over a network.

CSS can be used to apply style to whole page or website without changing much of the code.

The look and layout of a site can be changed beyond recognition just by altering the CSS file.

With a CSS page, the navigation can be moved to the bottom of the source code, so the search
engine displays your content instead of the navigation.

One can achieve more precise control of layout;

One can apply different layout to different media-types (screen, print, etc.);

CSS has some disadvantages as well. One of the biggest disadvantages of CSS is that CSS does not work
consistently in different browsers. Microsoft Internet Explorer and Opera support CSS in a logical way
but unfortunately their logic does not support current CSS standards. Firefox supports CSS standards
more closely. So a site could look quite different on Internet Explorer from the way it looks in Firefox.
Therefore, the site must be designed for both Firefox and Internet Explorer.
Applying CSS to an HTML document
Html style tag includes the following:
<Style> : Defines the style information for a document
<link> : Defines the relationship between a document and an external resource

There are three ways you can apply CSS to an HTML document.

Method 1: In-line (the attribute style)


One way to apply CSS to HTML is by using the HTML attribute style. Building on the above example
with the red background color, it can be applied like this:
<html>

This is a heading

<body style="background-color:yellow;">
<h2 style="background-color:red;">This
is a heading</h2>
<p style="background-color:green;">This
is a paragraph.</p></body></html>

This is a paragraph.

Method 2: Internal (the tag style)


Another way is to include the CSS codes using the HTML tag <style>. For example like this:
<html>
<style type=text/css>
H1{font-family:verdana}

A heading
A paragraph.

P{font-family:arial;color:red;font-size:20px}
<body>
<h1>A heading</h1>
<p >A paragraph.</p>
</body></html>

Method 3: External (link to a style sheet)


The recommended method is to link to a so-called external style sheet. An external style sheet is simply a
text file with the extension .css. Like any other file, you can place the style sheet on our web server or
hard disk.
For example, let's say that your style sheet is named style.css and is located in a folder named style. The
situation can be illustrated like this:

The trick is to create a link from the HTML document (default.htm) to the style sheet (style.css). Such
link can be created with one line of HTML code:
<link rel="stylesheet" type="text/css" href="style/style.css" />

Notice how the path to our style sheet is indicated using the attribute href.
The line of code must be inserted in the header section of the HTML code i.e. between
the <head> and </head> tags. Like this:
<html>
<head><title>My document</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
...

This link tells the browser that it should use the layout from the CSS file when displaying the HTML
file. The really smart thing is that several HTML documents can be linked to the same style sheet. In
other words, one CSS file can be used to control the layout of many HTML documents.

This technique can save you a lot of work. If you, for example, would like to change the background
color of a website with 100 pages, a style sheet can save you from having to manually change all 100
HTML documents. Using CSS, the change can be made in a few seconds just by changing one code in the
central style sheet.

Unit II
Introduction to JavaScript
What are the advantage of the DHTML?

Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to
create interactive and animated web sites by using a combination of a static markup language (such
as HTML), a client-side scripting language, a presentation definition language (such as CSS), and
the Document Object Model.
DHTML allows scripting languages to change variables in a web page's definition language, which in turn
affects the look and function of otherwise "static" HTML page content, after the page has been fully
loaded and during the viewing process. Thus the dynamic characteristic of DHTML is the way it
functions while a page is viewed, not in its ability to generate a unique page with each page load.
DHTML is differentiated from Ajax by the fact that a DHTML page is still request/reload-based. With
DHTML, there may not be any interaction between the client and server after the page is loaded; all
processing happens in JavaScript on the client side. By contrast, an Ajax page uses features of DHTML to
initiate a request to the server to perform actions such as loading more content
JavaScript
JavaScript (more on JavaScript in a bit) is a programming language that both Netscape Navigator and
Internet Explorer can understand, making it a good choice for cross-browser DHTML.
Cascading Style Sheets (CSS)
Cascading Style Sheets (CSS) is another important part of DHTML. Where JavaScript provides the
programming end of things, CSS defines the appearance of objects. While older HTML tags allowed you
to define an object's appearance. CSS allows you to do this much more efficiently, and from a central
'rule' as it were. (More on CSS a bit later on in this course.)
Document Object Model (DOM)
Central to all three of the above items is the Document Object Model (DOM). The DOM is what allows
you to locate any object in a Web page, and manipulate it the way you want to. Some browsers have
slightly different versions of the DOM, that can make things a little more difficult than they should be. We
will be discussing the DOM in greater detail later on in this course.
Benefits of DHTML

1. Supported by all browser: DHTML is supported in every major browser, including


opera, safari, internet Explorer, and Firefox.
2. Open standards: you can create your pages according to the standardized
technologies of DHTML and you can expect that, they will display much the same on
any major browser.
3. Small file size: like html, we created DHTML with files which are smaller than
graphic files and generally render faster than alternatives such as flash and java
4. Change contents on the fly: when we have loaded our DHTML page then also we
can makes the necessary changes to the web page without having to reload it. This
is where the dynamic in DHTML comes from.
5. No plug-ins required: if a browser support HTML, CSS, JAVASCRIPT and the Dom it
supports DHTML without the need for any additional plug-ins.
6. Easy to learn: it is easy to learn DHTML. For DHTML no need to learn an entire
java programming language. Although DHTML is based on JAVASCRIPT which is now
a full featured programming language, you do not have to have a degree in
computer science to use the basics.
7. Data binding: Microsoft develops this to allow easier access to databases from
web sites. It is very similar to using a CGI to access a database, but uses an active x
control to function. This feature is very advanced and difficult to use for the
beginning DHTML writer.
8. Real-time positioning: when most people think of DHTML this is what they expect.
Object, images, and text moving around the web page. This can allow you to play
interactive games with your readers or animate portions of your screen.

Explain about JavaScript.


JavaScript is a scripting language designed primarily for adding interactivity to
Web pages and creating Web applications. The language was first implemented by
Netscape Communications Corp. in Netscape Navigator 2. Client-side JavaScript
programs, or scripts, can be embedded directly in HTML source of Web pages.
Depending on the Web developer's intent, script code may run when user opens the
Web page, clicks or drags some page element with the mouse, types something on
the keyboard, submits a form, or leaves the page. One can do things with few lines
of JavaScript that will significantly reduce the load on your server, give the user
better feed back, and enhance the appearance of your web pages.

JavaScript is an object-oriented language with prototypal inheritance. The


language supports several built-in objects, and programmers can create or delete
their own objects. Prototypal inheritance makes JavaScript very different from other
popular programming languages such as C++, C#, or Java featuring classes and
classical inheritance. JavaScript does not have classes in the C++ or Java sense. In
JavaScript, objects can inherit properties directly from each other, forming the
object prototype chain.
JavaScript is an interpreted language, with optional JIT-compilation support.
JavaScript was a purely interpreted language. This means that scripts execute
without preliminary compilation, i.e. without conversion of the script text into
system-dependent machine code. The user's browser interprets the script, that is,
analyzes and immediately executes it.
JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! JavaScript is usually
embedded directly into HTML pages
Benefits of JavaScript

It is widely supported in browser


Itt is also an easy language to get started using.
It gives easy access to document object and can manipulate most of them.
JavaScript can give interesting animations with many multimedia datatypes.
Special plug-in are not required to use JavaScript
JavaScript is secure language
JavaScript code resembles the code of C language, The syntax of both the language is very close
to each other. The set of tokens and constructs are same in both the language.

Disadvantages of JavaScript
Different versions of Netscape will behave differently depending on the language
features you use. It is possible to write JavaScript programs that use advanced
JavaScript features but do not cause problems on older browsers. However, doing
this is can be a complex and labour intensive process. Unfortunately, even the same
version of Netscape may behave differently depending on the operating system it is
run on. The language is very new and still evolving. Few software development tools
exist to help you write and debug your scripts. And while you can do a lot with
JavaScript, some things like animation, scrolling/animated banners and notices, and
complex programming are often better done using animated GIFs, Netscape Plugins
such as Flash, or Java applets.
JavaScript is used for the following purposes:

JavaScript is also an easy language to get started using.

JavaScript was designed to add interactivity to HTML pages

build small but complete client side programs.

build forms that respond to user input without accessing a server;

validate user input in an HTML form before sending the data to a server;

change the appearance of HTML documents and dynamically write HTML into
separate Windows;

manipulate HTML "layers" including hiding, moving, and allowing the user to
drag them around a browser window;

A JavaScript can be set to execute when something happens, like when a page has finished
loading or when a user clicks on an HTML element
A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load
another page specifically designed for that browser
A JavaScript can be used to store and retrieve information on the visitor's computer

JavaScript and Java

A common misconception is that JavaScript is similar or closely related to Java; this is not so.
Both have a C-like syntax, are object-oriented, are typically sandboxed and are widely used in
client-side Web applications, but the similarities end there. Java has static typing; JavaScript's
typing is dynamic

Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their
last common ancestor language.

Nonetheless, JavaScript was designed with Java's syntax and standard library in mind. In
particular, all Java keywords are reserved in JavaScript, JavaScript's standard library follows
Java's naming conventions

What are the different datatypes in JavaScript?


Numbers

"no explicit distinction between integers and real" numbers though integers
may be stored differently than floating point or real numbers.

Here are some literal numbers being assigned to a variable (not a complete
sampling):

x=8
//integer
x = .7343 //floating point

x = -4.3e3 //same as -4.3 103


x = 4.3e-3 //same as 4.3 10-3

Boolean Values

true or false are the two boolean values

Examples when true or false values result from an expression (not a complete
sampling):

10 < 11
10 > 11

//will be evaluated to result in the value true


//will be evaluated to false

Strings

strings can be created by assigning a literal value to a variable or by creating


a String object initialized with a literal string.

msg = "I there is no end to the details I have to remember?"


msg = new String("Is there is not end to the details I have to remember?")

null
null - "special key word denoting a null value"
x = null

What are the different controls in Javascript?


In JavaScript we have the following conditional statements:

if statement - use this statement to execute some code only if a specified


condition is true

if...else statement - use this statement to execute some code if the


condition is true and another code if the condition is false

if...else if....else statement - use this statement to select one of many


blocks of code to be executed

switch statement - use this statement to select one of many blocks of code
to be executed

If Statement
Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
Code to be executed if condtion is not true
}

Ex:
If (a>b)
{ document.writeln(a is greatest);
}
Else
{
Document.writeln(b is greatest);
}
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Ex:
var day=new Date().getDay();
switch (day)

{
case 0:
x="Today is Sunday";
break;
case 1:
x="Today is Monday";
break;
-------------default:
x="Today is Saturday";
break;
}

Loops
Loops are handy, if you want to run the same code over and over again, each time with a
different value.
The for loop is often the tool you will use when you want to create a loop.

for (statement 1; statement 2; statement 3)


{
the code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.


Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.

Example
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}

For/in Loop
The JavaScript for/in statement loops through the properties of an object:

var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (var x in person)
{
txt=txt + person[x];

}
While loop
The while loop loops through a block of code as long as a specified condition is true.

while (condition)
{
code block to be executed
}

Example
The loop in this example will continue to run as long as the variable i is less than 5:

Example
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition
is true.

Syntax
do
{
code block to be executed
}
while (condition);

Example
The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:

Example
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);

Illustrate about various String Manipulation functions.


String handling basically means the dissecting and manipulation of a piece of string. String manipulation
involves either joining strings together, splitting them apart or searching through them. JavaScript has
functions which perform all of those operations.

charAt(position)
charAt() simply returns the character at the specified position. For example:
var message="internet"
//alerts "n"
alert(message.charAt(1))

-concat(v1, v2,..)
A "redundant" method, concat() combines the strings of it's parameters with the calling string. Here's an
example:
var message="Bob"
var final=message.concat(" is a"," hopeless romantic.")
//alerts "Bob is a hopeless romantic."
alert(final)
The reason for this method's redundancy is that it's often a lot simpler to use the "+" operator instead to
combine strings. The choice is yours, of course.

-indexOf(char/substring)
An extremely useful string method, indexOf() allows you to search whether a particular character or
substring exists within a string, and if so, where the first character of the character/substring is located. If
no match is found, "-1" is returned instead.
The below demonstrates using this method to determine whether the word "George" exists in a sentence:
var sentence="Hi, my name is George!"
if (sentence.indexOf("George")!=-1)
alert("George is in there!")
Since it does, indexOf() will NOT return -1, but rather, the index number of "G", and subsequently, the
alert message will be executed.
If we were to tweak the sentence ever so slightly, so it reads:
var sentence="Hi, my name is Goerge!"
Running the same indexOf() code will return "-1" instead.

-slice(start, end)
As the name implies, slice() extracts out a substring from the string as determined by the starting and
ending points of it's parameters:
var text="excellent"
text.slice(0,4) //returns "exce"
text.slice(2,4) //returns "ce"
Simple enough, right?

-split(delimiter)
One of my personal favorite, split() cuts up a string into pieces, using the delimiter as the point to cut off,
and stores the results into an array. "Say that again?", you say. Consider the following message:
var message="Welcome to JavaScript Kit"
To extract out the individual words ("Welcome", "to", etc) from it.
//word[0] contains "Welcome", word[1] contains "to" etc
var word=message.split(" ")
Variable word instantly becomes an array that holds the individual words. This is so because we used a
space (" ") as the delimiter, which also is what's separating each word.
var message="Welcome to JavaScript Kit"
//word[0] contains "We", word[1] contains "come to
JavaScript Kit"
var word=message.split("l")
The spit() method is often used to parse values stored inside a cookie, since they are by default separated
by semicolons (;), a set delimiter.

-substring(from, to)
Last but not least, we arrive at substring(). This method simply returns the substring beginning with the
"from" parameter (included as part of the substring), and ending with "to" (NOT included as part of
substring). It behaves just like the slice() method seen earlier. For example:
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"

How Arrays in JavaScript are different from those of other


languages? List out the Array methods.
An array is an ordered set of data elements which can be accessed through a single
variable name.
Each element in the array has its own ID so that it can be easily accessed. One can
access the data elements either sequentially by reading form the start of the array,

or by their index. Index starts from 0 and continues till last i.e., till (array length
-1) .
In JavaScript, an array is slightly different because it is a special type of object and
has functionality which is not normally available in other languages.
Create an Array
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array
1: var fruits = new Array( "apple", "orange", "mango" );
2:var fruits = [ "apple", "orange", "mango" ];

You could also pass an integer argument to control the array's size:
Var fruits=new Array(3);
One can refer to a particular element in an array by referring to the name of the
array and the index number. The index number starts at 0.
document.write(fruits[0]);
document.write(fruits[3]);
Array Methods
Method

Description

concat()

Returns a new array comprised of this array joined with other array(s)
and/or value(s).

indexOf()

Returns the first (least) index of an element within the array equal to the
specified value, or -1 if none is found.

join()

Joins all elements of an array into a string.

lastIndexOf()

Returns the last (greatest) index of an element within the array equal to the
specified value, or -1 if none is found.

pop()

Removes the last element from an array and returns that element.

push()

Adds one or more elements to the end of an array and returns the new
length of the array.

reverse()

Reverses the order of the elements of an array -- the first becomes the last,
and the last becomes the first.

shift()

Removes the first element from an array and returns that element.

slice()

Extracts a section of an array and returns a new array.

sort()

Sorts the elements of an array.

splice()

Adds and/or removes elements from an array.

toString()

Returns a string representing the array and its elements.

unshift()

Adds one or more elements to the front of an array and returns the new
length of the array.

Sample Program demonstrating array functions.


<html>
<body>
<p id="demo">Click the button to join the array elements into a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{ var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=document.getElementById("demo");
x.innerHTML=fruits.join();
}</script>
</body>
</html>

Explain about how parameters are passed to functions using JavaScript.

A function is a group of reusable code which can be called anywhere in your


programme. This eliminates the need of writing same code again and again. This
will help programmers to write modular code. You can divide your big programme in
a number of small and manageable functions.

Defining a Function
Syntax
<script type="text/javascript">
<!-function functionname(parameter-list)
{
statements
}
//-->
</script>
Note: A function with no parameters must include the parentheses () after the function name.

Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{ alert("Hello World!"); }
</script> </head>
<body>
<form> <input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body> </html>
The function displaymessage() will be executed if the input button is clicked.
To invoke a function somewhere later in the script, you would simple need to write
the name of that function as follows:
FunctionName();
Ex: sample();

The return Statement:


A JavaScript function can have an optional return statement. This is required if you
want to return a value from a function. This statement should be the last statement
in a function
Passing parameters to a function
<script type="text/javascript">
<!-function concatenate(first, last)
{ var full;
full = first + last;
return full;
}
//-->
</script>

Now we can call this function as follows:


<script type="text/javascript">
<!-var result;
result = concatenate('Zara', 'Ali');
alert(result );
//-->
</script>

Output :
ZaraAli

Explain the concept of Objects in JavaScript illustrating


with an example.

JavaScript is not a pure object oriented programming language, but uses the
concept of objects. The new keyword used here is to create an object, it allocates
memory and storage. Objects can have functions and variables. To differentiate
between global variables and those which are part of an object but may have the
same name, JavaScript uses this keyword. When referring to a property of an
object, whether a method or a variable, a dot is placed between the object name
and the property. It doesnt have inheritance and the structure of code can look
peculiar.

Creating an Object
To create your own JavaScript objects you need to:
1. call a function using the key word: new
2. either write a special "constructor" function or call
the Object(), Array(), Date() or other predefined constructor function.
function Question(question, answer){
this.question = question
this.answer = answer
}

theQuestion = new Question("What is the sum of 5 and 3?", 8)


1. the new operator creates an object in memory and passes a reference to the
new object to the constructor function: Question();
2. the reference to the new object is available inside the Question() function
using the keyword this which is used to create and assign values to the two
properties question and answer;

3. a reference to the newly created and initialized object is returned and


assinged to the theQuestion variable.
Now that theQuestion variable holds a reference to an object, it can be treated like
an object with properties that can be read and set. For example:
theQuestion.answer = 99
alert("The answer is: " + theQuestion.answer)
The new operator and the Question() function can be used to create as many
"Question" objects as are needed (or that can fit in memory):
aQuestion = new Question("What is the sum of 7 and 3?", 10)
bQuestion = new Question("What is the sum of 5 and 7?", 12)

Example:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method


function addPrice(amount){
this.price = amount;
}

function book(title, author){


this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}

</script></head>

<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script></body></html>

Output:
Book title is : Perl
Book author is : Mohtashim
Book price is : 100

Explain about DOM model


The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines
the logical structure of documents and the way a document is accessed and manipulated. In the DOM
specification, the term "document" is used in the broad sense - increasingly, XML is being used as a way
of representing many different kinds of information that may be stored in diverse systems, and much of
this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as
documents, and the DOM may be used to manage this data.
With the Document Object Model, programmers can create and build documents, navigate their structure,
and add, modify, or delete elements and content. Anything found in an HTML or XML document can be
accessed, changed, deleted, or added using the Document Object Model, with a few exceptions - in
particular, the DOM interfaces for the internal subset and external subset have not yet been specified.
As a W3C specification, one important objective for the Document Object Model is to provide a standard
programming interface that can be used in a wide variety of environments and applications. The
Document Object Model can be used with any programming language.

The Document Object Model is a programming API for documents. The object model itself closely
resembles the structure of the documents it models. For instance, consider this table, taken from an
HTML document:
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
The Document Object Model represents this table like this:

In the Document Object Model, documents have a logical structure which is very much like a tree; to be
more precise, it is like a "forest" or "grove" which can contain more than one tree. However, the
Document Object Model does not specify that documents be implemented as a tree or a grove , nor does it
specify how the relationships among objects be implemented in any way. In other words, the object model
specifies the logical model for the programming interface, and this logical model may be implemented in
any way that a particular implementation finds convenient. In this specification, we use the term structure
model to describe the tree-like representation of a document; we specifically avoid terms like "tree" or
"grove" in order to avoid implying a particular implementation. One important property of DOM structure
models is structural isomorphism: if any two Document Object Model implementations are used to create
a representation of the same document, they will create the same structure model, with precisely the same
objects and relationships.
The name "Document Object Model" was chosen because it is an "object model" is used in the traditional
object oriented design sense: documents are modeled using objects, and the model encompasses not only

the structure of a document, but also the behavior of a document and the objects of which it is composed.
In other words, the nodes in the above diagram do not represent a data structure, they represent objects,
which have functions and identity. As an object model, the Document Object Model identifies:

the interfaces and objects used to represent and manipulate a document

the semantics of these interfaces and objects - including both behavior and
attributes

the relationships and collaborations among these interfaces and objects

The structure of SGML documents has traditionally been represented by an abstract data model, not by an
object model. In an abstract data model, the model is centered around the data. In object oriented
programming languages, the data itself is encapsulated in objects which hide the data, protecting it from
direct external manipulation. The functions associated with these objects determine how the objects may
be manipulated, and they are part of the object model.
The Document Object Model currently consists of two parts, DOM Core and DOM HTML. The DOM
Core represents the functionality used for XML documents, and also serves as the basis for DOM HTML.
All DOM implementations must support the interfaces listed as "fundamental" in the Core specification;
in addition, XML implementations must support the interfaces listed as "extended" in the Core
specification. The Level 1 DOM HTML specification defines additional functionality needed for HTML
documents.

Explain how a Regular Expression can simplify the


validation process.
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods
that use regular expressions to perform powerful pattern-matching and search-and-replace functions on
text.
A regular expression could be defined with the RegExp( ) constructor like this:
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;

pattern: A string that specifies the pattern of the regular expression or another regular expression.

attributes: An optional string containing any of the "g", "i", and "m" attributes that specify
global, case-insensitive, and multiline matches, respectively.

Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to
find a range of characters.
Expressi
on

Description

[...]

Any one character between the brackets.

[^...]

Any one character not between the brackets.

[0-9]

It matches any decimal digit from 0 through 9.

[a-z]

It matches any character from lowercase a through lowercase z.

[A-Z]

It matches any character from uppercase A through uppercase Z.

Quantifiers:
The frequency or position of bracketed character sequences and single characters can be denoted by a
special character. Each pecial character having a specific connotation. The +, *, ?, and $ flags all follow a
character sequence.
Expres
sion

Description

p+

It matches any string containing at least one p.

p*

It matches any string containing zero or more p's.

p?

It matches any string containing one or more p's.

p{N}

It matches any string containing a sequence of N p's

p{2,3}

It matches any string containing a sequence of two or three p's.

p{2, }

It matches any string containing a sequence of at least two p's.

p$

It matches any string with p at the end of it.

^p

It matches any string with p at the beginning of it.

Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning.For instance, you can search for large money sums using the '\d'
metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.

Character

Description

a single character

\s

a whitespace character (space, tab, newline)

\d

a digit (0-9)

\D

a non-digit

\w

a word character (a-z, A-Z, 0-9, _)

\W

a non-word character

[aeiou]

matches a single character in the given set

[^aeiou]

matches a single character outside the given set

(foo|bar|baz)

matches any of the alternatives specified

Modifiers
Several modifiers are available that can make your work with regexps much easier, like case sensitivity,
searching in multiple lines etc.
Modifier

Description

Perform case-insensitive matching.

Specifies that if the string has newline or carriage return characters, the
^ and $ operators will now match against a newline boundary, instead
of a string boundary

Perform a global matchthat is, find all matches rather than stopping
after the first match.

RegExp Methods:
Method
exec()

Description
Executes a search for a match in its string parameter.

test()

Tests for a match in its string parameter.

toString()

Returns a string representing the specified object.

The String object has four methods that take regular expressions as arguments. These are
your workhorse methods that allow you to match, search, and replace a string using the
flexibility of regular expressions:
Method

Description

match( regular expression )

Executes a search for a match within a string based on a regular


expression. It returns an array of information or null if no match
are found.

replace( regular expression,


replacement text )

Searches and replaces the regular expression portion (match)


with the replaced text instead.

split ( string)

Breaks up a string into an array of substrings based on a regular


expression or fixed string.

search( regular expression )

Tests for a match in a string. It returns the index of the match, or


-1 if not found. Does NOT support global searches (ie: "g" flag not
supported).

Javascript code to validate username and age using


regular expressions
<html>
<body>
<form method="post" action="">
Name : <input type="text" length=24>
Age : <input type="text" size="3">
<input type="button" onclick="validate1()" value="submit">
</form>
<script language="javascript">
function validate1()
{

var name=document.forms[0].elements[0].value;
var age=document.forms[0].elements[1].value;
var name_re=new RegExp("^[A-Z][a-zA-Z'-.]+$","g");
var age_re=new RegExp("^[\\d]+$","g");
if (name.match(name_re))
{
if(age.match(age_re))
{
alert("Valid User");
}
else
{
alert("Age does not match ");
}
}
else
{
alert("Name does not match ");
}
}
</script>
</body>
</html>

Explain about the various Builtin Objects of JavaScript.


Window Object
The window object represents an open window in a browser.
If a document contain frames (<frame> or <iframe> tags), the browser creates one window object for the
HTML document, and one additional window object for each frame.

Windows size can be specified by


Width=pixels
Height = pixels
Many attributes of the browser can be switched on/off individually
Toolbar=[1/0]
location=[1/0]
directories=[1/0]
status=[1/0]
menubar=[1/0]
scrollbar=[1/0]

Method

Description

alert()

Displays an alert box with a message and an OK button

close()

Closes the current window

open()

Opens a new browser window

scroll()

This method has been replaced by the scrollTo() method.

stop()

Stops the window from loading

Document Object
A document is a Web page that is being either displayed or created. The document
has a number of properties that can be accessed by JavaScript programs and used
to manipulate the content of the page. Some of these can be used to create HTML
pages from within JavaScript while others may be used to change the operation of
the current page.
Property / Method
document.anchors

Description
Returns a collection of all the anchors in the
document

document.close()

Closes the output stream previously opened with


document.open()

document.cookie

Returns all name/value pairs of cookies in the


document

document.forms

Returns a collection of all the forms in the


document

document.getElementById()

Returns the element that has the ID attribute


with the specified value

document.getElementsByName()

Accesses all elements with a specified name

document.links

Returns a collection of all the links in the


document

document.open()

Opens an HTML output stream to collect output


from document.write()

document.title

Sets or returns the title of the document

document.URL

Returns the full URL of the document

document.write()

Writes HTML expressions or JavaScript code to a


document

document.writeln()

Same as write(), but adds a newline character


after each statement

Browser Object
The navigator object contains information about the browser
Property

Description

appCodeName

Returns the code name of the browser

appName

Returns the name of the browser

appVersion

Returns the version information of the browser

cookieEnabled

Determines whether cookies are enabled in the browser

language

Returns the language of the browser

product

Returns the engine name of the browser

userAgent

Returns the user-agent header sent by the browser to the server

Date Object
The Date object is used to work with dates and times. Date objects are created with new
Date(). There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Method
getDate()

Description
Returns the day of the month (from 1-31)

getDay()

Returns the day of the week (from 0-6)

getHours()

Returns the hour (from 0-23)

getMilliseconds()

Returns the milliseconds (from 0-999)

getMinutes()

Returns the minutes (from 0-59)

getMonth()

Returns the month (from 0-11)

getSeconds()

Returns the seconds (from 0-59)

setDate()

Sets the day of the month of a date object

setHours()

Sets the hour of a date object

setMilliseconds()

Sets the milliseconds of a date object

setMinutes()

Set the minutes of a date object

setMonth()

Sets the month of a date object

setSeconds()

Sets the seconds of a date object

JavaScript is event driven. What are events? What events


can JavaScript handle?
JavaScript's interaction with HTML is handled through events that occur when the user or browser
manipulates a page.When the page loads, that is an event. When the user clicks a button, that click, too, is
an event. Another example of events are like pressing any key, closing window, resizing window etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of response
imaginable to occur. Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element have a certain set of events which can trigger JavaScript Code.

Attribute

Event Type

Description

Onerror

Window

Script to be run when an error occur

onload

Window

Fires after the page is finished loading

onblur

Form

Fires the moment that the element loses focus

onchange

Form

Fires the moment when the value of the element is changed

onfocus

Form

Fires the moment when the element gets focus

Onreset

Form

Fires when the Reset button in a form is clicked

onselect

Form

Fires after some text has been selected in an element

onsubmit

Form

Fires when a form is submitted

onkeydown

Keyboard

Fires when a user is pressing a key

onkeypress

Keyboard

Fires when a user presses a key

onkeyup

Keyboard

Fires when a user releases a key

onclick

Mouse

Fires on a mouse click on the element

ondblclick

Mouse

Fires on a mouse double-click on the element

onmousedown

Mouse

Fires when a mouse button is pressed down on an element

onmousemove

Mouse

Fires when the mouse pointer moves over an element

onmouseout

Mouse

Fires when the mouse pointer moves out of an element

onmouseover

Mouse

Fires when the mouse pointer moves over an element

onmouseup

Mouse

Fires when a mouse button is released over an element

Onscroll

Mouse

Script to be run when an element's scrollbar is being scrolled

Following example shows how a division reacts when we bring our mouse in that
division:
<html>
<head>
<script type="text/javascript">
<!-function over() {
alert("Mouse Over");
}

function out() {
alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div></body></html>

Output :

Bring your mouse inside the division to see the result:


This is inside the division

Dynamic HTML using with Javascript


Write a Javascript code to validate email address.
Form validation is the process of making sure that data supplied by the user using a form, meets the
criteria set for collecting data from the user. For example, if you are using a registration form, and you
want your user to submit name, email id and address, you must use a code (in JavaScript or in any other
language) to check whether user entered a name containing alphabets only, a valid email address and a
proper address.
JavaScript, provides a way to validate form's data on the client's computer before sending it to the web
server. Form validation generally performs two functions.

Basic Validation - First of all, the form must be checked to make sure data was entered into each
form field that required it. This would need just loop through each field in the form and check for
data.

Data Format Validation - Secondly, the data that is entered must be checked for correct form
and value. This would need to put more logic to test correctness of data.

Program for validating email address using regular expressions


<html>
<head> <title> Email Validation</title>

<script type="text/javascript">
function IsValidEmail(email) {

var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|


(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};

function ValidateEmail() {
var email = document.getElementById("txtEmail").value;
if (!IsValidEmail(email)) {
alert("Invalid email address.");}

else
alert("Valid email address.");
}

</script>
</head>
<body>

<form id="form1">
<input type="text" id="txtEmail" />
<input type="button" id="btnValidate" value="Validate
Email" onclick = "ValidateEmail()"/>
</form></body></html>

Write a Javascript code to Write to Other


Frames and Windows
You can also use the document.write( ) method to send dynamically created content
to another frame in a frameset or to another browser window previously opened by
a script in the same page. In this case, you are not restricted to only one call
to document.write( ) per page; you can open an output stream to another frame or
window and keep dumping stuff into it until you close the stream
withdocument.close( ).
JavaScript code to write dynamic content to another frame
<html>
<head>

<title>Welcome Page</title>
<script language="JavaScript" type="text/javascript">
// create custom page and replace current document with it
function rewritePage(form) {
// accumulate HTML content for new page
var newPage = "<html>\n<head>\n<title>Page for ";
newPage += form.entry.value;
newPage += "</title>\n</head>\n<body bgcolor='cornflowerblue'>\n";
newPage += "<h1>Hello, " + form.entry.value + "!</h1>\n";
newPage += "</body>\n</html>";
// write it in one blast
parent.instrux.document.write(newPage);
// close writing stream
parent.instrux.document.close( );
}
</script>
<body>
<h1>Welcome!</h1>
<hr>
<form onsubmit="return false;">
<p>Enter your name here: <input type="text" name="entry" id="entry"></P>
<input type="button" value="New Custom Page"
onclick="rewritePage(this.form);">
</form>
</body>
</html>

Write a Javascript code to illustrate Rollover buttons

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Test a Javascript Image Rollover by Boolanchai Wells</title>
<script language="javascript">
function MouseRollover(MyImage) {
MyImage.src = "MyPicture2.jpg";
}
function MouseOut(MyImage) {
MyImage.src = "MyPicture1.jpg";
}

</script>
</head>
<body>
<div align="center">
<!--The rollover image displays here.-->
<img src="MyPicture1.jpg" border="0px" width="650px" height="550px"
onMouseOver="MouseRollover(this)"
onMouseOut="MouseOut(this)" />
</div>
</body>
</html>
Implement a Floating logo.
With CSS float, an element can be pushed to the left or right, allowing other elements to wrap around
it.Float is very often used for images, but it is also useful when working with layouts.
Elements are floated horizontally, this means that an element can only be floated left or right, not up or
down.A floated element will move as far to the left or right as it can. Usually this means all the way to the
left or right of the containing element.The elements after the floating element will flow around it.The
elements before the floating element will not be affected. If an image is floated to the right, a following
text flows around it, to the left:
<html>
<head>
<style>
div{
float:right;
width:120px;
margin:0 0 15px 20px;
padding:15px;
border:1px solid black;
text-align:center;}
</style></head>
<body>

<div>
<img src="logocss.gif" width="95" height="84" /><br>
CSS is fun!
</div>
<p>
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>
<p>
In the paragraph above, the div element is 120 pixels wide and it contains the image.
The div element will float to the right.
Margins are added to the div to push the text away from the div.
Borders and padding are added to the div to frame in the picture and the caption.
</p>
</body></html>

Anda mungkin juga menyukai