+ All Categories
Home > Education > Web programming UNIT II by Bhavsingh Maloth

Web programming UNIT II by Bhavsingh Maloth

Date post: 19-May-2015
Category:
Upload: bhavsingh-maloth
View: 261 times
Download: 2 times
Share this document with a friend
Description:
this file contain information regards javascript and all
51
WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH 1 Objectives: Understand JavaScript. Understand Objects in JavaScript. Understand DHTML with JavaScript. History Of JavaScript: JavaScript,Which was Originally named like Live Script. javaScript was developed by Natesacpe’s Microsoft’s JavaScript is named like: Jscript What is JavaScript? Was designed to add interactivity to HTML pages Is a scripting language (a scripting language is a lightweight programming language) JavaScript code is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) JavsScript Can be divided into THREE parts: 1. Core Java Script. 2. Client Side Java Script. 3. Server Side JavaScript. CORE JAVA SCRIPT: Core is the heart of the language including it’s Operators Expressions,Statements,and Sub Programs. Client Side JavaScript: Client side Java Script is a collection of Objects,that support controls of a browser and Interactions with Users CLIENT-SIDE SCRIPTING generally refers to the class of computer programs on the web that are executed client- side, by the user's web browser, instead of server-side (on the web server) This type of computer programming is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variables. Web authors write client-side scripts in languages such as JavaScript (Client- side JavaScript) and VBScript. SERVER SIDE JAVASCRIPT: Server Side JavaScript is a collection of Objects that make the language use full on a webserver JavaScript is considered to be one of the most famous scripting languages of all time. JavaScript, by definition, is a Scripting Language of the World Wide Web.
Transcript
Page 1: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

1

Objectives: Understand JavaScript.

Understand Objects in JavaScript.

Understand DHTML with JavaScript.

History Of JavaScript: JavaScript,Which was Originally named like Live Script.

javaScript was developed by Natesacpe’s

Microsoft’s JavaScript is named like: Jscript What is JavaScript?

Was designed to add interactivity to HTML pages Is a scripting language (a scripting language is a lightweight programming language) JavaScript code is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

JavsScript Can be divided into THREE parts: 1. Core Java Script.

2. Client Side Java Script.

3. Server Side JavaScript. CORE JAVA SCRIPT:

Core is the heart of the language including it’s Operators Expressions,Statements,and Sub

Programs. Client Side JavaScript: Client side Java Script is a collection of Objects,that

support controls of a browser and Interactions with Users

CLIENT-SIDE SCRIPTING

generally refers to the class of computer programs on the web that are executed client-

side, by the user's web browser, instead of server-side (on the web server) This type of

computer programming is an important part of the Dynamic HTML (DHTML) concept,

enabling web pages to be scripted; that is, to have different and changing content

depending on user input, environmental conditions (such as the time of day), or other

variables. Web authors write client-side scripts in languages such as JavaScript (Client-

side JavaScript) and VBScript.

SERVER SIDE JAVASCRIPT:

Server Side JavaScript is a collection of Objects that make the language use full on a webserver

JavaScript is considered to be one of the most famous scripting languages of all time.

JavaScript, by definition, is a Scripting Language of the World Wide Web.

Page 2: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

2

The main usage of JavaScript is to add various Web functionalities, Web form validations,

browser detections, creation of cookies and so on. JavaScript, along with VBScript, is one of

the most popular scripting languages and that is why it is supported by almost all web

browsers available today like Firefox, Opera or the most famous Internet Explorer.

JavaScript is the most popular scripting language on the internet, and works in all major

browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

What is JavaScript?

JavaScript was designed to add interactivity to HTML pages

JavaScript is a scripting language

A scripting language is a lightweight programming language

JavaScript is usually embedded directly into HTML pages

JavaScript is an interpreted language (means that scripts execute without preliminary

compilation)

Everyone can use JavaScript without purchasing a license

Are Java and JavaScript the same?

NO!

Java and JavaScript are two completely different languages in both concept and design!

What can a JavaScript do?

JavaScript gives HTML designers a programming tool - HTML authors are normally not

programmers, but JavaScript is a scripting language with a very simple syntax! Almost

anyone can put small "snippets" of code into their HTML pages

JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:

document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

JavaScript can react to events - 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

Page 3: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

3

JavaScript can read and write HTML elements - A JavaScript can read and change the

content of an HTML element

JavaScript can be used to validate data - A JavaScript can be used to validate form data

before it is submitted to a server. This saves the server from extra processing

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect

the visitor's browser, and - depending on the browser - load another page specifically

designed for that browser

JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve

information on the visitor's computer

The Real Name is ECMAScript

JavaScript's official name is ECMAScript.

ECMAScript is developed and maintained by the ECMA organization.

ECMA-262 is the official JavaScript standard.

The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996.

The development of ECMA-262 started in 1996, and the first edition of was adopted by the ECMA General Assembly in June 1997.

The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.

The HTML <script> tag is used to insert a JavaScript into an HTML page.

JavaScript

JavaScript is a scripting language used to enable programmatic access to objects within

other applications. It is primarily used in the form of client-side JavaScript for the

development of dynamic websites. JavaScript is a dialect of the ECMAScript standard and is

characterized as a dynamic, weakly typed, prototype-based language with first-class

functions. JavaScript was influenced by many languages and was designed to look like Java,

