JavaScript Notes For BCA & MCA

Java Script?
Java script is language developed strictly for the web sites to create interactive web page that can handle calculations, controls such as displaying certain information when certain values provided, validate forms, and more without whole lot of programming effort.  In short description, java script is easy programming language specifically designed to make web page elements interactive. An interactive element is one that responds to a user's input.  It's developed by NetScape and is not connected to Java but has similarities with C and C++.  JavaScript is case sensitive.
Like the HTML java script uses open and close tags.
Use the following syntax to start and end any java script codes.
<script language="javascript">
  put your java script statement here
</script>

<script> - Indicates the document is script language.
<language> - Defines the script language, (eg: javascript, vbscript, etc). In this case, language is defined as javascript.
</script> - Closes the script tag.
// - This is a comment line for java script, which means the computer will not interpret this line as a code.
The following is simple java script program displaying a dialog box with the text This is java script dominated page and writes same text on the browser.
<html>
<head>
</head>
<body>
<script language="javascript">
   alert("This is a java script dominated page");
   document.write("This is a java script dominated page");
</script>
<body>
<html>
How it works
We started this code with the start and close tags:
Start <script language="javascript">
Close</script>
Then we display a dialog box with this statement:
alert("This is a java script dominated page")
Alert is a method that displays the string within the brackets.
Then we write same message on the browser using this statement:
document.write("This is the java script dominated page")
Document is an object means this page. Write is a method writes the string in the brackets to the browser.
Java script code can be placed in the head or body section of the html document. The head section is best suited for all your functions and the body section is best for immediate execution code like the one above.
Variables are used to store information. A variable's value can change during the script. You could have someone's last name and first name stored in the word name. JavaScript variables are case sensitive so watch upper case and lower case letters when referring to a variable. They also must start with letter or underscore.
Declare a variable in JavaScript variable like this:
var name;. This means, create variable name.
Var is term used to declare a java and JavaScript variables.
Assign a value to the variable like this:
name="G. Danyeer";. This simply assigns the value G. Danyeer to the variable name. You can declare and assign a value in single statement as follows:
var name = "G. Danyeer";
Arrays
An array is an indexed list of things called elements or group of related variables.   Element value can be whatever you want them to be such as numbers or strings.  Array is helpful when ever you want to keep track of a group of related items. Say that we want declare variables for list of cars like this;
var car1="Camry";
car2="Corolla";
car3="Accord";
car4="Civic";
car5="Maxima";

The list can go on and on. Here is an array way to do the same.
var cars=new Array()
car[0]="Camry";
car[1]="Corolla";
car[2]="Accord";
car[3]="Civic";
car[4] ="Maxima";

Note that the first element of array is 0. The variable car now contains list of cars indexed by numbers 0 to 4. What about if we want access the list? We can access the list all at once using loops or individually. Here is how you would write the list on the browser all at once.
var x=0;
for(x=0;x<4;x++);
{
cars[x];
document.write(cars[x]);
}

We declared variable x with initial value of zerro. It's important to initialize variables in some languages such as c++ but not important for JavaScrip. Then we have loop statement for (x=0;x<4;x++).  This loop increments x 0 to 4 and the variable x is place for each index number by assigning x into cars[x]. The document.write statement, writes the value each time that new element is read.
The following is a sample of the array explained above.
Arrays
An array is an indexed list of things called elements or group of related variables.   Element value can be whatever you want them to be such as numbers or strings.  Array is helpful when ever you want to keep track of a group of related items. Say that we want declare variables for list of cars like this;
var car1="Camry";
car2="Corolla";
car3="Accord";
car4="Civic";
car5="Maxima";

The list can go on and on. Here is an array way to do the same.
var cars=new Array()
car[0]="Camry";
car[1]="Corolla";
car[2]="Accord";
car[3]="Civic";
car[4] ="Maxima";

Note that the first element of array is 0. The variable car now contains list of cars indexed by numbers 0 to 4. What about if we want access the list? We can access the list all at once using loops or individually. Here is how you would write the list on the browser all at once.
var x=0;
for(x=0;x<4;x++);
{
cars[x];
document.write(cars[x]);
}

We declared variable x with initial value of zerro. It's important to initialize variables in some languages such as c++ but not important for JavaScrip. Then we have loop statement for (x=0;x<4;x++).  This loop increments x 0 to 4 and the variable x is place for each index number by assigning x into cars[x]. The document.write statement, writes the value each time that new element is read.
The following is a sample of the array explained above.



<html>
<body>
<script language="javascript">
{
    var cars = new Array()
    cars[0]="Camry";
    cars[1]="Corolla";
    cars[2]="Accord";
    cars[3]="Civic";
    cars[4]="Maxima";
    for(x=0;x<=4; x++)
   {
            cars[x];
        document.write(cars[x]+"<br>");
   }
}
</script>
</body>
</html>


