Great Reads

Welcome to the world of Greatreads. You can find old as well as newer reads.

Monday, June 30, 2008

Learn Javascript




JavaScript





Introduction

Today's web sites need to go much beyond HTML.There is a definite need to
allow users,browsing through a web site,to actually interact with the web
site.The web site must be intelligent enough to accept users input and dynamically
structure web page content,tailer made,to a user's requirements.



This may be as simple as ensuring a web page delivered to a user,having a
background color that the user is confortable with of as complex as delivering
a web page with special textual formatting for a user with visul disabilities.


The
need to return standard HTML Pages,that map to a user's input ,is due to the
fact that brosers use HTTP to communicate with a web server and are designed
to interpret and render HTML on a client's machine.


The
web site development enviroment should also provide the facility for 'validating'
user input.Invalid user input,will either cause data to be sent back
from the web server to the browser,which is not what the user wants or give
rise to an error message being sent back to the browser from the web server.Neither
of which would really attract repeat visits to the web site.

Hence,the web site development environment must also faciitate coding which
runs in a browser at client side or data validation.Most developement environments
offer standard constructs for data validation.Standard Programming constructs
are:





  • Condition
    checking constructs


  • Case checking
    constructs

  • Super controlled
    Loop Constructs


Additionally ,all
development environment provide syntax to create and use memory variables,constants
and functions.

IF the development environment is obejct oriented it will provide an object
hierarchy to work with.An Object Oriented Programming(OOP)environment always
offers event driven programming.This means that the programming environment
will recognize object based events and allow the connection of code snippets
to these events.When an event occurs, the code snippets will execute.


Netscape
and javascript


Javascript is a
scripting language(web site development environment)created by Netscape hence
Javascript works best with the Netscape suite of client and server products.


The Netscape client
'browser'product is called Netscape Communicator.The default scripting langauge
that Netscape Communicator understands is Javascript.


Database
Connectivity


Netscape has a
product called 'Livve Wire'.which permits server side.Javascript code,to connect
to Realational Database Management Systems(RDBMS).RDBMS such as Oracle.MS SQL
Server,MySQL and a host of other widely used relational database,which use generally
use ANSI SQL as their natural language.'Live Wire' database drivers also support
a number of non -relations databases.


Client
side javascript


Client-side,javascript
is traditionally embedded into a standard HTML program .Javascript is embedded
between the <script>......</script>HTML tags.These tags can are
embedded within the <Head>.......</head>or <body>.......</body>
tags of the HTML program.

Javascript is embedded into an HTML program because Javascript uses the filename.html
and the HTTP protocol to transport itself from the web server to the client's
browser where the Javascript executes and processes client information.

Only a browwser that is Javascript enabled will be able to interpret Javascript
code.Netscape Communicator does this best as Javascript is the natural langauge
of Netscape Communicator.

Microsoft's Internet Explorer also interprets Javascript.However,Internet Explorer
latest releases support an old version of Javascript.Hence,the total functionality
of the latest release of Javascript as is available in Netscape Communicator
is not available in Internet Explorer.


Javascript is an
object-oriented langauge that allows creation of interactive web pages,Javascript
allows user entries,which are loaded into an HTML form to be processed as reequired
.This empowers a web site to return site information according to a user's requests.


Javascript offers
several advantages to a web developer .A short development cycle .Ease of learing.Small
size scripts .The strengths Of Javascript can be easily and quickly used to
extend the functionally of HTML pages,already on a web site.



Variable


        A
Variable is a data storage in memory we can imagine memory as a series of
cubyholes or box.Each box will have the Numerical address.

The literal name of the box is called variable with the help of the variable
we can strore the data in it ir retrieve the data fpr manipulation.


Variable
naming Convention:





  1. Every
    variable name must start with character/underscore


  2. No space

  3. No special character(.,%,*,etc)

  4. No Keyword(eg
    if,else)


Declaring
a variable in Javascript


var x;

var age;

var name;



Example


<html>

<head>

<title>Javascript sample page</title>

</head>

<body>

<script langauge="javascript">

var x;

x=10;

document.write("value of x ="+x )

</script>

</body>




Operators and expressions on Javascript


An operator is
used to transform one or more values into a single resultant value.The values
to which the opertaor is referred to as operands .A combination of an operator
and its operands is referred to as an expression.

Expressions are evaluated to determine the value of the expression.This is the
value that results when an opertors is applied to its operands.


Arithmetic
Operators



