but to be easier for non-programmers to work with.

JavaScript-specific

JavaScript is officially managed by Mozilla, and new language features are added

periodically. However, only some non-Mozilla "JavaScript" engines support these new features:

conditional catch clauses

property getter and setter functions

Page 4: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

4

iterator protocol adopted from Python

shallow generators/coroutines also adopted from Python

array comprehensions and generator expressions also adopted from Python

proper block scope via new let keyword

array and object destructuring (limited form of pattern matching)

concise function expressions (function(args) expr)

Use in web pages

The primary use of JavaScript is to write functions that are embedded in or included from

HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:

Opening or popping up a new window with programmatic control over the size, position, and

attributes of the new window (i.e. whether the menus, toolbars, etc. are visible).

Validation of web form input values to make sure that they will be accepted before they are

submitted to the server.

Changing images as the mouse cursor moves over them: This effect is often used to draw the

user's attention to important links displayed as graphical elements.

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 (meaning a variable can hold an object of any type and cannot

be restricted). 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, and JavaScript's Math and Date classes are based on those from Java 1.0.

JAVASCRIPT HOW TO .. .

EXAMPLES

Page 5: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

5

Write text

How to write text on a page

HOW TO PUT A JAVASCRIPT INTO AN HTML DOCUMENT

<html>

<head>

</head>

<body>

<script type="text/javascript">

document.write("Hello World!")

</script>

</body>

</html>

And it produces this output:

Hello World!

To insert a script in an HTML document, use the <script> tag. Use the type attribute to define the

scripting language.

<script type="text/javascript">

Then comes the JavaScript: In JavaScript the command for writing some text on a page is

document.write:

document.write("Hello World!")

The script ends:

</script>

INSERTING TEXT WITH HTML FORMATTING

Write text with formatting

How to format the text on your page with HTML tags

<html> <body> <script type="text/javascript"> document.write("<h1>Hello World!</h1>") </script> </body> </html>

Page 6: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

6

ENDING STATEMENTS WITH A SEMICOLON?

With the traditional programming languages C++ and Java, each code statement has to end with

a semicolon.

Many programmers continue this habit when writing JavaScript, but in general, semicolons are

optional and are required only if you want to put more than one statement on a single line.

HOW TO HANDLE OLDER BROWSERS

Older browsers that do not support scripts will display the script as page content. To prevent

them from doing this, you can use the HTML comment tag:

<script type="text/javascript">

<!--

some statements

//-->

</script>

The two forward slashes in front of the end of comment line (//) are a JavaScript comment

symbol, and prevent the JavaScript from trying to compile the line.

Note that you can't put // in front of the first comment line (like //<!--), because older browser

will display it. Funny? Yes ! But that's the way it is.

JAVASCRIPT VARIABLES

AN EXAMPLE OF VARIABLE USE

Variable

Variables are used to store data. This example shows you how:

<html> <body> <script type="text/javascript"> var name = "WECT" document.write(name) document.write("<h1>"+name+"</h1>>") </script> This example declares a variable, assigns a value to it, and then displays the variable.<P> Then the variable is displayed one more time, only this time within a heading element. </body> </html>

Page 7: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

7

VARIABLES

A variable is a "container" for information you want to store. A variable's value can change

during the script. You can refer to a variable by name to see its value or to change its value.

Rules for Variable names:

Variable names are case sensitive They must begin with a letter or the underscore character

DECLARE A VARIABLE

You can create a variable with the var statement:

var strname = some value

You can also create a variable without the var statement:

strname = some value

ASSIGN A VALUE TO A VARIABLE

You assign a value to a variable like this:

var strname = "Hege"

Or like this:

strname = "Hege"

The variable name is on the left side of the expression and the value you want to assign to the

variable is on the right. Now the variable "strname" has the value "Hege".

LIFETIME OF VARIABLES

When you declare a variable within a function, the variable can only be accessed within

that function. When you exit the function, the variable is destroyed. These variables are

called local variables. You can have local variables with the same name in different

functions, because each is recognized only by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it.

The lifetime of these variables starts when they are declared, and ends when the page is

closed.

Page 8: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

8

WHERE TO PUT YOUR JAVASCRIPT IN A WEB PAGE

Scripts in a page will be executed immediately while the page loads into the browser. This is not

always what we want. Sometimes we want to execute a script when a page loads, other times

when a user triggers an event.

Scripts in the head section: Scripts to be executed when they are called, or when an event is

triggered, go in the head section. When you place a script in the head section, you will ensure

that the script is loaded before anyone uses it.

<html>

<head>

<script type="text/javascript">

some statements

</script>

</head>

Scripts in the body section: Scripts to be executed when the page loads go in the body section.

When you place a script in the body section it generates the content of the page.

<html>

<head>

</head>

<body>

<script type="text/javascript">

some statements

</script>

</body>

Scripts in both the body and the head section: You can place an unlimited number of scripts

in your document, so you can have scripts in both the body and the head section.

<html>

<head>

<script type="text/javascript">

some statements

</script>

</head>

<body>

<script type="text/javascript">

some statements

</script>

</body>

HOW TO RUN AN EXTERNAL JAVASCRIPT

Page 9: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

9

Sometimes you might want to run the same script on several pages, without writing the

script on each and every page.

To simplify this you can write a script in an external file, and save it with a .js file

extension, like this:

document.write("This script is external")

Save the external file as xxx.js.

Note: The external script cannot contain the <script> tag

Now you can call this script, using the "src" attribute, from any of your pages:

<html>

<head>

</head>

<body>

<script src="xxx.js"></script>

</body>

</html>

Remember to place the script exactly where you normally would write the script.

EXAMPLES

Head section

Scripts that contain functions go in the head section of the document. Then we can be sure that

the script is loaded before the function is called.

<html> <head> <script type="text/javascript"> function message() { alert("This alert box was called with the onload event") } </script> </head> <body> </body> </html>

Body section

Execute a script that is placed in the body section.

<html> <body>

Page 10: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

10

<script type="text/javascript"> document.write("This message is written when the page loads") </script> </body> </html>

External script

How to access an external script.

<html> <head> <script src="xxx.js"></script> </head> <body> In this case, the script is in an external script file called "xxx.js". </body> </html>

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

JAVASCRIPT CONDITIONAL STATEMENTS

CONDITIONAL STATEMENTS

Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have three conditional statements:

if statement - use this statement if you want to execute a set of code when a condition is true

if...else statement - use this statement if you want to select one of two sets of lines to execute

switch statement - use this statement if you want to select one of many sets of lines to execute

IF AND IF...ELSE STATEMENT

You should use the if statement if you want to execute some code if a condition is true.

Page 11: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

11

SYNTAX

if (condition)

{

code to be executed if condition is true

}

EXAMPLE

//If the time on your browser is less than 10,

//you will get a "Good morning" greeting.

<script type="text/javascript">

var d=new Date()

var time=d.getHours()

if (time<10)

{

document.write("<b>Good morning</b>")

}

</script>

Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if the

condition is true.

If you want to execute some code if a condition is true and another code if a condition is false,

use the if....else statement.

SYNTAX

if (condition)

{

code to be executed if condition is true

}

else

{

code to be executed if condition is false

}

EXAMPLE

//If the time on your browser is less than 10,

//you will get a "Good morning" greeting.

//Otherwise you will get a "Good day" greeting.

<script type="text/javascript">

var d = new Date()

var time = d.getHours()

if (time < 10)

{

document.write("Good morning!")

Page 12: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

12

}

else

{

document.write("Good day!")

}

</script>

SWITCH STATEMENT

You should use the Switch statement if you want to select one of many blocks of code to be

executed.

SYNTAX

switch (expression)

{

case label1:

code to be executed if expression = label1

break

case label2:

code to be executed if expression = label2

break

default:

code to be executed

if expression is different

from both label1 and label2

}

This is how it works: First we have a single expression (most often a variable), that is evaluated

once. The value of the expression is then compared with the values for each case in the structure.

If there is a match, the block of code associated with that case is executed. Use break to prevent

the code from running into the next case automatically.

EXAMPLE

//You will receive a different greeting based

//on what day it is. Note that Sunday=0,

//Monday=1, Tuesday=2, etc.

<script type="text/javascript">

var d=new Date()

theDay=d.getDay()

switch (theDay)

{

case 5:

document.write("Finally Friday")

break

Page 13: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

13

case 6:

document.write("Super Saturday")

break

case 0:

document.write("Sleepy Sunday")

break

default:

document.write("I'm looking forward to this weekend!")

}

</script>

CONDITIONAL OPERATOR

JavaScript also contains a conditional operator that assigns a value to a variable based on

some condition.

SYNTAX

variablename=(condition)?value1:value2

EXAMPLE

greeting=(visitor=="PRES")?"Dear President ":"Dear "

If the variable visitor is equal to PRES, then put the string "Dear President " in the

variable named greeting. If the variable visitor is not equal to PRES, then put the string

"Dear " into the variable named greeting.

EXAMPLES

If statement

How to write an If statement. Use this statement if you want to execute a set of code if a

specified condition is true.

<html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) {

Page 14: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

14

document.write("<b>Good Morning</b>") } </script> <p>This example demonstrates the If statement. <p>If the time on your browser is less than 10, you will get a "Good Morning" greeting. </body> </html>

If...else statement

How to write an If...Else statement. Use this statement if you want to execute one set of code if

the condition is true and another set of code if the condition is false.

<html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("<b>Good Morning</b>") } else { document.write("<b>Good Day</b>") } </script> <p>This example demonstrates the If ... Else statement. <p>If the time on your browser is less than 10, you will get a "Good Morning" greeting. Otherwise you will get a "Good Day" greeting </body> </html>

Random link

This example demonstrates a link, when you click on the link it will take you to W3Schools.com

OR to W3AppML.com. There is a 50% chance for each of them.

<html> <body> <script type="text/javascript"> var r = Math.random() if (r>0.5) { document.write("<a href='http://www.w3schools.com'>Learn Web Development!<a>") } else {

Page 15: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

15

document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!<a>") } </script> <p>This example demonstrates the Math.random() method. <p>The Hyperlink included in the page depends on the state of a random variable. </body> </html>

Switch statement

How to write a switch statement. Use this statement if you want to select one of many blocks of

code to execute.

<html> <body> <script type="text/javascript"> var d = new Date() var theDay = d.getDay() switch (theDay) { case 5: document.write("<b>Finally Friday</b>") break case 6: document.write("<b>Super Saturday</b>") break case 0: document.write("<b>Sleepy Sunday</b>") break default: document.write("<b>Looking Forward to the Weekend</b>") } </script> <p>This example demonstrates the switch statement. <p>The text presented depends on the day of the week (0=Sunday, 1=Monday, 2=Tuesday, etc.) </body> </html>

POP BOXEX

Alert Box

An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax

Page 16: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

16

alert("sometext");

Example

<html>

<head>

<script type="text/javascript">

function show_alert()

{

alert("I am an alert box!"); }

</script>

</head>

<body>

<input type="button" onclick="show_alert()" value="Show alert box" />

</body>

</html>

Page 17: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

17

Confirm Box

A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax

confirm("sometext");

Example

<html>

<head>

<script type="text/javascript">

function show_confirm()

{ var r=confirm("Press a button");

if (r==true)

{

document.write("You pressed OK!");

}

else

{ document.write("You pressed Cancel!"); } }

</script>

</head>

<body>

<input type="button" onclick="show_confirm()" value="Show confirm box" />

</body>

</html>

Prompt Box A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after

entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box

returns null.

Syntax

prompt("sometext","defaultvalue");

Example

<html>

<head>

<script type="text/javascript">

function show_prompt()

{

Page 18: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

18

var name=prompt("Please enter your name","Harry Potter");

if (name!=null && name!="")

{

document.write("Hello " + name + "! How are you today?");

}

}

</script>

</head>

<body>

<input type="button" onclick="show_prompt()" value="Show prompt box" />

</body>

</html>

JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script

into a function.

A function contains code that will be executed by an event or by a call to the function.

You may call a function from anywhere within a page (or even from other pages if the

function is embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document.

However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section.

This is JavaScript's method to alert the user.

alert("here goes the message")

HOW TO DEFINE A FUNCTION:

To create a function you define its name, any values ("arguments"), and some statements:

function myfunction(argument1,argument2,etc)

{

some statements

}

A function with no arguments must include the parentheses:

Page 19: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

19

function myfunction()

{

some statements

}

Arguments are variables that will be used in the function. The variable values will be the

values passed on by the function call.

By placing functions in the head section of the document, you make sure that all the code

in the function has been loaded before the function is called.

Some functions return a value to the calling expression

function result(a,b)

{

c=a+b

return c

}

HOW TO CALL A FUNCTION:

A function is not executed before it is called.

You can call a function containing arguments:

myfunction(argument1,argument2,etc)

or without arguments:

myfunction()

THE RETURN STATEMENT:

Functions that will return a result must use the "return" statement. This statement

specifies the value which will be returned to where the function was called from. Say you

have a function that returns the sum of two numbers:

function total(a,b)

{

result=a+b

return result

}

When you call this function you must send two arguments with it:

sum=total(2,3)

Page 20: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

20

The returned value from the function (5) will be stored in the variable called sum.

EXAMPLES

Function

How to call a function.

<html> <head> <script type="text/javascript"> function myfunction() { alert("HELLO") } </script> </head> <body> <form> <input type="button" onclick="myfunction()" value="Call function"> </form> <p>By pressing the button, a function will be called. The function will alert a message. </body> </html>

Function with arguments

How to pass a variable to a function, and use the variable value in the function.

<html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Hello')" value="Call function"> </form> <p>By pressing the button, a function will be called. The function will alert using the argument text. </body> </html>

Page 21: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

21

Function with arguments 2

How to pass variables to a function, and use these variable values in the function.

<html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Good Morning')" value="In the Morning"> <input type="button" onclick="myfunction('Good Evening')" value="In the Evening"> </form> <p>By pressing a button, a function will be called. The function will alert using the argument passed to it. </body> </html>

Function that returns a value

How to let the function return a value.

<html> <head> <script type="text/javascript"> function myfunction() { return ("Hello, have a nice day!") } </script> </head> <body> <script type="text/javascript"> document.write(myFunction()) </script> <p>The function returns text. </body> </html>

A function with arguments, that returns a value

How to let the function find the sum of 2 arguments and return the result.

Page 22: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

22

<html> <head> <script type="text/javascript"> function total(numberA,numberB) { return numberA + numberB } </script> </head> <body> <script type="text/javascript"> document.write(total(2,3)) </script> <p>The script in the body section calls a function with two arguments: 2 and 3. <p>The function returns the sum of these two arguments. </body> </html>

JAVASCRIPT OBJECT

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

language can be called object-oriented if it provides four basic capabilities to developers:

Encapsulation . the capability to store related information, whether data or methods,

together in an object

Aggregation . the capability to store one object inside of another object

Inheritance . the capability of a class to rely upon another class (or number of classes)

for some of its properties and methods

Polymorphism . the capability to write one function or method that works in a variety of

different ways

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

be a method of the object otherwise, the attribute is considered a property.

OBJECT PROPERTIES:

Object properties can be any of the three primitive data types, or any of the abstract data

types, such as another object. Object properties are usually variables that are used

Page 23: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

23

internally in the object's methods, but can also be globally visible variables that are used

throughout the page.

The syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;

EXAMPLE:

Following is a simple example to show how to get a document title using "title" property of

document object:

var str = document.title;

OBJECT METHODS:

The methods are functions that let the object do something or let something be done to it.

There is little difference between a function and a method, except that a function is a

standalone unit of statements and a method is attached to an object and can be

referenced by the this keyword.

Methods are useful for everything from displaying the contents of the object to the screen

to performing complex mathematical operations on a group of local properties and

parameters.

EXAMPLE:

Following is a simple example to show how to use write() method of document object to write

any content on the document:

document.write("This is test");

USER-DEFINED OBJECTS:

Page 24: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

24

All user-defined objects and built-in objects are descendants of an object called Object.

THE NEW OPERATOR:

The new operator is used to create an instance of an object. To create an object, the new

operator is followed by the constructor method.

In the following example, the constructor methods are Object(), Array(), and Date(). These

constructors are built-in JavaScript functions.

var employee = new Object();

var books = new Array("C++", "Perl", "Java");

var day = new Date("August 15, 1947");

THE OBJECT() CONSTRUCTOR:

A constructor is a function that creates and initializes an object. JavaScript provides a

special constructor function called Object() to build the object. The return value of the

Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned to the object

are not variables and are not defined with the var keyword.

EXAMPLE 1:

This example demonstrates how to create an object:

<html>

<head>

<title>User-defined objects</title>

<script type="text/javascript">

var book = new Object(); // Create the object

book.subject = "Perl"; // Assign properties to the object

book.author = "Mohtashim";

</script>

</head>

<body>

Page 25: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

25

<script type="text/javascript">

document.write("Book name is : " + book.subject + "<br>");

document.write("Book author is : " + book.author + "<br>");

</script>

</body> </html>

EXAMPLE 2:

This example demonstrates how to create an object with a User-Defined Function. Here

this keyword is used to refer to the object that has been passed to a function:

<html>

<head>

<title>User-defined objects</title>

<script type="text/javascript">

function book(title, author){

this.title = title;

this.author = author;

}

</script>

</head>

<body>

<script type="text/javascript">

var myBook = new book("Perl", "Mohtashim");

document.write("Book title is : " + myBook.title + "<br>");

document.write("Book author is : " + myBook.author + "<br>");

</script>

</body>

</html>

JAVASCRIPT NATIVE OBJECTS:

Javascript - Strings

Javascript - Date

Page 26: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

26

Javascript - Boolean

Javascript - Math

Javascript - Date:

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

SYNTAX:

Here are different variant of Date() constructor:

new Date( )

new Date(milliseconds)

new Date(datestring)

new Date(year,month,date[,hour,minute,second,millisecond ])

Note: Paramters in the brackets are always optional

Here is the description of the parameters:

No Argument: With no arguments, the Date( ) constructor creates a Date object set to

the current date and time.

milliseconds: When one numeric argument is passed, it is taken as the internal numeric

representation of the date in milliseconds, as returned by the getTime( ) method. For

example, passing the argument 5000 creates a date that represents five seconds past

midnight on 1/1/70.

datestring:When one string argument is passed, it is a string representation of a date, in

the format accepted by the Date.parse( ) method.

7 agruments: To use the last form of constructor given above, Here is the description of

each argument:

1. year: Integer value representing the year. For compatibility (in order to avoid the

Y2K problem), you should always specify the year in full; use 1998, rather than

98.

2. month: Integer value representing the month, beginning with 0 for January to 11

for December.

3. date: Integer value representing the day of the month.

4. hour: Integer value representing the hour of the day (24-hour scale).

5. minute: Integer value representing the minute segment of a time reading.

6. second: Integer value representing the second segment of a time reading.

7. millisecond: Integer value representing the millisecond segment of a time

reading.

DATE PROPERTIES:

Page 27: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

27

Here is a list of each property and their description.

Property Description

constructor Specifies the function that creates an object's prototype.

prototype The prototype property allows you to add properties and methods to an object.

DATE METHODS:

Here is a list of each method and its description.

Method Description

Date() Returns today's date and time

getDate()

Returns the day of the month for the specified date according to local time.

getDay()

Returns the day of the week for the specified date according to local time.

getFullYear() Returns the year of the specified date according to local time.

getHours() Returns the hour in the specified date according to local time.

getMilliseconds() Returns the milliseconds in the specified date according to local time.

getMinutes() Returns the minutes in the specified date according to local time.

getMonth() Returns the month in the specified date according to local time.

getSeconds() Returns the seconds in the specified date according to local time.

getTime()

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Page 28: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

28

getTimezoneOffset() Returns the time-zone offset in minutes for the current locale.

getUTCDate()

Returns the day (date) of the month in the specified date according to universal time.

getUTCDay()

Returns the day of the week in the specified date according to universal time.

getUTCFullYear() Returns the year in the specified date according to universal time.

getUTCHours() Returns the hours in the specified date according to universal time.

getUTCMilliseconds()

Returns the milliseconds in the specified date according to universal time.

getUTCMinutes()

Returns the minutes in the specified date according to universal time.

getUTCMonth() Returns the month in the specified date according to universal time.

getUTCSeconds() Returns the seconds in the specified date according to universal time.

getYear()

Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.

setDate() Sets the day of the month for a specified date according to local time.

setFullYear() Sets the full year for a specified date according to local time.

setHours() Sets the hours for a specified date according to local time.

setMilliseconds() Sets the milliseconds for a specified date according to local time.

setMinutes() Sets the minutes for a specified date according to local time.

setMonth() Sets the month for a specified date according to local time.

setSeconds() Sets the seconds for a specified date according to local time.

Page 29: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

29

setTime()

Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

setUTCDate()

Sets the day of the month for a specified date according to universal time.

setUTCFullYear() Sets the full year for a specified date according to universal time.

setUTCHours() Sets the hour for a specified date according to universal time.

setUTCMilliseconds() Sets the milliseconds for a specified date according to universal time.

setUTCMinutes() Sets the minutes for a specified date according to universal time.

setUTCMonth() Sets the month for a specified date according to universal time.

setUTCSeconds() Sets the seconds for a specified date according to universal time.

setYear()

Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.

toDateString() Returns the "date" portion of the Date as a human-readable string.

toGMTString()

Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.

toLocaleDateString()

Returns the "date" portion of the Date as a string, using the current locale's conventions.

toLocaleFormat() Converts a date to a string, using a format string.

toLocaleString() Converts a date to a string, using the current locale's conventions.

toLocaleTimeString()

Returns the "time" portion of the Date as a string, using the current locale's conventions.

toSource()

Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.

Page 30: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

30

toString() Returns a string representing the specified Date object.

toTimeString() Returns the "time" portion of the Date as a human-readable string.

toUTCString() Converts a date to a string, using the universal time convention.

valueOf() Returns the primitive value of a Date object.

Example on Date():

Date

Returns today's date including date, month, and year. Note that the getMonth method returns 0 in

January, 1 in February etc. So add 1 to the getMonth method to display the correct date.

<html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(".") document.write(d.getFullYear()) </script> </body> </html>

Time

Returns the current local time including hour, minutes, and seconds. To return the GMT time use

getUTCHours, getUTCMinutes etc.

<html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getHours()) document.write(".")

Page 31: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

31

document.write(d.getMinutes() + 1) document.write(".") document.write(d.getSeconds()) </script> </body> </html>

Set date

You can also set the date or time into the date object, with the setDate, setHour etc. Note that in

this example, only the FullYear is set.

<html> <body> <script type="text/javascript"> var d = new Date() d.setFullYear("1990") document.write(".") </script> </body> </html>

UTC time

The getUTCDate method returns the Universal Coordinated Time which is the time set by the

World Time Standard.

<html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getUTCHours()) document.write(".") document.write(d.getUTCMinutes() + 1) document.write(".") document.write(d.getUTCSeconds()) </script> </body> </html>

Display weekday

A simple script that allows you to write the name of the current day instead of the number. Note

that the array object is used to store the names, and that Sunday=0, Monday=1 etc.

<html> <body> <script type="text/javascript">

Page 32: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

32

var d = new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") document.write("Today is " + weekday[d.getDay()]) </script> </body> </html>

Display full date

How to write a complete date with the name of the day and the name of the month.

<html> <body> <script type="text/javascript"> var d = new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") document.write(weekday[d.getDay()] + " ") document.write(d.getDate() + ". ") document.write(monthname[d.getMonth()] + " ") document.write(d.getFullYear()) </script> </body> </html>

Display time

How to display the time on your pages. Note that this script is similar to the Time example

above, only this script writes the time in an input field. And it continues writing the time one

time per second.

<html> <body> <script type="text/javascript"> var timer = null

function stop()

{

clearTimeout(timer)

}

function start()

{

var time = new Date()

Page 33: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

33

var hours = time.getHours()

minutes=((minutes < 10) ? "0" : "") + minutes

var seconds = time.getSeconds()

seconds=((seconds < 10) ? "0" : "") + seconds

var clock = hours + ":" + minutes + ":" + seconds

document.forms[0].display.value = clock

timer = setTimeout("start()",1000)

}

</script>

</body>

</html>

JAVASCRIPT - THE STRING OBJECT:

SYNTAX:

Creating a String object:

var val = new String(string);

The string parameter is series of characters that has been properly encoded.

STRING PROPERTIES:

Here is a list of each property and their description.

Property Description

constructor Returns a reference to the String function that created the object.

length Returns the length of the string.

prototype The prototype property allows you to add properties and methods to an object.

EXAMPLE: STRING LENGTH

Page 34: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

34

STRING METHODS

Here is a list of each method and its description.

Method Description

charAt() Returns the character at the specified index.

charCodeAt()

Returns a number indicating the Unicode value of the character at the given index.

concat() Combines the text of two strings and returns a new string.

indexOf()

Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

lastIndexOf()

Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

localeCompare()

Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

Page 35: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

35

match() Used to match a regular expression against a string.

replace()

Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

search()

Executes the search for a match between a regular expression and a specified string.

slice() Extracts a section of a string and returns a new string.

split()

Splits a String object into an array of strings by separating the string into substrings.

substr()

Returns the characters in a string beginning at the specified location through the specified number of characters.

substring() Returns the characters in a string between two indexes into the string.

toLocaleLowerCase()

The characters within a string are converted to lower case while respecting the current locale.

toLocaleUpperCase()

The characters within a string are converted to upper case while respecting the current locale.

toLowerCase() Returns the calling string value converted to lower case.

toString() Returns a string representing the specified object.

toUpperCase() Returns the calling string value converted to uppercase.

valueOf() Returns the primitive value of the specified object.

Example:

FINDING A STRING IN A STRING

Page 36: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

36

The indexOf() method returns the position (as a number) of the first found occurrence of a

specified text inside a string:

EXAMPLE

var str="Hello world, welcome to the universe.";

var n=str.indexOf("welcome");// index starts from “0”

MATCHING CONTENT

The match() method can be used to search for a matching content in a string:

EXAMPLE

var str="Hello world!"; document.write(str.match("world") + "<br>"); document.write(str.match("World") + "<br>"); document.write(str.match("world!"));

REPLACING CONTENT

The replace() method replaces a specified value with another value in a string.

EXAMPLE

str="Please visit Microsoft!" var n=str.replace("Microsoft","gpcet");

UPPER CASE AND LOWER CASE

A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():

EXAMPLE

var txt="Hello World!"; // String var txt1=txt.toUpperCase(); // txt1 is txt converted to upper

Page 37: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

37

var txt2=txt.toLowerCase(); // txt2 is txt converted to lower

JAVASCRIPT - THE MATH OBJECT

The math object provides you properties and methods for mathematical constants and functions.

Unlike the other global objects, Math is not a constructor. All properties and methods of Math

are static and can be called by using Math as an object without creating it.

SYNTAX:

Here is the simple syntax to call properties and methods of Math.

var pi_val = Math.PI;

var sine_val = Math.sin(30);

MATH PROPERTIES:

Here is a list of each property and their description.

Property Description

E Euler's constant and the base of natural logarithms, approximately 2.718.

LN2 Natural logarithm of 2, approximately 0.693.

LN10 Natural logarithm of 10, approximately 2.302.

LOG2E Base 2 logarithm of E, approximately 1.442.

LOG10E Base 10 logarithm of E, approximately 0.434.

PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.

SQRT1_2

Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.

Page 38: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

38

SQRT2 Square root of 2, approximately 1.414.

MATH METHODS

Here is a list of each method and its description.

Method Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

asin() Returns the arcsine (in radians) of a number.

atan() Returns the arctangent (in radians) of a number.

atan2() Returns the arctangent of the quotient of its arguments.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns the cosine of a number.

exp()

Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is, base exponent.

random() Returns a pseudo-random number between 0 and 1.

Page 39: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

39

round() Returns the value of a number rounded to the nearest integer.

sin() Returns the sine of a number.

sqrt() Returns the square root of a number.

tan() Returns the tangent of a number.

toSource() Returns the string "Math".

EXAMPLE:

Round

How to round a specified number to the nearest whole number

<html>

<body>

<script type="text/javascript">

document.write(Math.round(7.25))

</script>

</body>

</html>

Random number

The random method returns a random number between 0 and 1

<html>

<body>

<script type="text/javascript">

document.write(Math.random())

</script>

</body>

</html>

Random number from 0-10

How to write a random number from 0 to 10, using the round and the random method.

Page 40: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

40

<html>

<body>

<script type="text/javascript">

no=Math.random()*10

document.write(Math.floor(no))

</script>

</body>

</html>

Max number

How to test which of two numbers, has the highest value.

<html>

<body>

<script type="text/javascript">

document.write(Math.max(2,4))

</script>

</body>

</html>

Min number

How to test which of two numbers, has the lowest value.

<html>

<body>

<script type="text/javascript">

document.write(Math.min(2,4))

</script>

</body>

</html>

JAVASCRIPT - THE BOOLEAN OBJECT

The Boolean object represents two values either "true" or "false".

SYNTAX:

Creating a boolean object:

var val = new Boolean(value);

Page 41: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

41

If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the

object has an initial value of false.

BOOLEAN PROPERTIES:

Here is a list of each property and their description.

Property Description

constructor Returns a reference to the Boolean function that created the object.

prototype The prototype property allows you to add properties and methods to an object.

BOOLEAN METHODS

Here is a list of each method and its description.

Method Description

toSource()

Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.

toString()

Returns a string of either "true" or "false" depending upon the value of the object.

valueOf() Returns the primitive value of the Boolean object.

JAVA SCRIPT EVENTS:

WHAT IS AN EVENT ?

JavaScript's interaction with HTML is handled through events that occur when the user or

browser manipulates a page.

Page 42: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

42

HTML 4 STANDARD EVENTS

The standard HTML 4 events are listed here for your reference. Here script indicates a

Javascript function to be executed agains that event.

Event Value Description

onchange script Script runs when the element changes

onsubmit script Script runs when the form is submitted

onreset script Script runs when the form is reset

onselect script Script runs when the element is selected

onblur script Script runs when the element loses focus

onfocus script Script runs when the element gets focus

onkeydown script Script runs when key is pressed

onkeypress script Script runs when key is pressed and released

onkeyup script Script runs when key is released

onclick script Script runs when a mouse click

ondblclick script Script runs when a mouse double-click

onmousedown script Script runs when mouse button is pressed

onmousemove script Script runs when mouse pointer moves

onmouseout script Script runs when mouse pointer moves out of an

Page 43: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

43

element

onmouseover script Script runs when mouse pointer moves over an element

onmouseup script Script runs when mouse button is released

ONCLICK EVENT TYPE:

This is the most frequently used event type which occurs when a user clicks mouse left button.

You can put your validation, warning etc against this event type.

EXAMPLE:

<html>

<head>

<script type="text/javascript">

<!--

function sayHello() {

alert("Hello World")

}

//-->

</script>

</head>

<body>

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>

</html>

ONSUBMIT EVENT TYPE:

Another most important event type is onsubmit. This event occurs when you try to submit a

form. So you can put your form validation against this event type.

Here is simple example showing its usage. Here we are calling a validate() function before

submitting a form data to the webserver. If validate() function returns true the form will be

submitted otherwise it will not submit the data.

EXAMPLE:

Page 44: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

44

<html>

<head>

<script type="text/javascript">

<!--

function validation() {

all validation goes here

.........

return either true or false

}

//-->

</script>

</head>

<body>

<form method="POST" action="t.cgi" onsubmit="return validate()">

.......

<input type="submit" value="Submit" />

</form>

</body>

</html>

ONMOUSEOVER AND ONMOUSEOUT:

These two event types will help you to create nice effects with images or even with text as

well. The onmouseover event occurs when you bring your mouse over any element and the

onmouseout occurs when you take your mouse out from that element.

EXAMPLE:

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>

Page 45: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

45

</html>

List of Javascript Programs:

JAVASCRIPT PROGRAMS WITH EXAMPLES

Fibonacci Series JavaScript Program (for beginners)

This is a simple JavaScript example program for fibonacci sequence.

<body> <script type="text/javascript"> var a=0,b=1,c; document.write("Fibonacci"); while (b<=10) { document.write(c); document.write("<br/>"); c=a+b; a=b; b=c; } </script> </body> </html>

Copy Text JavaScript Program (for beginners)

This is simple JavaScript Program with example to Copy Text from Different Field. <

Page 46: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

46

html> <head> <title> Copy text</title> </head> <body> <center> <h2>Copy text from different field</h2> <p> <input type="text" style="color: #FF0080;background-color: #C9C299" id="field1" value="Good Morning"> <input type="text" style="color: #FF0080;background-color: #C9C299" id="field2"> <button style="background-color: #E799A3" onclick="document.getElementById('field2').value = document.getElementById('field1').value">Click to Copy Text </p> </center> </body> </html>

Form Validation JavaScript Program (for beginners)

This is a simple JavaScript form validation program with example.

<html> <head> <script type="text/javascript"> function sub() { if(document.getElementById("t1").value == "") alert("Please enter your name"); else if(document.getElementById("t2").value == "") alert("Please enter a password"); else if(document.getElementById("t2").value != document.getElementById("t3").value) alert("Please enter correct password"); else if(document.getElementById("t4").value == "") alert("Please enter your address"); else alert("Form has been submitted"); } </script> </head> <body> <form> <p align="center">

Page 47: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

47

User Name:<input type="text" id="t1"><br><br> Password:<input type="text" id="t2"><br><br> Confirm Password:<input type="text" id="t3"><br><br> Address:<textarea rows="2" cols="25" id="t4"></textarea><br><br> <input type="button" value="Submit" onclick="sub()"> <input type="reset" value="Clear All"> </p> </form> </body> </html>

JavaScript Popup Window Program (for beginners)

This is a simple JavaScript example program to generate confirm box.

<html> <head> <script type="text/javaScript"> function see() { var c= confirm("Click OK to see Google Homepage or CANCEL to see Bing Homepage"); if (c== true) { window.location="http://www.google.co.in/"; } else { window.location="http://www.bing.com/"; } } </script> </head> <body> <center> <form> <input type="button" value="Click to chose either Google or Bing" onclick="see()"> </form> </center> </body> </html>

Page 48: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

48

Palindrome JavaScript Program (for beginners)

This is a simple JavaScript palindrome program with example.

<html> <body> <script type="text/javascript"> function Palindrome() { var revStr = ""; var str = document.getElementById("str").value; var i = str.length; for(var j=i; j>=0; j--) { revStr = revStr+str.charAt(j); } if(str == revStr) { alert(str+" -is Palindrome"); } else { alert(str+" -is not a Palindrome"); } } </script> <form > Enter a String/Number: <input type="text" id="str" name="string" /><br /> <input type="submit" value="Check" onclick="Palindrome();"/> </form> </body> </html>

Check Odd/Even Numbers JavaScript Program (for beginners)

This is a simple JavaScript program to check odd or even numbers with example.

<html> <head> <script type="text/javascript">

Page 49: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

49

var n = prompt("Enter a number to find odd or even", "Type your number here"); n = parseInt(n); if (isNaN(n)) { alert("Please Enter a Number"); } else if (n == 0) { alert("The number is zero"); } else if (n%2) { alert("The number is odd"); } else { alert("The number is even"); } </script> </head> <body> </body> </html>

Simple Switch Case JavaScript Program (for beginners)

This is a simple switch case JavaScript example program for beginners..

<html> <head> <script type="text/javascript"> var n=prompt("Enter a number between 1 and 7"); switch (n) { case (n="1"): document.write("Sunday"); break; case (n="2"): document.write("Monday"); break; case (n="3"): document.write("Tuesday");

Page 50: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

50

break; case (n="4"): document.write("Wednesday"); break; case (n="5"): document.write("Thursday"); break; case (n="6"): document.write("Friday"); break; case (n="7"): document.write("Saturday"); break; default: document.write("Invalid Weekday"); break } </script> </head> </html>

ALL THE BEST

Page 51: Web programming UNIT II by Bhavsingh Maloth

WEB PROGRAMMING UNIT-II NOTES: PREPARED BY BHAVSINGH MALOTH

51


Recommended