The result will look like as follows:
Camry
Corolla
Accord
Civic
Maxima


We can display the result on message box, window or where ever we want.  Say that we want display the result on message box when we click on a button.  Here is what we would change.  Change cars[x] to alert(cars[x]} then remove the java script code from the body and replace with this statement.  Put the removed code in the head section within a function called listOfCars(). <input type="button" value="Display the car inventory" name "me" onclick="listOfCars();">
The result would look like this:
Like any other languages, java script can be categorized by functions. Function is a collection of java script code that performs an specific task and can be used anywhere in the document by calling it's name. A function can also return a value. The advantage of it, is to avoid repeating codes that does same tasks all over your document. Functions are usually defined in the head of the document and called in the body.
Here is a syntax for none-parameterized function:
function functionName()
(
  java script statement
)
Here is a syntax for parameterized function:
function functionName(argument1, argument2, etc)
(
  java script statement
)
A function can return a value. Function that returns a value must have a return statement in it. The following function returns the product of two numbers:
function product()
(
  x=2;
  y=3;
  z=x*y;
  return z;
)
Functions are not executed before they called. When you calling a function, three things are important.
  • The name of the function

  • The number and type of parameters the function expects

  • What function is supposed to return; for example, a number, a string, or whatever

Functions are usually called from the body section of html document within a java script code. Here is how you would call a none-parameterized function:
functionName()
And here is how you would call parameterized function:
functionName(argument, argument,etc).
The following is complete example of none-parameterized function
A variable that has a double quoted value is called string variable because the values are kept as they appear. It's integer variables such as X & Y above that can be calculated. Document.write has an object 'document'and a method 'write'. Document defines characteristics of the overall body of a web page and write method writes the the expression to the specific document object. The function is called from the body.
<html>
<head>
<script language="javascript">
function calculate()
{
    var X = 5;
    var Y = 4;
    var Z= X*Y;
    var xval="X has the value: ";
    var yval=" Y has the value: ";
    document.write(""+xval+""+""+X+""+","+""+yval+""+""+Y+""+","+" X*Y is equal "+""+Z+"");
}
</script>
</head>
<body>
<script language="javascript">
    calculate();
</script>
</body>
</html>

The result of the above sample is as follows:
X has the value: 5, Y has the value: 4, X*Y is equal 20
The following is complete example of parameterized function:
When arguments are passed to a function, their values must be provided when the function is called. This function simply lists the provided values on the page. We passed two arguments; firstName and lastName to the function. Then we write the arguments using document.write statement. The function expects value when it's called. Call without values will display undefined.

<html>
<head>
<script language="javascript">
function names(firstName,lastName)
{
    document.write (firstName);
    document.write(lastName);
    document.write("<br>");
}
</script>
</head>
<body>
<script language="javascript">
    names("Cilmi"," B.");
    names("Warsame"," Dool");
    names("H."," Faaruuq");
</script>
</body>
</html>

The following is result from this script:
Cilmi, B.
Warsame, Dool
H. Faaruuq

The following is complete example of a parameterized function that returns value
We passed numOrder and itemPrice to this function. We created a variable called total which is equal to product of the two other numbers. Then we returned the total.
We then created another variable called price when the function is called and set it equal to the function name and argument. This variable simply stores returned value from the function. Then we write the variable price using document.write statement.
<html>
<head>
<script language="javascript">
function calculateTotal(numOrdered, itemPrice)
{
    var total=numOrdered*itemPrice;
    return total;
}
</script>
</head>
<body>
<script language="javascript">
    var price=calculateTotal(4,5.99);
    document.write("Total: "+price);
</script>
</body>
</html>

The result of this script is as follows:
Total: 23.96
JavaScript If statment
Using if statement, javascript has the ability to make distinctions between different possibilities. For example, you might have a script that checks if Boolean value is true or false, if variable contains number or string value, if an object is empty or populated, or even check type and version of the visitors browser.

Here is a syntax for if statement:
if (condition)
{
 Action statement
}
This is a single if statment wich responds on one condition and executes statements inside the curly braces {} when the condition is true.
if (condition)
{
 Action statement
}
else
{
 Alternative action statement
}
-This executes the statements inside the curly braces when conditon is true and alternative statements when when condition is not true. Notice parenthesis are used around the condition statement. Java scipt if statement uses parenthesis and is case sensitive.
Here is an example of if statement.
In this example, we created a variable n and initialized with zerro. Then we used if statement to see if n is equal to 0. We display n is zerro if the conditon is true and n is something else if the condition is not true.
In this case, the condition is true because n is equal to 0 so the first message is alerted. Notice that == is used for comparison. You cannot use = to compare two values.
<html>
<body>
<script type="text/javascript">
var n=0
if (n==0)
{
  alert("n is zerro")
}
else
{
  alert("n is some thing else")
}
</script>
</body>
</html>