Operator Description
+ Addition
- Subtraction
or uniary negation
* Multiplication
/ Division
% Modulus
++ Returs
the value then Increment
-- Return
the value then Decrement

 


An operator requiring
a single is referred to as a uniary operator and one that requires two operands
is a binary operator

The above standard arithemetic operators are binary operators.In addition to
these binary operators,there are unary arithemetic operator.They are (++) and
(--)

Both these increment and decrement operators can be used in two different ways.Before
the operand or after the operand .For example,++x increment x by one and returns
the result,While x++ returns x and then increment the value of x by one.similarly,--x
decreases the value of x by one before returing a result,while x-- return the
value of x before decreasing its value by one.


Example

x=3

y=++x

z=x++

In these lines of code, X is first assigned the value of 3,which is then increased
to 4 and assigned to Y.The new value of 4 is assigned to Z,and the value of
x is increased to 5.Finally,x is 5,y is 4 and z is 4.


Logical
Operators

Logical operators are used to perform Boolean Operators on Boolean
Operand and,or,not.The logical operators supported by javascript are:



















Operator Description
&& and
|| or
! not

Comparison
Operator


Comaparison Opertors
are used to compare two values.The comparison opertors supported by javascript.







































Operator Description
=
=
Equal
=
= =
Strictly
Equal
!= not
Equal
!=
=
Strictly
not equal
< Less
then
<= Less
than or equal to
> Greater
than
>= Greater
than or equal to



String Operator

String Operators are those operators that are used to perform operation on strings.Currently
Javascript supported only the string concatenation(+) operator.


This operator is
used to join two strings.Eg. "pq"+ "ab" produce "pqab".




Specail Operators

Javascript support a number of special operators that do not fit into the operator
categories covered above.


The delete
Operator


The delete operator
is used to delete a property of an element at an arrray index.

Example

delete myarray[5]

Deletes the sixth element of myarray



The new operators


The new operator
is used to create an instance of an object type.

Example

myArray=new Array()

This will create a new javascript object of the type array assign this array
to a context area in memory called myArray.



The Void operator:

The void operator does not return a value.It is typically used ub javascript
to return a URL with no value.


Javascript
programmming constructs


Most Programming
langauge support a common set of construct.Langauges only differ in the syntax
used for structuring these constructs.

Javascript provides a complete range of basic programming constructs.While it
is not an object oriented programming environment Javascript is an object-based
language.









































































Construct Purpose Example
Assignment Assigns
the value of an expression to avariable
x=y+z
data
declaration
Declares
a variable and optionally assigns a value to it.
var
x=10
if Program
execution depends upon the value of returned by the condition.If the value
returned is True the program executes else the program doesnot execute
if(x>y)

{

      z=x

}
switch Select
from a number of alternatives
switch(num)

{

Case 1:

   //statement

break;

Case 2:

//statement

break;

default

   //default action
While Repeatedly
executes a set of statements until a condition becomes false
while(x!=7)

  {

     x=n

    }
For Repeatedly
executes a set of statements untill a condition becomes false
For(i=1;i<7;i++)

{

    document.write

("Himalayanweb.com")

}
do
while
Repeatedly
executes a set of satements while a condition is true
do


{

//statement

}while(i>0)
lable Associate
a label with a statement
Label
Name:

statement
break Immediately
terminates a do while or for loop construct
if(x>y)continue
continue Immediately
terminates the current iteration of a do,while or forn construct
if<x>y)continue
function
call
Invokes
a function
x=abs(y)
return Returns
a value from a function call
return
x*y
with Indentifies
the default object
with(Math)

{

d=P*2*r;

}

 


CONDITIONAL
CHECKING


if - then-else

The conditional construct in javascript offers a simple way to make a decision
in a Javascript program.The conditional construct in Javascript will either
return a 'True' or a 'False' depending upon how the 'condition' evaluated.

using the if-else construct the flow of the javascript program can be altered
.The if condition determines which section of the program code will be executed
based on whether the condition evaluates to TRUE or FALSE.

Syntax

if(condition)

{

        statements

}



Example

var x=1

if(x= =1)