The following is if statement example that checks many conditions in sequence

This example is extention of previous example. This time we are using prompt box to get a number from the user. Using if statement, we tested if the provided number is one, two, three, or four alerting the user when a match is found. If the provided number is not within this range, then we check if the number is greater than 4 using > operator. If the condition still false, then we checked if the number is less than 1 using < operator. If none of the conditions are true then else condition is true and it's alert message; You did not enter a number.

<html>
<body>
<script type="text/javascript">
var n=prompt("Enter number between 1 to 4","1")
if (n==1)
  {alert("n is one")}
else if(n==2)
  {alert("n is two")}
else if(n==3)
   {alert("n is three")}
else if(n==4)
  {alert("n is four")
}
else if(n>4)
  {alert("You entered number greater than 4, please enter 1-4")}
else if(n<1)
  {alert("You entered number less than 4, please enter 1-4")}
else
  {alert("You did not enter a number!")}
</script>
</body>
</html>

Boolean Operators
Three boolean operators are used in if statements. The operator, && , allows you to combine two conditions so that both must be true to satisfy the if condition. The operator , ||, which combines two conditions such that the if statement is satisfied if either condition is true. The third boolean operator Operator, !, which makes a condition that returns true, false and vice versa.
Suppose you wanted the previous example to display a message for numbers 1 to 9, 10 to 19, 20 to 29, 30 to 39, and so on. Checking each number would take you hundreds of pages of codes, thanks to the booleans operators. Using boolean operators we can perform the operation in ranges.
The following example is modification of previous example using boolean operators:

Since the first portion of our alert message is always the same, we created a variable that stores this portion just to make the writing short. We use an if statement to check the provided number in ranges. For example: if (n>=1 && n<10), in order this condition to be true, the number must be 1,2,3,4,5,6,7 , 8 or 9. If the number is 10, the condition will be false because n<10 means 10 is less than 10 but not equal to. If the number is 1, then the condition will be true because n>=1, means n is greater than or equal 1.
The operator || is used to check unrelated rang of values and returns true value when one condition is satisfied. For example: if(n<1 || n>100), this condition will return true value when n is less than one, or n is greater than 100 either way. It returns false value, when n is number between 1 and 100 inclusive. The rest of the code is same as previous.

<html>
<body>
<script type="text/javascript">
var n=prompt("Enter a number","1")
var enter="You entered a # between"
if (n>=1 && n<10)
  {alert(enter+" 0 and 10")}
else if(n>=10 && n<20)
  {alert(enter+" 9 and 20")}
else if(n>=20 && n<30)
  {alert(enter+" 19 and 30")}
else if(n>=30 && n<40)
  {alert(enter+" 29 and 40")}
else if(n>=40 && n<=100)
  {alert(enter+" 39 and 100")}
else if(n<1 || n>100)
  {alert("You entered a # less than 1 or greater than 100")}
else
  {alert("You did not enter a number!")}
</script>
</body>
</html>

Javascript Case Statements

Javascript case statements can be used to control the different outcomes of a condition. Javascript case statements are recommended when a single condition has a range of outcomes. For example, getDate is a method that can return any day of the week. Javascript case statements can be used to determine and display a message related to the current day.

The syntax for javascript case statements are as follows:
switch(condition)
{
case value:
action statement
}
The case value is executed when the condition is "true". If no match is found, then the default condition is executed (if specified).

This example uses a javascript case statement to display the current day:

Here we declared a variable 'date', and set it to the date object.

getDay accesses the days of the week in numbers 1-7.
switch sets the condition to test.
case tests the value, and executes when it's "true".
break is used to "break" the condition.

Since the condition is always "true" (hence everyday is a day), there is no need to specify a default statement to execute when there is no match. The example executes when the page is loaded since it's located in the 'body' section of the document.

<html>
<body>
<script type="text/javascript">
<!--
var date = newDate()
today = date.getDay()
switch (today)
{
case 1:
  alert("It's Monday")
  break
case 2:
  alert("It's Tuesday")
  break
case 3:
  alert("It's Wednesday")
  break
case 4:
  alert("It's Thursday")
  break
case 5:
  alert("It's Friday")
  break
case 6:
  alert("It's Saturday")
  break
case 7:
  alert("It's Sunday")
  break
}
//-->
</script>
</body>
</html>


<body>
<script type="text/javascript">
var number = prompt("Enter a number between 1 to 3:", 0)
switch (number)
{
case (number = "1"):
  alert("You typed" + number);
break
case (number = "2"):
  alert("You typed " + number);
break
case (number = "3"):
  alert("You typed " + number);
break
default:
  alert("Sorry, wrong number");
break
}
</script>
</body>


JavaScript Loops
Loops are set of instructions that repeat elements in specific number of times.  Counter variable is used to increment or decrement with each repetition of the loop.  The two major groups of loops are, For..Next and Do..Loop.  While..Wend is another type of Do..Loop.  The For statements are best used when you want to perform a loop in specific number of times. The Do and While statements are best used to perform a loop an undetermined number of times.
For..Loop syntax example.
for(i=0;i<value; i++)
{
   javascript statement
}

This example increments a variable i from 0 to value and continues performing java script statements while i is less then value.

<html>
<body>
<script type="text/javascript">
for (i = 0; i <= 4; i++)
{
alert("Current value of i is " + i)
}
</script>
</body>
</html>

This display the value like this on alert boxes: 0,1,2,3,4. The for loop sets i equal to 0 and continues displaying values on an alert boxes as long as i is less than , or equal to, 4. The value of i will increase by 1 each time the loop runs.

While..Loop
The While..Loop structure repeats a block of statements until a specified condition is met.
Bellow is syntax for While..loop:
while(variable=value)
{
   javascript statement
}
The above syntax simply repeats some javascript statements while condition tested false.

Bellow is simple example of while loop:

<html>
<body>
<script type="text/javascript">
var x=5*5;
x=prompt("What is 5 x 5?");
while (x != 25)
{
alert("Wrong answer");
x=prompt("What is 5 x 5?",0);
}
document.write("Right, the answer is " + x)
</script>
</body>
</html>

For this example, we declared variable x and initialized 25. We set it equal to prompt box. The prompt box asks the product of 5x5 and continues asking until true answer is provided. It also informs each wrong attempts or each loop.

Bellow is the same example but performs the test at the end of the loop. This time, Do..Loop is used. Using this loop, true value is tested.


<html>
<body>
<script type="text/javascript">
var x = 5*5;
do
{
x=prompt("What is 5 x 5?",0);
}
while (x != 25)
document.write("Right, the answer is " + x)
</script>
</body>
</html>

The syntax are same for Do..While and While but keep in mind one tests false condition and the other tests true condtion. The execution of this example will be same as the previous example









Java Script Operators
Bellow are list of some of operators available in Java Script. Their meanings and fair example of each.
Operator
Description
Example
Result
+
Addition sign. Adds two numbers together.
8+2
10
-
Subtraction sign. Subtracts number from a number.
8-2
6
*
Multiplication sign. Multiplies two numbers.
4*4
16
/
Division sign. Divides a number by another number.
5/2
2.5
%
Modulus. Tracks the reminder of two divided numbers.
5%2
1
++
Increment. Increases values by one each run.
x=3
x++
x=4
--
Decrement. Decreases values by one in each run.
x=3
x--
x=2
=
Assignment sign. Assigns right variable or value to the left variable.
x=y
x has same value as y
+=
Left variable is added to right value on each run.
x+=y
x=x+y
-=
Left variable is subtracted from right value on each run.
x-=y
x=x-y
*=
Left variable is multiplied by the right value on each run.
x*=y
x=x*y
/=
Left variable is divided by the right value on each run.
x/=y
x=x/y
%=
Reminder is tracked on each run.
x%=y
x=x%y
==
Compares two values and returns boolean.td>
4==3
false

!=
Tests if the values are NOT equal
4!=3
true

> 
Test if the left value is greater right value
5>4
true

< 
Test if the left value is less than right value
5<8
true

>=
Test if left value greater than or equal to right value
3>=5
false

<=
Test if left value less than or equal to right value
3<=5
true

&&
Performs a logical conjunction on two expressions. AND for other languages.
See if statement

||
Performs a logical conjunction on two expressions. OR for other languages.
See if statement

&&
Perform a logical negation on an expression. AND for other languages.
See if statement




Javascript Form Validation

Javascript form validation means checking that the proper information is entered in the form fields before it is submitted. Forms aren't of much use in terms of processing and posting if you are only limited to HTML, and you don't have access to other scripts such as CGI. This tutaorial is limited to form validations (if you want to learn how to create them, check-out the HTML form page).
This example alerts the value entered in the text fields:

<html>
<head>
</head>
<body>
<FORM name="fm">
Type your first name:
<INPUT type="text" name="first"><br>
Type your last name:
<INPUT type="text" name="last">
<INPUT type="button" name="dis" value="Display" onClick='alert("You say your name is: "+document.fm.first.value+" "+document.fm.last.value)'>
</FORM>
</body>
</html>

The only Javascript in this example is onClick. The onClick event handler responds when an object is clicked, and executes the Javascript code or function. In this case, it executes alert box. The alert box displays the values in the text boxes.

This example shows how to select and display:

<html>
<body>
<html>
<body>
<FORM name="fm2">
Select one: <select name="selec" onchange='alert("You selected "+document.fm2.selec.value)'><br>
<option>Select One
<option value="Java">Java
<option value="C++">C++
<option value="Cobol">Cobol
</select>
</FORM>
</body>
</html>
</body>
</html>

We used the onChange event handler to display the alert box with the selected value. onChange executes the specified Javascript code or function in an event change. (when this happens, it executes an alert box that displays the selected value of the select box)

Javascript Object Validations

Javascript object validations have a practical business use (making sure that a required user's information is correct.
This example checks and alerts if the fields of the form are empty:

<HTML>
<HEAD>
<script type="text/javascript">
function validate(formCheck) //Function with a parameter representing a form name.
{
if (formCheck.name.value = "")
{
alert("Please provide your name:");
formCheck.name.focus();
return false;
}
var mail = formCheck.email.value
if (mail.indexOf("@.") == -1)
{
alert("Please type a valid email:");
formCheck.email.focus();
return false;
}
return true;
}
</script>
</HEAD>
<BODY>
<FORM name="inform" action="" method="post">
Your Name: <INPUT type=text NAME="name" value="" SIZE=20><br>
Your Email: <INPUT type=text NAME="email" value="" SIZE=30><br>
<INPUT type="button" name="submit" value="Send" onClick="return validate(inform)";>
<INPUT type="reset" name="reset" value="Clear">
</FORM>
</BODY>
</HTML>

How it Works

We created a function called validate which takes a parameter. This parameter represents the form name.
Using an if statement, we compare the text field name with the empty string. If this field is equal to the empty string, then an alert box is displayed, and the focus is set to this field. We then return a false outcome to avoid the action being continued.
The email field is slightly different. For this field, we check if the '@' and '.' are provided. If not, we alert the user, set the focus, and return false. If the two controls pass a "true" value, then the function returns "true". In this case, the onClick event handler returns "true", and nothing happens.
Note: if the form action proceeds to another page, use onSubmit instead of onClick. onSubmit executes the function, and continues processing the file defined in the form action.

Javascript Alert Box

A javascript alert box is a dialog box that pops-up with a message and an 'OK' button. The alert method displays an alert box with a string passed to it. For example: alert() will display an empty dialog box with just the 'OK' button. alert("Hello world") will display a dialog box with the message, 'Hello world' and an 'OK' button. (it remains paused until it is clicked). You can display any type of value on an alert box.
For example:
var number = 12345
alert("The number is: "+number)
This simply displays, 'The number is: 12345' on an alert box. The '+' sign ties the two values that are to be displayed in one statement.

Here is a javascript alert box that pops-up when the page is loade

<html>
<body>
<script type="text/javascript">
alert("Hello world")
</script>
</body>
</html>

Hello world is displayed in a dialog box when the page is loaded

Here is a javascript alert box that pops-up when a link is clicked:

<html>
<body>
<A HREF='javascript:onClick=alert("Not an active link")'>Click here</A>
</body>
</html>

onClick is an event that understands the mouse click. We set the onClick event to the alert box so that when the active link is clicked, the onClick event executes the alert box.


Here is a javascript alert box that pops-up when a button is clicked:

<html>
<body>
<form>
<input type="button" name="click" value="Click To Alert" onclick='alert("You clicked a button to display an alert box")'>
</form>
</body>
</html>

Again, we used the onClick event to display the alert box when the button is clicked

Javascript Prompt Box

The prompt() is a method of the window object, just like alert() we just saw. The format for prompt() is similar to alert(), except for one addition. Prompt uses a text field to enter a value. It also has 'OK' and 'CANCEL' buttons, while the alert has only one button.
Here is an example of a prompt box:
prompt("Type your name:"). This prompt method will display the message, 'Type your name' on a prompt box and text field with the default text of undefined. We can display default text in the text field by simply doing the following:
prompt("Type your name:", "Type here")
The information submitted to the prompt() can be stored in a variable as follows:
var name = prompt("Type your name:", "Type here")
Once we have a value from the prompt box stored in a variable, we can display it on a message box.

Here is a javascript prompt box that displays the provided value on a message box:


<html>
<body>
<script type="text/javascript">
var name = prompt("What is your name?", "Type your name here");
alert("Your name is: "+name)
</script>
</body>
</html>

This example displays a prompt box when the page is loaded with the message, 'What is your name?' and the default text field value of, 'Type your name here'. Once a name is provided, it is stored in the variable name, and is displayed on an alert box

Javascript Confirm Box

The Javascript confirm box differs from a regular alert box in that it provides two choices for the user: 'OK' and 'CANCEL' to confirm the request. You can use a variable and an if statement to determine if the 'OK' or 'CANCEL' button is clicked.
Here is an example of a confirm box:
Confirm: ("Do you want to continue?") This displays a dialog box with the message, 'Do you want to continue?' (with 'OK' and 'CANCEL').


Here is a javascript confirm box that tells you which button you clicked:


<html>
<body>
<script type="text/javascript">
var answer = Confirm: ("Do you want continue?")
if (answer)
alert("You said: Ok")
else
alert("You said: Cancel")
</script>
</body>
</html>

We stored the confirm objects in the variable, answer, and then used an if statement to determine which button was clicked. The default and expected button is, 'Ok' so we stated if the answer is equal to 'Ok', then go to a specify location. Else will be "true", and the second message will be displayed, if the current value of answer is not the default value.

Here is an example that directs the user to another page when the, 'OK' button is clicked:

<html>
<body>
<script type="text/javascript">
var answer = Confirm: ("Do you want a different page?")
if (answer)
window.location = "http://www.videogamedeals.com"
else
alert("Nothing happened")
</script>
</body>
</html>

We stored the confirm objects in the variable answer, and then used an if statement to determine which button was clicked. The default and expected button is, 'Ok' so we stated that if the answer is equal to 'Ok', then go to: www.videogamedeals.com. Else will be "true", and the second message, 'Nothing happened' will be displayed if the current value of answer is not the default value.


JavaScript objects
Objects are things that are visible. People often describe objects things we can touch, like chair and car but the real meaning of objects in programming are things you see on your screen, like windows, frames, forms, fields, etc. Object could have a Property or Method. Property is an another object within an object. For example, Car is an object, Tire is property of the car when it's party of the car but Tire is another object when it's sitting by it self. Drive is not an object but way of doing. Method is way of doing things like drive.
Now, we know what object.property.method are, but how does it apply to javascript?.
Look this statement carefully and identify object, property, method:
window.document.write()
Window is an object, document is property, and write is method. This is similar to car.tires.drive. If we have just document.write() is object and method similar to tire.spin.
We could have object.property without a method. For example, document.formName.textBoxName.value. Document is an object representing whole html page, form is another object, which is the property of document and textBox is another object, which is the property of form. Since we have some idea of what object is, we will discuss different types of objects that are often used in javascript in detail.

String object
String is one of stand alone objects that takes string value. For example, var cars = new car("Fox Wagon").   Creates string object containing the value "Fox Wagon".   Be carefull because car="Fox Wagon" is not an string object.  It's string literal. Java script temporarily converts string literals to string objects so you can use string object methods for string literals too.  If you try to evaluate object string using eval function, it will not work because objects do not change in behaviour.   Length and Prototype are two string object property available.  Length counts the number of characters in the string, for example
car.length
will return 9 characters long.  Prototype creates more properties for the object.

Following are list of some string object methods available.
Method
Method Decriptions
Method Example
Big(),Small(),Bold(), Italic(), Strike(), sub(), sup()
Returns big, small, bold, italic, strike, subscript, or superscript text format
var prog="This is is big() example"
document.write(prog.big())
Result:
--> This is is big() example
IndexOf(), lastIndexOf()
Returns the position of specified string or -1 if the string is not found. lastIndexOf() start from right to left
var prog="JavaScript is not hard"
var pos=prog.indexOf("h")
document.write("found h at: "+pos)
Result:
found h at: 18
fixed()
Displays a Teletype string format.
document.write("This is teletype format".fixed())
fontcolor(), fontsize()
Returns a string in a specified font color or size.
var prog="Changes the font color"
document.write(prog.fontcolor('blue'))
Result:
--> Changes the font color
match()
Returns specified value from string or null if the value not found.
var prog = "Do you see the example"
document.write(prog.match("see"))
returns:
see
toLowerCase(), toUpperCase()
Converts strings to upper or lower case
document.write("chang this to upper case letters".toUpperCase()) returns: CHANG THIS TO UPPER CASE LETTERS
charAt(), charCodeAt()
Returns character at specified position and the other returns unicode instead.
var prog="What do you see"
document.write(prog.charAt("5"))
returns: d
blink()
Returns blinking link.
var prog="What do you see"
document.write(prog.blink())
returns: What do you see"
link()
Returns a string as a hyperlink
document.write("This web site".link("http://www.clik.to/program"))
returns:
--> This web site
replace()
Replaces specified character with specified character.
document.write("Replace him".replace("him","me"))
returns:
Replace me
research()
Returns number representing specified character or -1 if no match found.
document.write("Character search".search("t"))
returns:
6
substring()
Returns a string starting specified position and contain specified number of chars. Count starts at 0.
var prog="Web Programmer/Developer" document.write(prog.substring(3,14))
returns:
Programmer



Date object
The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. It's easy to use the Date object and its methods to work with dates and times in your document.
To create a date object, the following syntax is used: dateObjectName = new Date() where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object. The following example explains the use of date object.

<html>
<body>
<script type="text/javascript">
var CDate = new Date()
document.write(CDate.getDate())
document.write("/")
document.write(CDate.getMonth()+1)
document.write("/")
document.write(CDate.getFullYear())
document.write("@")
document.write(CDate.getHours()+":")
document.write(CDate.getMinutes()+":"+CDate.getSeconds())
</script>
</body>
</html>

The variable CDate is set to a date object. Date() returns date object and has methods set(), get() and to (). Set() initializes the date object with the specified value and get() receives date value from the date object. To() converts date object to string

Here is the result of this sample:
-->11/10/2011@15:56:17

<html>
<body>
<script type="text/javascript">
var CDat = new Date()
CDat.setMonth("9")
CDat.setDate("11")
document.write(CDat.getDate()+"/"+CDat.getMonth())
</script>
</body>
</html>

This example sets the date to 11 and the month to 9. These value are kept in memory unless you change it.
Here is the result >
--> 11/9

The following example displays full date, with day name and month name.

<html>
<body>
<script type="text/javascript">
var dat=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[dat.getDay()] + " ")
document.write(monthname[dat.getMonth()] + " ")
document.write(dat.getDate() + ", ")
document.write(dat.getFullYear())
</script>
</body>
</html>

In this example, we created two array of objects. One populated with months of the year and the other with days of the week. We can display the date in numbers using date object as we saw before. We can also display the name of the month or the day using the date methods as an index of the array. See array object.
Here is the result of this example:
--> Tuesday Oct 11, 2011



The following are list of methods that can be used and description of it's value.
Date Object Methods

Method
Description


getYear()
Returns the year in ## format.
getFullYear()
Returns the year #### format.
getMonth()
Returns the month of the year in ##.
getDate()
Returns the date in ##.
getDay()
Returns the day in # (0-6).
getHours()
Returns the hour of 24-hr day
getMinutes()
Returns the minutes of hour
getSeconds()
Returns the seconds within the minute
getTime()
Returns milliseconds since 1/1/1970.
getTimezoneOffset()  
Returns minutes offset from GMT
toGMTString()
Returns string in universal format
getLocalString()
Returns string in system's format
parse("string")
Returns string to milliseconds
UTC(value)
Returns date from GMT


Set Method
Description


setYear()
Sets the year in ##.
setFullYear()
Sets the year in ####.
setMonth()
Sets the month of Year in ##
setDate()
Sets the date within the month
setDay()
Sets a day of week in # (0-6)
setHours()
Sets an hour of 24-hr day
setMinutes()
Sets the minutes of hour
setSeconds()
Sets the seconds within minute
setTime()
Sets milliseconds since 1970.


Array Object
We saw array in the date example above. An array is collection of related data that is contained within a variable. For example:
daysOfWeek = new Array ("Sunday", "Monday","Tuesday", "Wednesday", "Thursday","Friday", "Saturday") is an array that stores days of the week.
Getting the data out of the array is just as easy. You refer to a particular element of data like this:
daysOfWeek[n]
where n is the numeric position of the data element starting at 0. For instance daysOfWeek[0] would yield Sunday. See variables & arrays for more array examples.

Javascript Pop-up Window Objects

The javascript pop-up window object refers to the web browser, and all of the items you can see within it. This tutorial will explain how objects are used to create a pop-up window, and the various properties and methods available. Properties are sub-objects which are a part of another object. Methods are the different ways you can do things. Javascript pop-up window object properties refer to: window name, window size, window address, etc. Javascript pop-up window object methods refer to: open, close, scroll, move, resize, alert, etc.

You need to at least specify for a blank window to open. Here is how you open a blank window: window.open()
(This will open a blank window, and use all of the default settings).

The best way to display a window with a particular: size, color, menu, toolbar, object, etc. is to create a function, and call it when either: a link is clicked, when an object is clicked, or for an onload event.

Below is a pop-up window that displays another website in a smaller window:

<html>
<head>
<script type="text/javascript">
function WindowE()
{
window.open("http://www.videogamedeals.com", "WinE", "width=650,height=500,toolbar=no,resizable=yes")
}
</script>
</head>
<body>
<a href="javascript:WindowE()">Click Here</a>
</body>
</html>

We created a pop-up window with a width of 650 pixels wide, and a height of 500 pixels high. It displays the website: VideoGameDeals.com. The name of the window is 'WinE', and it is resizable because we set that option to 'yes', however it won't display the toolbar because we set that option to 'no'. This window has been created using a function. When this webpage loads, all you will see is the 'Click Here' link (which calls the function that creates the window)

When creating a javascript pop-up window, remember the following syntax: window.open("url", "windowName", "windowAttributes").

URL > specifies the domain name for a website.
WindowName > refers to the name of the javascript window object.
WindowAttributes > are the various options such as: toolbar, statusbar, scrollbars, etc.

Here are a list of attributes for your pop-up window:
width
height
toolbar
location
directories
status
scrollbars
resizable
menubar



Below is a pop-up window that uses all of the various attributes listed above:

<html>
<head>
<script type="text/javascript">
function WindowC()
{
window.open("http://www.videogamedeals.com", "WinC", "width=550,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no, scrollbars=no,resizable=yes,copyhistory=no")
}
</script>
</head>
<body>
<form>
<input type="button" value="Open Window" onclick="WindowC()">
</form>
</body>
</html>
This pop-up window displays the website: VideoGameDeals.com again, and sets all of the attributes to no (which means that this window will not display any of those named attributes). Also, we are using a button to call the function that creates the window. Below is the result


Below is a complete list of Properties and Methods available for javascript pop-up window objects:
Property
Description
Syntax
Closed
Returns boolean value to determine if a window has been closed
window.closed
defaultStatus
Defines the default message displayed in a window's statusbar
window.defaultStatus(="message")
document
Defines the document to be displayed in a window
window.document
frames
Returns an array containing references to all the named child frames in the current window
window.frames(="frameId")
history
Returns the history list of visited URLs
window.history
innerHeight
Returns the height of a window's display area
window.innerHeight = value
innerWidth
Returns the width of a window's display area
window.innerWidth = value
length
Returns the number of frames in a window
window.length
location
The URL of a website loaded into a window
window.location
locationbar
A window's location bar (the property is visible)
window.locationbar.visible=false
menubar
A window's menu bar (the property is visible)
window.menubar.visible=false
name
Used to set, or return a window's name
window.name
opener
The name of a window opened in a current window
window.opener
outerHeight
Used to return the height of the outer area of a window
window.outerHeight
outerWidth
Used to return the width of the outer area of a window
window.outerWidth
pageXOffset
Used to return the X-coordinate of a current window
window.pageXOffset
pageYOffset
Used to return the Y-coordinate of a current window
window.pageYOffset
parent
The name of a window containing a particular window
window.parent
personalbar
Returns boolean value indicating the visibility of the directories bar
window.personalbar.visible=false
scrollbars
Returns boolean value indicating the visibility of the scrollbars bar
window.scrollbars.visible=false
self
Used to refer to current window
self.method
status
The message displayed in a window's status bar
window.method="message"
statusbar
Returns boolean value indicating visibility of the status bar
window.statusbar.visible=false
toolbar
Returns boolean value indicating visibility of the tool bar
window.toolbar.visible=false
top
Used to return the name of top-most window
window.top
window
Used to return the current window
window.[property]or[method]
Method
Description
Syntax
alert(message)
Displays a text string on a dialog box
alert("Type message here")
back()
Loads previous page in the window
window.back()
blur()
Removes the focus from a window
window.blur()
captureEvents()
Sets a window to capture all events of a specified type
window.captureEvent(eventType)
clearTimeout()
Clears a timeout (set with the setTimeout method)
window.clearTimeout(timeoutID)
close()
Used to close a window
window.close()
confirm(message)
Displays a confirmation dialog box with a text message
confirm("type message here")
disableExternalCapture/
enableExternalCapture
Disables/Enables external event capturing
window.disableExternalCapture( )/
window.enableExternalCapture( )
focus()
Used to give focus to a window
window.focus()
forward()
Loads the next page in a window
window.forward()
handleEvent(event)
Invokes the event handler for a specified event
window.handleEvent(eventID)
moveBy(horizontal, vertical)
Moves a window by the amount specified in the horizontal and vertical directions
window.moveBy(HorValue, VerValue)
moveTo(x, y)
This method moves the window's left edge and top edge to the specified x and y coordinates
moveTo(Xposition,Yposition)
open()
Used to open a window
window.open(url, name, attributes)
print()
Displays a print dialog box
window.print()
prompt(message, defaultValue)
Displays a prompt dialog box
window.prompt("Type message here", value)
releaseEvents(event)
Release any captured events of a specified type
window.releaseEvents(eventType)
resizeBy(horizontal, vertical)
Resizes a window by the specified horizontal and vertical amounts
window.resizeBy(HorValue, VerValue)
resizeTo(width, height)
Resizes a window to the specified width and height amounts
window.resizeTo(widthValue,heightValue)
scroll(x, y)
Scrolls the window to the specified coordinates
window.scroll(xValue, yValue)
scrollBy(x, y)
Scrolls the window's content area by the specified coordinates
window.scrollBy(HorValue, VerValue)
scrollTo(x, y)
Scrolls the window's content area to the specified coordinates
window.scrollTo(xValue, yValue)
setInterval(expression, time)
Evaluates an expression in milliseconds
window.setIntervals(expression, milliseconds)
stop()
Used to stop a window from loading
window.stop()






 

No comments:

Post a Comment