{

       document.write("The value is
one")

}


LOOP


Looping refers
to the ability if a block of code to reapeat itself.This repetition can be for
a predefined number of times or it can go until certain conditions are met.

Javascript offers 2 type of loop structures:

For loops: These loops iterate a specific number of times as
specified

While Loops:These are conditional Loops,which continue untill
a condition is met.


For Loop

The for loop is the most basic type of loop and resembles a for loop
in most other programming languages,including ASCI 'C'

Syntax

for(expression1;conditional;expression2)

{

         statements

}

Where



  • expression1
    sets up a couter variable and assigns the initial value.The declaration of
    the counter variable can also be done here itself

  • condition specifies
    the final value for the loop ti fire

  • expression2
    specifies how the initial value in expression1 is incremented.


Example

<html>

<head>

<Title>For loop</Title>

</head>

<body>

<script language="javascript">

var i;

for(i=1;i<=10;i++)

{

      document.write("<br>"+i)

}

</script>

</body>

</html>


While Loop

The while loop provides a simialar functionally.The basic structure
of a while loop is :

Syntax

while(condition)

{

          Statements

}

Where,the condition is a valid javascript expression that evaluates to a Boolean
value.The Javascript commands executed as long as the codition is true.



Example



<html>

<head>

<Title>While loop</Title>

</head>

<body>

<script language="javascript">

var num=1;

while(num<=10)

{

     document.write(num);

     num++

}

</script>

</body>

</html>


Functions
in javascript


Functions are blocks of Javascript code that peroform a specific task and often
return a value. A javascript funnction may take take zero or more paramaters.Parameters
are a standard technique via which control data can be passed to a function.Control
data passed to a function,offers a means of controlling what a function returns.

Built in Function

Javascript provides several built in functions that can be used to perform explicit
type conversions.Some of them are eval(),parseInt()and parseFloat()

Example

eval()

<html>

<head>

<Title>Sample page</Title>

</head>

<body>

<script language="javascript">

var total;

total=eval(" 0*10+5");

document.write(total)



</script>

</body>

</html>



parseInt()

<html>

<head>

<Title>sample page</Title>

</head>

<body>

<script language="javascript">

var x,y,sum;

x=prompt("Enter any number")

y=prompt("Enter any number")

sum=parseInt(x)+parseInt(y)

document.write("Total sum ="+sum)

</script>

</body>

</html>




Function


Functions are declared
and created using the function keyword.A function can comprise of the following:



  • A name for the
    function

  • A list of parameters(arguments)that
    will accept values passed to the function when called

  • A block of Javascript
    code that defines what the funcion does


syntax

function function_name(parameter1,parameter2.....)

{

      Block of Javascript code

}

A Function_name is case sensitive,can include underscores(_)and has to start
with a letter.the list of parameters passed to the function appears in parenthese
and commas separate members of the list.



place of declaration

Functions can be declared anywhere within an HTML file.Preferably,functions
are created within in <HEAD>......</HEAD> tags of the HTML file
.This ensures that all functions will be parsed,it will lead to an error condition,as
the function has not been evaluated and the Browser does not know that it exists.



Passing parameters

Values can be passed to function parameters when a 'Parameterized'
function is called.Values are passed to the function ny listing them in the
parenthese following the function name.Multiple values can be passed,separated
by commas provided that the function has been coded to accept multiple parameters.

Both javascript built in functions and user-defined functions can accept parameters,process
them and retrun values.During declaration,a function need to be infromed about
the number of values that will be passed. 

Example


function printname(user)

{

    document.write("<HR>your name is<b>M<i>");

    document.write(user);

    document.write("<B><I><HR>");

}

Where printname is a function,which has a parameter called user.The parameter
user can be passed a value at the time of invoking the function.Within the function,reference
to user will then refer to the value passed to function.

Function call:

   Printname("bob");

Note:

1)Both variables and literals can be passed as arguments when calling a function

2)If a variable is passed to the function changing the value of the parameter
   within the function doesnot change the value of the variable
passed to the    function

3)Parameters exits onlu for the life of the function



Example

<html>

<head>

<title>javascript</title>

<script langauge="javascript">

function sample()

{

document.write("Function starting")

}

</script>

</head>

<body>

<script lanague="javascript">

sample();

</script>

</body>

</html>


Example

<html>

<head>

<title>javascript Function</title>

<script langauge="javascript">

function sum(x,y)

{

var z;

z=x+y

document.write(z);

}

</script>

</head>

<body>

<script lanague="javascript">

sum(10,20)

</script>

</body>

</html>


Dialog
Boxes

Javascript provides the ability to pickup user or display small amounts
of text to the user by dialog boxes.these dialog appear asd separate windows
and their content depends on the information provided by the user.This content
is independent of the text in the HTML page conatining the Javascript script
and does not affect the content of the page in any way.

There are three types of dialog boxes provided by Javascript:

The Alert dialog box:

The simplest way to direct small amounts of textutal output to a browser's window
is to use an alert dialog box.The javascript alert()method takes a string as
an argument and displays an alert dialog box in the browser window when invoked
by appropriate Javascript.

The alert dialog box can be used to display a cautinary message or display some
information.For instance:

A message is displayed to the user when incorrect information is keyed in a
form

An invalid result is the output of calculation

A warning that a service is not available on a given date/time

sytax

alert("message")


Example

<html>

<head>

<Title>alert message</Title>

</head>

<body>

<script language="javascript">

alert("Hello")

</script>

</body>

</html>




The Prompt dialog box:

As seen the alert dialog box simply displays information in a browser
and does not allow any interaction of the OK button provides some very minimal
control over form events i.e.program execution halts completely untill some
user action takes place.



  • Javascript
    a predefined Message

  • Displays a
    textbox and accepts user input

  • Can pass what
    the user keyed into the textbox back the javascript

  • Displays an
    Ok & Cancel push buttons



Syntax

prompt("Message","Default value");

Example

<html>

<head>

<Title>prompt box</Title>

</head>

<body>

<script language="javascript">

var x;

x=prompt("Enter any number")

</script>

</body>

</html>




The confirm dialog box:

Javascript provides a third type of a dialog box called the confirm
dialog box.As the name suggests,this dialog box serves as a technique for confirming
user action.The confirm dialog box displays the following information:

      A pre defined message

      Ok & Cancel button

The confirm dialog box,causes program execution to halt until user action takes
place.User can be either the OK button being clicked, or the CANCEL button being
clicked,which causes the following action to take place.



  • Clicking on
    the OK button causes TRUE to be passed to the program which called the confirm
    dialog box.

  • Clicking on
    the CANCEL button caueses FALSE to be passed to the program which called the
    confirm dialog box.


Syntax

confirm("message");

Example

<html>

<head>

<Title>Confirm box</Title>

</head>

<body>

<script language="javascript">

confirm("Are you sure want to exit out of system")

</script>

</body>

</html>






Arrays




Arrays let you store several pieces of data in the same variable. Usually the
pieces have a common theme. This can save you creating a heap of variables all
with similar names. This is how they work:


var month_totals
= new Array(12);

month_totals[3] = 1999.95;

month_totals[4] = 'No sales';


var a=4;

document.write(month_totals[a]);

document.write(month_totals.length);

document.write(month_totals);


var days = new
Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");

The variables totals and days are made into arrays by the as-yet cryptic code
'new Array(…)'. This does two things. First, the number of items in the
array is decided, and stored in a hidden place called 'length'. In line 1, it's
set explicitly to 12. Second, space for some variables (also called array elements)
is created, which is equal to the size of the array. Line 2 shows one of those
items storing a value. '[3]' means the array element with element index 3. Array
elements are counted from 0 (zero), not one, so a three element array called
fred has elements fred[0], fred[1] and fred[2]. As line 2 and 3 show, array
elements, can contain different types of data: 'month_totals[3] = 1999.95' is
an an array variable of the Number type, whereas the third line, 'month_totals[4]
= 'No sales'' is a String type..


Accessing array
elements is easy. The first two document.write() lines display 'No sales' and
'12'. The last line shows a shorthand way of creating an Array and setting all
its elements at the same time.


Arrays in JavaScript
are closely tied to objects, which are discussed further on. In particular,
the array indices are not restricted to numbers because of their object-like
status. Arrays can also expand in size (in number of elements) just by storing
a value in an array element whose index is bigger than any that exists so far.
So arrays are quite flexible compared to equivalent concepts in other languages.


The third document.write()
above only needs to report that the variable printed is an object to match ECMAScript.
However, Netscape Navigator will print out all the array elements, comma-separated,
which is very handy. Navigator 2.02 doesn't know how to do 'new Array', and
neither does Internet Explorer 3.02 with JScript 1.0, but it can be simulated
with objects—see that section.


One of the things
you can store in an array element is another array. An array of arrays can be
treated like a multidimensional array, which has a number of uses, particularly
in mathematics and graphics. This example creates a two-dimensional array of
size two-by-two, and fills it with the values that make up an 'identity matrix'.


var matrix = new
Array(2);

matrix[0] = new Array(2);

matrix[1] = new Array(2);


matrix[0][0] =
1;

matrix[1][0] = 0;

matrix[0][1] = 0;

matrix[1][1] = 1;











No comments: