• JavaScript is a scripting language designed to add interactivity to HTML pages introduced by Netscape, which is also known as ECMA Script.
  • Its a lightweight programming language
  • It is a compiler based language.
  • JavaScript is usually embedded directly into HTML pages using <Script>… </script> tags.
  • JavaScript is an interpreted language (no need of compilation).
  • Browsers should be java script enabled.

Advantages of Javascript

  • JS gives HTML designers a programming tool.
  • It can put dynamic text into an HTML page Ex. document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
  • It can react to events
  • It can read and write HTML elements.
  • It can be used to validate data
  • It 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.

Ex.Simple JS
<html><body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>


Ex. Dynamically adding HTML contents
Generated on the fly while processing the java script. Note that < & > symbols should be used with &#62 and &#60(or &lt; &gt;).

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

Add an HTML comment tag( “<!--  and --> “)before and after JavaScript statements  to avoid java script text being displayed in non-java compliant browsers..


Ex. Adding Comments
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>
// is the single line comment for javascript stopping the process of -- >.


Write() & writeln()

  • document.write() outputs the string inside the “()” to the browser document.
  • document.writeln() outputs the string with a carriage return at the end of line. 
  • document.writeln() will work only when embedded inside <PRE> tag.

WAP: That prints “Welcome to Javascript”. Apply the formatting as Bold, Italic and Underline. Change the color of the text also.


Significance of JS in different sections of HTML


Head section

  • JS in head section will be executed when CALLED.
  • By placing a script in the head section, it is ensured that the script is loaded well before any call is made from body section.

Body section

  • JS in the body section will be executed WHILE the page loads.
  • If you place a script in the body section, it generates the content of a page dynamically.

Head and Body sections

  • You can use <Script> tags and write JS any number of times in a html document both in head and body section.

External file

  • To run same script on several pages, you can write JS  in an external file.
  • Save the file with a .js file extension.
  • Note: The external script should not contain the <script> tag!
  • Use  "src" attribute of the <script> tag to point to js file. Ex. <script language=”javascript” src=”myscript.js”>

Basics of JavaScript

  • JS is case sensitive. Alert, alert, ALERT are different.
  • A JS statement is a command for browser. Ex. document.write (”hello world”) is a command asking the browser to write “hello world” in it.
  • Use semicolon (;) at the end of the statement, it suggests the end of command.
  • Using ; you can write more commands in a single line.
  • “{“ and “}” are used to create one single block of commands.

Escape Sequence
These are special characters used in JS with a “\” and then the letter.

Character

Description

\n

New line

\t

Tab

\r

Carriage Return

\f

Form Feed

\b

Backspace

\0

Null character

\v

Vertical tab

\’

Single quote

\”

Double quote

\\

Backslash


Ex: Using escape sequence on the fly
<html><body>
<pre>
<script type="text/javascript">
document.write("<html><head><title>Using escape sequence</title></head>");
document.write("<h1 align=center>Hello World!</h1>");
document.write("<hr><h2 align=center>one \t two \t three \t four \t five\n");
document.write("six \t seven \t eight \t nine \t ten\n\n");
document.write("<hr><h1>This \"Hello World!\" is in double quotes\”");
document.write("<hr><h2>This is a url : \“ \\\\ http:\\ z:\\tests\\css\\blureffects.html\”");
document.write(" ");
</script></pre></body></html>


Datatypes
Basic data types are :-
(a) Numbers are values of integer like 234, 456, 58777 and floating types like 23.35, 44.657 etc.
(b) Strings are values of text embedded inside quotes like “my name”, ‘who’ etc.
(c) Boolean values carry either “true” or “false”.
(d) Null means empty/no value.


Variables

  • Variable stores a reference to the location of the memory. 
  • It can hold any value of a given type.
  • Variable can be used with or without declaration.
  • Declare variable using “var”. Ex. Var name = ”Raja”;
  • Variable names can use alphanumeric type of text but not precede with a number.
  • Variable names can start with “_”(underscore).
  • While using the variables JS automatically sets the type of variable itself.

          Ex.      Var no=”129” is treated as string by JS.
Var no=129 is treated as integer by JS.
Var no=129.59 is treated as float type of value by JS.


Dialogue Boxes
Dialogue boxes are small windows that help in interacting with the user.  Three dialogue boxes are commonly used.


Prompt:

  • Prompt provides two parameters “message” and a “default value”. 
  • The message will be displayed and default value appears in text box.
  • The data can be entered in Text box which is available for JS for use.
  • “Cancel” and “OK” buttons are also displayed for user.

Ex. var a=prompt(“Enter you name”, “xxxxxx“);
var b=prompt(“Enter a number”, 100-200);

Alert:

  • Will display any message given by JS to the user.
  • Displays an “ok” button, which, unless pressed, does not proceed.

Ex.      <html><body>
<script language=“javascript”>
Var age=prompt(“enter your age”, “1000”);
If (age==1000 || age==” “) {
alert (“do not hide your age!”);
Else {
Alert (“Do not reveal your age!”);
}
}
</script></body></html>


WAP:  That takes two values from the user and perform the mathematical operations (+,-,*, /, %).


Confirm:

  • Will display a message to confirm.
  • Contains two buttons “OK” and “cancel”.
  • If clicked “OK” will pass “true” and “cancel” will pass “false” as value.

Concatenation
In JS concatenation is done by using “+” operator. This is a special operator which appends any type of data or objects together.

 Ex.
<html>
<head><title>concatenation</title></head>
<body>
<script language="javascript">

var one=prompt("enter a value","xxx");
var two=prompt("enter a value", "xxx");

if(confirm("do you want to confirm"))
alert ("concatenation of "+one+" and "+two+" is :"+ one+two);
else alert("sorry! cancelled");

</script>
</body>
</html>


WAP that takes 2 values from the user and display the greater one.


Parsing Strings
For converting strings to numbers we have (a) parseInt (b) parseFloat functions.


(a) parseInt()

  • If given string does not contain number/white space/minus sign it returns “NaN”.
  • It takes second parameter as radix, ie base 2-36 ex. parseInt(“17”,8) gives base 8 no.

Ex.
parseInt("3 chances")                   //returns 3
parseInt("   5 alive")                    //returns 5
parseInt("I have 3 computers")      //returns NaN
parseInt("17", 8)                         //returns 15
parseInt(“13.34”)                         //returns 13

 

(b) parseFloat()

  • This is similar to parseInt() except for useful to extract decimal places of a float number.

Ex.  parseFloat("-3.98 points")       //returns -3.98


isNaN()

  • Returns true if the parameter is not a number else false.

Ex.  isNaN("points") //returns true


isFinite()

  • Returns true if it’s a finite number(normal no) returns false if iis a infinite no.

Ex.  isFinitte("-3.98")          //returns true

 

eval() method
Evaluates the given string to a numerical value.
Ex.  eval("8+3+1") //returns 12
var a=5
var b=23
Eval(a+b)  //returns 28


Ex. Using eval method
<html><body>
<script language=”javascript”>
var quest = prompt(“enter the expression to evaluate”, “xxxx”);
document.writeln(“<b><br>the result of this expression is </b></br>”);
document.write(eval(quest));
</script>
</body></html>
WAP that takes two numbers and operation from user and perform the operation using eval().


Reserved words
This is the list of reserved words which should not be used for declaration in JS.


abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double

else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in

instanceOf
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super

switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with


OPERATORS
Operators are used to perform tasks in programming using variables, data, etc.



Operator

Description

Example

Basic Arithmetic Operators

+

Adds

a=15, b=10,
c = a+b;

c=25

-

Subtracts

c = a-b;

c=5

*

Multiplication

c=a*b;

c=150

/

Division

c=a/b;

c=1.5

%

Modulus

c= a%b; results in 5.

Gives the remainder after division.



Unary Operator

++

Increments the operand with 1.

a=15, b=10
a++;  c=(a++)-b =5;
++a;  c=(++a)-b =6;

a++ results in operation first and increment next.
++a results in increment first and operation next.

--

decreases the operand with 1.

a=15, b=10
a--;  c=(a--)-b =5;
--a;  c=(--a)-b =6;

a—results in operation
first and increment next.
--a results in increment
first ad operation next.

-

Negation operator

a=15; a=-(a) = -15;
b=10; b=-(b) = -10;

Negation of a number


Ex.  using unary operator.
<HTML><HEAD><TITLE>USING INCREMENT OPS</TITLE></head>
<body>
<SCRIPT>
var no=prompt("enter a number", 1000);
document.write("<h1>You have entered :"+no);
document.write("<h2>"+no+" operated with ++ gives :"+(++no));
document.write("<p>"+(--no)+" operated with -- gives :"+(--no));
document.write("<p>negation of "+no+" is : "+ -(no));
document.write("<hr><h1> PUT THE ++ AND -- AFTER THE NO AND SEE THE DIFFERENCE");
</SCRIPT></body></HTML>


Assignment Operators

=

Number on the right side is assigned to left side.

a=15; b=10;
a = b; results in a=10;
a = (b*100)/10 results in a=100;

-=

New value of left side will be old value of it minus the number on right side.

a=15; b=10
a-=4; results in (15-4) a=11;
b-=2; results in (10-2) b=8;

+=

New value of left side will be old value of it plus the number on right side.

a=15; b=10
a+=b; results in (15+10) a=25;
b+=2; results in (10+2) b=12;

/=

New value of left side will be old value of it divided with the number on right side.

a=15; b=10
a /= 2; results in (15 / 2) a=7.5;
b /= 2; results in (10 / 2) b=5;

%=

New value of left side will be old value of it modulus with the number  on right side.

a=15; b=10
a %= 3; remainder of (15 / 3) a=0;
b %= 3; remainder of (10 / 3) b=1;

NOTE : use braces () to override the operator priority or precedence.


Ex. Assignment Operators

<html><head><title>Untitled Document</title>
</head><body>
<Script language="javascript">
var a=15; b=10;

document.write("<H2 align=center>VALUE OF A = 15 AND B=10</h2><hr>");
document.write("<h3>Results of = op<hr>  \"a = b\" result is: ");
a=b;
document.write(a+"<br>");
document.write("value of a=(b*100)/100 is :");
a=(b*100)/10;
document.write(a+"<br>");
document.write("<h3><hr>Results of -= operator<hr> value of a-=4 is : ");
a=15; b=10;
a-=4;
document.write(a+"<br>");
document.write("<h3> Results of b-=2 is :");
b-=2;
document.write(b+"<br>");
document.write("<h3><hr>Results of *= operator<hr> Result of a*=3 is : ");
a=15; b=10;
a *= 3;
document.write(a+"<br>");
document.write("<h3>results of b*=2 is :");
b *= 2;
document.write(b+"<br>");
document.write("<h3><hr>Results of /= operator<hr> Result of a/=2 is : ");
a=15; b=10;
a /= 3;
document.write(a+"<br>");
document.write("<h3>results of b/=2 is :");
b /= 2;
document.write(b+"<br>");
document.write("<h3><hr>Results of %= operator<hr> Result of a%=2 is : ");
a=15; b=10;
a %= 2;
document.write(a+"<br>");
document.write("<h3>results of b%=3 is :");
b %= 3;
document.write(b+"<br>");
</script></body></html>


Logical

&&

Returns true when both the operands are true

a=10, b=15;
if(a>10 &&b>10) c=20; results in c=null.
if(b>10) c=b;
results in c=15

||

Returns true when either operand is true

if(a>10 || b>10) c=20;
results in c=20;

!

Returns true if operand is false and false if operand is true.

a=true; b=false;
if(a) c=40 results in c=40;
if(!b) c=50 results in c=50;

 

Ex. Using Logical operators
<html><head><title>Using logical operators</title></head>
<body>
<H1 align="center">VALUE OF A=10 AND B=15</H1><hr/>
<h2><u>RESULTS OF && OPERATOR <h2></p></U>

<h3><p>Result of " if(a>10 && b>10) c=20" is :</p>
<script>var a=15;b=10;if(a>10 && b>10) c=20; else c="null";document.write(c);</script>
</h3>

<h3><p>Result of " if(b>10) c=b;" is :</p>
<script> var a=15; b=10; if(b>10) c=b; else c="null";document.write(c);</script>
</h3><hr/>

<p><h2><U>RESULT OF " || " OPERATOR</U><h2></p>
<h3><p>Result of "if(a>10 || b>10) c=20;" is :</p>
<script> var a=10; b=15; if(a>10 || b>10) c=20; document.write(c);</script>
<h3><hr>

<p><h2><u>RESULT OF "!" OPERATOR (VALUE OF A="true" and B="false")</U><h2></p>
<h3><p>Result of " if(a) c=40";</p>
<script> var a=true; b=false; if(a) c=40;document.write(c);</script>
</h3>

<h3><p>Result of "if(!b) c=50";</p>
<script> var a=true; b=false; if(!b) c=50;document.write(c);</script>
</h3>
</body></html>


Comparison

 

==

Returns true if operands are equal

a=10; b=15
if(a==b) c=14; result c=null;
a=10; b=10
if(a==b) c=14; result c=14;

===

Checks if both operands are exactly equal in type and value.

a=new String(“test”);
b=new String(“text”);
alert(a===b); //results false
b=a;
alert(a===b); //results true

!=

Returns true if operands are not equal

a=15; b=24;
if(a!=b) c=12; result c=12;
a=15; b=15;
if(a!=b) c=12; result c=null

Returns true if left operand is greater than right operand.

a=10, b=10;
a>b //result false;
b>a //result false;

Returns true if left operand is less than right operand.

a=19, b=23;
a<b //result true;
b<a //result false;

>=

Returns true if left operand is greater than or equal to right operand.

a=14, b=14;
a>=b //result true;
a=14, b=16;
b>= a //result true;

<=

Returns true if left operan is less than or equal to right.

a=213, b=234;
a<=b result true;
a=313, b=313;
a<=b result true;

 

WAP : to show the above condition evaluations.


Ternary Operator

Condition ? val1 : val2

Condition is evaluated and if its true “val1” is assigned to the variable else if its false “val2” is assigned.

a=23; b=45;
c=(a>b)? 34: 44; result c=44;
c=(b>a)? 34: 44; result c=34;
c=(a>b || b>a)? 44: 34; result c=44;
c=((a*5-4)>b)? 33: 56; result c=33;
c=(45*2 >b)? 43: 564; result c=43;

 

Ex. Using Ternary operator
<html><head><title>Using ternary operators</title></head>
<body>
<script language="javascript">
var a=prompt("enter first Number", 0);
var b=prompt("enter second number", 0);
confirm("Enter condition as < or > or <= or >=");
var cond=prompt("enter condition to evaluate");
c=eval(a+cond+b)? 10: 20;
alert ("Ternary operation(true=10 & false=20) : "+a+cond+b+" has resulted in : "+c);
</script></body></html>


Bitwise Operators

&

Bitwise AND.

a=5, b=6

a & b = 4

|

Bitwise OR

a=5, b=6

a | b  = 7

^

Bitwise XOR.

a=5, b=6

a ^ b = 3

~

Bitwise NOT

a=5

~a  = -6

<< 

Shift left.

a=15

a<<1 = 30

>> 

Shift right.

a=15

a>>1 = 7

>>> 

Shift right, zero fill.

a=35

a>>>2 = 8

 

Ex.     


0

0

0

0

0

0

1

1

 

 

27

26

25

24

23

22

21

20

 

128

64

32

16

8

4

2

1

 

0

0

0

0

0

0

2

1

3

 

Ex. Bitwise operator
<html><body>
var test=2;
test=test<<2
alert(test) //alerts 8
</body></html>


Loops


(a) “for”  loop
Syntax:
for (var=startvalue;condition;iteration)
{
code for execution
}

  • var is initialized and condition is evaluated
  • if it is “false” code is terminated else if “true” code is executed and iteration is carried on.
  • condition is checked again and process continues till condition becomes false.

 

Ex. Demo of “for loop”.
<html><head><title>Demo of for loop</title></head>
<body>
<script type="text/javascript">

for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script></body></html>

 

Ex.2 producing color with for loop
<html><head><title>Producing colors</title>
</head><body>
<script langugage="javascript">
document.write("<pre><table border=0>");

for(i=0;i<256;i+=10){
document.writeln("<tr><td bgcolor=rgb(0,0,"+i+")>_________</td>");
document.writeln("<td bgcolor=rgb(0,"+i+",0)>  _________</td>");
document.writeln("<td bgcolor=rgb("+i+",0,0)>  _________</td>");
document.writeln("<td bgcolor=rgb("+i+","+i+",0)>    _________</td>");
document.writeln("<td bgcolor=rgb(0"+","+i+","+i+")>    _________</td>");
document.writeln("<td bgcolor=rgb("+i+","+"0,"+i+")>    _________</td></tr>");
}
</script></body></html>

 

  • WAP that prints from 1,3,5,7,9,11 to 49.
  • WAP that prints from 100,98,96,94 to 50.
  • WAP that prints the first 10 odd numbers.
  • WAP that prints the even numbers between 200 and 300.

(b) while loop

Syntax

while (condition)
  {
  code for execution
  }

  • If the condition is “true” the code is executed else terminated.
  • Loop continues until the condition becomes false.

 

Ex. While Loop Demo
<html><head><title>Demo of While loop</title></head>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
  {
  document.write("The number is " + i);
  document.write("<br />");
  i++;
  }
</script></body></html>


WAP that prints from 1 to 50.
WAP that prints from 100 to 50.


(c) Do while loop

Syntax
do
  {
  code for execution
  }
while (condition);

  • First the code between the braces is executed once.
  • Condition checked and if its true, the loop will continue else it will terminate.
  • The code is executed atleast once.

Ex. Demo of “do while”
<html><head><title> Demo of do while loop</title></head><body>
<script type="text/javascript">
var i=0;
do
  {
  document.write("The number is " + i);
  document.write("<br />");
  i++;
  }
while (i<=5);
</script></body></html>


Breaking loops
A loop can be terminated with “break” statement at any time.

 

Ex.Demo of break statement
<html><head><title> breaking from loops</title><body>
<script type="text/javascript">

for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    break;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script></body></html>


Continuing loops

  • “continue” statement will jump to next iteration when encountered in loop.
  • The code following the “continue”  will be avoided.

 

Ex.Demo of Continue

<html><head><title> Demo of continue in loops</title><body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    continue;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script></body></html>

Conditional Statements


(a) If Statement:
Syntax
if (condition)
  {
  code for execution
  }

  • If the condition is true the code is executed.
  • Condition can be any valid expression which will result in a “true/false”.

 

Ex. Demo of If condition.
<html><head><title> Demo of if condition</title></head><body>
<script type="text/javascript">
var d=new Date();
var time=d.getHours();

if (time<10)
  {
  document.write("<b>Good morning</b>");
  }
</script></body></html>

 

WAP  that takes a character from the user and checks whether the given character is vowel or consonant. (Use OR Logical Operator)
WAP  that takes name, address and age from the user. If age >12 then "You are not a child" should be displayed, otherwise "You are a child" should be displayed. Result should be printed as the following format.
Your name is Ram.
Your address is Kathmandu.
Your age is 23.
You are not a child.


(i)if else  :

Syntax:
if (condition)
  {
   code one
}

else
  {
  code two
  }

  • Condition is evaluated first and if its true first block (code one) is executed.
  • If condition is false “else” block (code two) is executed.

 

Ex. Demo of “if else” statement
<html><head><title> Demo of “if else” </title></head><body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
  {
  document.write("Good morning!");
  }
else
  {
  document.write("Good day!");
  }
</script></body></html>

 

WAP  that takes name and basic salary from the user. On the basis of basic salary, income tax is to be deducted, if basic salary>10000 then 10% of basic salary is deducted otherwise 6% is deducted. Display the details of an employee as the following format.
Your name is Ramesh.
Your basic salary is 12000.
You have to pay income tax of 1200.
Your net salary is 10800.


(ii) “if, else if” ladder 

Syntax 
if (condition1)
  {
  code 1
  }
else if (condition2)
  {
  code 2
  }
else
  {
   default code
  }

  • First “condition1” is evaluated and if true “code 1” is executed and exited.
  • If condition1 is false “condition2” is checked. If its true “code 2” is executed and exited.
  • If condition2 is false “default code” is executed.

 

Ex. Using “if else if” ladder
<html><head><title> Demo of “if else if” ladder</title></head><body>
<script type=”text/javascript”>
var d = new Date()
var time = d.getHours()
if (time<10)
  {
  document.write(“<b>Good morning</b>”);
  }
else if (time>10 && time<16)
  {
  document.write(“<b>Good day</b>”);
  }
else
  {
  document.write(“<b>Good Evening</b>”);
  }
</script></body></html>

 

WAP that takes name, basic salary and marital status from the user. On the basis of Marital status allowance is being determined. If marital status is Married then 15% of basic salary is being given else 8% is being given. Display the details of an employee as the following format.

Your name is Suresh.
Your marital status is Married.
Your basic salary is 10000.
You get allowance of 1500.
Your net salary is 11500.

 

WAP that takes name, basic salary and total years of service (n) from the user. On the basis of total years of service (n) allowance is being determined. The business logic for giving allowance is as follows:

  • if n>0 and n<=5 then allowance is 8% of basic salary
  • if n>5 and n<=10 then allowance is 12% of basic salary
  • if n>10 and n<=18 then allowance is 18% of basic salary
  • if n>18 then allowance is 25% of basic salary

Display the details of an employee as the following format.

Your name is Ramesh
Your basic salary is 10000
You worked for 5 years
Your allowance is 800
Your net salary is 10800.

 

WAP that takes name, basic salary (bs) from the user. On the basis of basic salary income tax (it) and security deposit (sd) is being deducted. The business logic is as follows

  • if bs>0 and bs<=2000 then it=2% of bs and sd=8% of bs
  • if bs>2000 and bs<=7000 then it=5% of bs and sd=10% of bs
  • if bs>7000 and bs<=12000 then it=8% of bs and sd=10% of bs
  • if bs>12000 and bs<=20000 then it=12% of bs and sd=10% of bs
  • if bs>20000  then it=17% of bs and sd=10% of bs

Display the details of an employee.
Your name is Raju
Your basic salary is 10000
Your income tax is 800
Your security deposit is 1000
Your net salary is 8200.


b)Switch:
Syntax:
switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}
Expression n (most often a variable) is evaluated once. The value 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.

 

Ex. Using switch statement
<html><head><title>Using switch statement</title>
<script language="javascript">
function calc(c){
var opt=c;
var a=parseInt(myf.no1.value);
var b=parseInt(myf.no2.value);

          if(a>0 && b>0) {

          switch(opt){

          case 0: alert ("Multiplication of "+a+" and "+ b+ " is : "+(a*b));
break;

          case 1: alert (b + " subtracted from "+a+" is : "+(a-b));
break;

          case 2:          alert(a + " and " + b + " added together is : "+(a+b));
break;

          case 3: alert(a + " divided by " + b + " is : " + (a/b));
break;

          case 4: alert(b + " percent of " + a + " is :" + (a*b)/100);
break;

          case 5: alert(a + " modulus of "+b+" is : "+ (a%b));
break;

          }

          }
else alert("Please enter proper numbers");
}

</script>
</head>

<body bgcolor=black text=lime>
<h2>Enter values and select the operation</h2>
<hr>
<form name=myf>
<p><input type="text" name="no1">
<p><input type="text" name="no2">
<p>Select the operation</p>
<select name=op>
<option>Multiplication
<option>Subtraction
<option>Addition
<option>Division
<option>percentage
<option>Modulus
</select>
<input type=button value=OK onClick="calc(op.selectedIndex)">
</form></body></html>

 

WAP: using switch to recognize the days of the week and put an alert message accordingly.  Use Date() function to get the day of the week.


Special Operators


(a) (,) comma: Used for multiple expressions.

Ex: for (var i=0, y=0; i<5; i++, y+=2){
     document.write(i+" "+y+"<br />")
}

(b) delete:
Deletes a variable defined not using "var", custom object property, method, or array element. It returns true if successful, false if not.
Ex. var x=3
y=4

delete x  //returns false, since x is a declared variable
delete y  //returns true, since y is an undeclared variable

 

(c)  in :
Checks for property of an object and returns true if property exists in object, false if not.

Ex.          var workers={worker1: 'peter', worker2: 'edward'}

"worker1" in workers //true

 

(d) instanceOf:
Checks for the type of an object.

Ex.
var today=new Date()
alert(today instanceof Date) //alerts true, today is a Date object

 

(e) new:
Ex.
var today=new Date() //create new instance of Date object

(f) typeOf :
The type of the argument passed is checked for its class.

Ex.
typeof 0 //number
typeof “name” //string
typeof false //Boolean

typeof window //object
typeof Math //object
typeof new Array() //object
typeof null //object

Note that apart from most core and user defined objects, arrays and null itself also evaluates to "object" in typeof.

typeof alert //function (window.alert())
typeof Date //function
typeof new Function("var x=3") //function
typeof document.getElementById //function

typeof null  //null

if (typeof x=="undefined")
alert("x doesn't exist!")


Functions
The most basic purpose of a function is to contain code and perform certain task. A function's advanced features are that it can take parameters and return values. Once we have defined a function, we can call it from anywhere, and any number of times.  Code must be embedded in a  pair of curly braces (“{}”).

 

Ex:
<HTML><HEAD><TITLE>Functions</TITLE>
<SCRIPT>
function hello() {
document.write('Hello');
}
hello();
hello();
</SCRIPT></HEAD></HTML>


Parameters for Functions
We can pass values or variables to the functions.

Ex:
<HTML><HEAD><TITLE>Parameters</TITLE>
<SCRIPT>
function greeting(greetStr) {
document.write(greetStr);
}

greeting('Hello');
greeting(“Hello ”+’?’);
var str=”Goodbye”
greeting(str);
</SCRIPT>
</HEAD>
</HTML>


Multiple parameters
<HTML><HEAD><TITLE>Multiple Parameters</TITLE>
<SCRIPT>
function greeting(greetStr,number) {
if (number!=parseInt(number)||number<=0) number=1;
for (iter=0;iter<number;iter++) document.write(greetStr+'<BR>');
}
greeting('Hello',5);
greeting('Goodbye');
greeting('HelloZero',0);
greeting('HelloThreePointOne',3.1);
greeting('HelloABC','ABC');
greeting('HelloMinusTen',-10);
</SCRIPT></HEAD></HTML>

 

Ex:
<HTML><HEAD><TITLE>parseInt </TITLE>
<SCRIPT>
function displayparseInt(n) {
document.write('<h2>parseInt of '+n+' equals '+parseInt(n)+'<BR></h2>');
}

function displayparseFloat(n) {
document.write('<h2>parseFloat of '+n+' equals '+parseFloat(n)+'<BR></h2><hr>');
}

displayparseInt(5);
displayparseFloat(5);
displayparseInt(null);
displayparseFloat(null);
displayparseInt(3.1);
displayparseFloat(3.1);
displayparseInt(0);
displayparseFloat(0);
displayparseInt('ABC');
displayparseFloat('ABC');
displayparseInt(-10);
displayparseFloat(-10);
displayparseInt("3 chances")          ;
displayparseFloat(“3 chances”);
displayparseInt("   5 alive");
displayparseFloat(“ 5 alive”);

</SCRIPT></HEAD></HTML>


Returning values from functions
Values can be returned from functions.  Only one value may be returned.  It can be stored or displayed directly.  If you need to pass many values create a object and pass the object reference.

 

Ex Returning Values
<HTML><HEAD><TITLE>Return values</TITLE>
<SCRIPT>
function square(x) {
return x*x;
}
document.write(square(5) +'<BR>');
ninesquared=square(9);
document.write(ninesquared);
</SCRIPT></HEAD></HTML>


Local/Global Variables in functions
Its a variable that cannot be seen outside its scope, and behaves independently from other variables of the same name.

Ex.
<HTML><HEAD><TITLE>Local</TITLE>
<SCRIPT>
x=5;
function printlocal() {
var x=10;
document.write('Local variable X is '+x+'<BR>');
}

document.write('Global variable X is '+x+'<BR>');
printlocal();
</SCRIPT></HEAD></HTML>


Resursive Functions
Resursive functions call themselves.  It can cause infinite recursion.  The last call is evaluated first and then calls engulfing it are evaluated in order of occurrence from “inside Out”.


Ex.
<html><head><title>Recursive functions</title></head>
<body>
<script language=”javascript”>
function factorial(num){
If(num>1){
Return num*factorial(num-1);
}
else {
return num;
}
}
factorial(8);
</script></body></html>


Using Built-in Java Script Objects
JavaScript is an Object Oriented Programming (OOP) language.
OOPs allows to define own data types and own objects.

 

Using Objects

  • Properties of the object are variables created automatically when the object is created. 

They carry system created default value which can be used while scripting.
For Ex. When a string is created, its length is automatically created by the system and stored in “length” variable.  It can be accessed like obj.length.

Ex.     a=”text”;
document.wrtie(a.length);

 

Ex. <Html>
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
</html>

  • Without object its properties cannot be accessed/used.
  • First the object and a “.” Connector is used to link to its property for use.  Ex: txt.length, Number.MAX etc.

 

Ex. Using object properties
<html><body>
<script language="javascript">
var x = navigator;
document.write("CodeName=" + x.appCodeName);
document.write("<br />");
document.write("MinorVersion=" + x.appMinorVersion);
document.write("<br />");
document.write("Name=" + x.appName);
document.write("<br />");
document.write("Version=" + x.appVersion);
document.write("<br />");
document.write("CookieEnabled=" + x.cookieEnabled);
document.write("<br />");
document.write("CPUClass=" + x.cpuClass);
document.write("<br />");
document.write("OnLine=" + x.onLine);
document.write("<br />");
document.write("Platform=" + x.platform);
document.write("<br />");
document.write("UA=" + x.userAgent);
document.write("<br />");
document.write("BrowserLanguage=" + x.browserLanguage);
document.write("<br />");
document.write("SystemLanguage=" + x.systemLanguage);
document.write("<br />");
document.write("UserLanguage=" + x.userLanguage);
</script></body></html>


Accessessing different levels of objects

  • To access object inside another object or methods of another object use “.” connector.

Ex. str.toLowerCase(), date.toString(), no.isNaN();

Ex. “parent.rtframe.document.write()” is hierarchy of connected objects. Here we have parent, rtframe and document as three objects and write() method is defined in the document object.

Ex:  create 2 frames html page. If you are clicking a button in left frame, you will write in right frame.


Contents of file “main.html”
<html>
<frameset cols=”40%,60%”>
<frame name=”ltframe” src=leftframe.html >
<frame name=”rtframe” src=rightframe.html>
</frameset>
</html>


Contents of file “leftframe.html”
<html><body>
<input type=button value=<write in right frame” onClick=”parent.rtframe.document.write(‘connecting objects<br>’);”>
</body></html>


Contents of file “rightframe.html”
<html><body>
“I Love Javascript”
</body></html>


“with” Keyword in JS
When assigning values to properties of objects which are lengthy you can avoid repeating the object heirarchy.

          Ex.      document.forms.order.user.value=”Dinesh”;
document.forms.order.city.value=”Kathmandu”

          Can be written as :-
with(document.forms.order){
user.value=”Dinesh”;
city.value=”Kathmandu”’
}


Arrays
Arrays are collection of identical elements with a single variable name.  The elements are identified with an index number.  In JS index starts from 0.  Array has an “length” property automatically.

 

Creating Arrays

(a) var myCars=new Array();   
//specifies that mycars is an array.
(b) var myCars=new Array(3); 
//specifies that mycars is an array of 3 elements.
(c) var myCars=new Array("Saab","Volvo","BMW"); 
//specifies mycars array along with three elements as values.


Assigning values to arrays

(a) var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
//In this type you can add any no of items.

(b) var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
//You can add three elements.

(c) var myCars=new Array("Saab","Volvo","BMW"); 
//you are assigning the values while declaration itself.


Accessing Arrays
Elements of arrays will be access with their index numbers.  Each element can act as a variable.  It can be used in the place of variables for all manipulations and they can also be modified.

Ex:      var b=myCars[1]      //results in b=”Volvo”.
myCars[1] = “Mercedes”;    //results in myCars[1] value as “Mercedes”.


Array inbuild functions


concat()

  • Syntax: arrayObject.concat(arrayX,arrayX,......,arrayX)
  • Joins given arrays & returns the new array.
  • No change in Original array.

join()

  • is used to put all the elements of an array into a string with comma by default.
  • Can specify separator.

pop()

  • Is used to remove and return the last element of an array.
  • changes the length of original array.

push()

  • Syntax : arrayObject.push(new1,new2,....,newX)
  • adds given elements at the end of an array and returns the new length.
  • At least one element is must. Changes the original array.

 
reverse()

  • Syntax : arrayObject.reverse()
  • reverses the order of the elements in an array and changes original array.

shift()

  • Syntax: arrayObject.shift()
  • removes and returns the first element of an array.
  • changes the length of the array.

unshift()

  • Syntax : arrayObject.unshift(new1,new2,....,newX)
  • adds given elements at the beginning of an array and returns the new length.
  • At least one element is must.
  • changes length of original array.
  • does not work properly in Internet Explorer!

slice()

  • Syntax : arrayObject.slice(start,end)
  • method returns selected elements from an existing array.
  • Start : Required. Specifies the start position. Must be a number. Starts at 0
  • End : Optional. Specifies end position. Must be a number
  • Use negative numbers to select from the end of the array.
  • If end position not specified, all elements till end of array are sliced.

 

sort()

  • Syntax : arrayObject.sort(sortby)
  • sorts the elements of an array in an order.
  • Sortby : Optional. Specifies the sort order. Must be a function
  • Sorts alphabetically by default. Nos will not be sorted correctly.
  • Original array is changed

splice()

  • removes and adds new elements to given array.
  • Syntax : arrayObject.splice(index,howmany,element1,.....,elementX)
  • Index : Required. Specify where to add/remove elements. Must be a number
  • Howmany : Required Specify how many elements should be removed. Must be a number or can be "0"
  • element1: Optional. Specify a new element to add.
  • elementX :Optional. Several elements can be added.

Ex. Using array functions
<html><head><title>Using Array functions</title></head><body>
<pre>
<script type="text/javascript">
var arr = new Array(3);
arr[0] = "Jani";
arr[1] = "Tove";
arr[2] = "Hege";

var arr2 = new Array(3);
arr2[0] = "John";
arr2[1] = "Andy";
arr2[2] = "Wendy";

var arr3 = new Array(2);
arr3[0] = "Stale";
arr3[1] = "Borge";

document.write("<h3>Three arrays are </h3> \n");

document.write("<h3>arr</h3>"+arr+"\n\n");
document.write("<h3>arr2</h3>"+arr2+"\n\n");
document.write("<h3>arr3</h3>"+arr3+"\n\n");

document.write("<h3>After using \"arr.concat(arr2)\" result is </h3>");
document.write(arr.concat(arr2)+"\n\n");  //results  Jani,Tove,Hege,John,Andy,Wendy

document.write("<h3>After using \"arr.concat(arr2,arr3)\" result is </h3>");
document.write(arr.concat(arr2,arr3)+"\n\n");  //results Jani,Tove,Hege,John,Andy,Wendy,Stale,Borge

document.write("<h3>After using \"arr.join()\" result is </h3>\n");
document.write(arr.join() + "\n\n");  //results Jani,Tove,Hege

document.write("<h3>After using \"arr.join(\'.\')\" result is </h3>\n");
document.write(arr.join(".")+"\n\n"); //results Jani.Tove.Hege

document.write("<h3>Present value of \"arr\" is </h3>\n");
document.write(arr + "\n\n"); // results:  Jani,Tove,Hege

document.write("<h3>After using arr.pop()</h3>\n");
document.write(arr.pop() + "\n\n");  // results: Hege

document.write("<h3>Present value of \"arr\" is</h3>\n");
document.write(arr+"\n\n");  // results:  Jani,Tove

 

document.write("<h3>After using arr.push(\"Hege\") result is</h3> \n");
document.write(arr.push("Hege") + "\n\n"); // 3

document.write("<h3>Present value of \"arr\" is</h3>\n");
document.write(arr+"\n\n"); // results:  Jani,Tove,Hege

document.write("<h3>After using \"arr.reverse()\" result is</h3> \n");
document.write(arr.reverse()+"\n\n"); //Hege,Tove, Jani

 

document.write("<h3>After using \"arr.shift()\" result is</h3> \n");
document.write(arr.shift() + "\n\n"); //results Hege

document.write("<h3>Present value of \"arr\" is</h3>\n");
document.write(arr+"\n\n"); // Tove, Jani

document.write("<h3>After using \"arr.slice(1)\" result is</h3> \n");
document.write(arr.slice(1) + "\n\n"); //Tove

document.write("<h3>Present value of \"arr\" is</h3>\n");
document.write(arr+"\n\n"); // Tove, Jani

document.write("<h3>After using \"arr.slice(0,1)\" result is</h3> \n");
document.write(arr.slice(0,1)+"\n\n") // Tove, Jani

document.write("<h3>Present value of \"arr\" is</h3>\n");
document.write(arr+"\n\n"); // Tove, Jani

document.write("<h3>After using \"arr.sort()\" result is</h3> \n");
document.write(arr.sort()+"\n\n"); //Jani, Tove

 

document.write("<h3>After using \"arr.splice(1,0,\'Hege\',\'Borge\')\" result is</h3> \n");
document.write(arr.splice(1,2,"Hege","Borge")+"\n\n"); //Jani,Hege,Borge

 

document.write("<h3>After using \"arr.unshift(\'Kai Jim\')\" result is</h3> \n");
document.write(arr.unshift("Kai")); // Kai Jim, Jani,Hege,Borge,Tove
document.write("\nBecause unshift does not work properly with IE");
</script></body></html>


Sorting number arrays
<html><head><title>Using Array functions</title></head><body>
<script type="text/javascript">
function sortNumber(a,b)
{
return a - b;
}
var arr = new Array(6);
arr[0] = "10";
arr[1] = "5";
arr[2] = "40";
arr[3] = "25";
arr[4] = "1000";
arr[5] = "1";
document.write(arr + "<br />");
document.write(arr.sort(sortNumber));
</script></body></html>


For...In Statement
It loops through the elements/or properties of an object.
The  code in the body of the loop is executed once for each element/property.
The variable argument can be a named variable, an array element, or a property of an object.

 

Syntax:
for (variable in object)
  {
  code to be executed
  }

 

Ex. Using “For …In”
<html><title>Using for in statement </title></head>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write (x+"  : ");
document.write(mycars[x] + "<br />");
}
</script></body></html>


String (build in) functions

 

Using  the length property:  returns the number of characters in a string.
Syntax: var a =”mystring”;
document.write(a.length);


String Object Methods


Method

Description

strike()

Displays a string with a strikethrough

anchor()

Creates an HTML anchor

big()

Displays a string in a big font

blink()

Displays a blinking string

bold()

Displays a string in bold

fontcolor()

Displays a string in a specified color

fontsize()

Displays a string in a specified size

italics()

Displays a string in italic

concat()

Joins two or more strings

sup()

Displays a string as superscript

link()

Displays a string as a hyperlink

toLowerCase()

Displays a string in lowercase letters

toUpperCase()

Displays a string in uppercase letters


Using common string functions

NOTE: All the string arrays have starting index as 0.

 

Ex. Using common string functions
<html><title>Using common string functions</title></head>
<body>
<script type="text/javascript">
var str="Hello world!";
document.write(str.anchor("myanchor"));
document.write(str.big());
document.write(str.blink());
document.write(str.bold());
document.write(str.charAt(1)); //result e
document.write(str.charCodeAt(1)); //result 101

var str1="Hello ";
var str2="world!";
document.write(str1.concat(str2));  //Result : Hello world!

var str="Hello world!";
document.write(str.fixed()); //displays as teletype text.
document.write(str.fontcolor("Red")); //text will be displayed in red.
document.write(str.fontsize(7)); //size 1- 7 only
document.write(str.italics());

//this is a static method.
document.write(String.fromCharCode(72,69,76,76,79)); // result HELLO
document.write("<br />");
document.write(String.fromCharCode(65,66,67)); //result ABC
document.write(str.link("http://www.w3schools.com")); //a link appears.
document.write(str.small()); //returns small font string.
document.write(str.strike()); //produces strike through style.
document.write(str.sub()); //produces a subscript.
</script></body></html>


Using special string functions

charAt()

Returns the character at a specified position

charCodeAt()

Returns the Unicode of the character at a specified position

fixed()

Displays a string as teletype text

fromCharCode()

Takes the specified Unicode values and returns a string

indexOf()

Returns the position of the first occurrence of a specified string value in a string

lastIndexOf()

Returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string

match()

Searches for a specified value in a string

replace()

Replaces some characters with some other characters in a string

search()

Searches a string for a specified value

slice()

Extracts a part of a string and returns the extracted part in a new string

small()

Displays a string in a small font

split()

Splits a string into an array of strings

sub()

Displays a string as subscript

substr()

Extracts a specified number of characters in a string, from a start index

substring()

Extracts the characters in a string between two specified indices

valueOf()

Returns the primitive value of a String object


indexOf() 

  • returns the position of the first occurrence of a specified string value within a string.
  • Syntax  stringObject.indexOf(searchvalue,fromindex)
  • “Seatchvalue” is a string value to search for
  • (Optional) “fromindex” specifies where to start the search.
  • is case sensitive.
  • Returns -1 if given string is not found.

Ex. Using indexOf()
<html>
<script type="text/javascript">
var str="Hello world!";
document.write(str.indexOf("Hello") + "<br />");
document.write(str.indexOf("World") + "<br />");
document.write(str.indexOf("world"));
</script>
</html>

 

Results:  0   -1     6.


 lastIndexOf()

  • Same as indexOf() but returns the position of the last occurrence of a specified string.
  • Search is backwards from the specified position in a string. 
  • Syntax: stringObject.lastIndexOf(searchvalue,fromindex)

Ex. Using lastIdexOf()

<html>
<script type="text/javascript">
var str="Hello world!";
document.write(str.lastIndexOf("Hello") + "<br />");
document.write(str.lastIndexOf("World") + "<br />");
document.write(str.lastIndexOf("world"));
</script><html>

 

Result : 0     -1        6


match()

  • searches for a specified value in a string. Similar to indexOf() and lastIndexOf(), but it returns the specified value of string, instead of the position of the string.
  • Syntax: stringObject.match(searchvalue)
  • Is case sensitive!
  • returns null if the string value not found.

 

Ex. Using method()
<html>
<script type="text/javascript">
var str="Hello world!";
document.write(str.match("world") + "<br />");
document.write(str.match("World") + "<br />");
document.write(str.match("worlld") + "<br />");
document.write(str.match("world!"));
</script></html>

 

Result : world         null     null     world!


replace()
will replace a string/char with another string/char in a given string.
Syntax: stringObject.replace(findstring,newstring)
“findstring”

  • Required. 
  • Specifies a string value to find.
  • To perform a global search add a 'g' flag
  • To perform a case-insensitive search add an 'i' flag.

“newstring”

  • Required.
  • Specifies the string to replace the found value from findstring
  • This method is case sensitive.

 

Ex. replace()

<html>        
<script type="text/javascript">
var str="Visit Microsoft!";
document.write(str.replace(“Microsoft”, "FutureInformationTechnology"));
</script></html>

 

Result : Visit FutureInformationTechnology!


search()

  • method is used to search a string for a specified value.
  • Syntax: stringObject.search(searchstring)
  • “Searchstring” Required. The value to search for in a string. To perform a case-insensitive search add an 'i' flag
  • is case sensitive.
  • returns the position of the specified value in the string.
  • If no match was found it returns -1.

Ex. Using search()
<html>
<script type="text/javascript">
var str="Visit Aptech!";
document.write(str.search(“Aptech”));
</script></html>


Results : 6


slice()

  • method extracts a part of a string and returns the extracted part in a new string.
  • Syntax: stringObject.slice(start,end)
  • “start”  Required. Specifies starting position. Must be a number. Starts at 0
  • “end”  Optional. Specifies end position. Must be a number
  • use negative index numbers to select from the end of the string.
  • If end is not specified, all characters till end of the string are extracted..

Ex. Using slice()

<html>
<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(0));
document.write(str.slice(6));
document.write(str.slice(0,1));
document.write(str.slice(6,11));
</script></html>


Result:
Hello happy world!
happy world!
            H
Happy


split()

  • used to split a string into an array of strings.
  • Syntax: stringObject.split(separator, howmany)
  • “separator” :  Required. Specifies the character, regular expression, or substring that is used to determine where to split the string
  • “howmany” : Optional. Specify how many times split should occur. Must be a numeric value
  • If an empty string ("") is used as the separator, the string is split between each character.

Ex. Using split()
<html>
<script type="text/javascript">
var str="How are you doing today?";
document.write(str.split(" ") + "<br />");
document.write(str.split("") + "<br />");
document.write(str.split(" ",3));
</script></html>


Result :
How,are,you,doing,today?
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
How,are,you


substr()

  • extracts a specified number of characters in a string, from a start index.
  • Syntax: stringObject.substr(start,length)
  • start : Required. Where to start the extraction. Must be a numeric value
  • length: Optional. How many characters to extract. Must be a numeric value.
  • To extract characters from the end of the string, use a negative start number (This does not work in IE).
  • If length not specified it extracts till the end of string.

Ex. Using substr()
</html>
<script type="text/javascript">
var str="Hello world!";
document.write(str.substr(3));
document.write(str.substr(3,7));
</script></html>

 

Result :
lo world!
lo worl


substring()

  • method extracts the characters in a string between two specified indices.
  • Syntax: stringObject.substring(start,stop)
  • start : Required. Where to start the extraction. Must be a numeric value
  • stop : Optional. Where to stop the extraction. Must be a numeric value
  • If the stop is not specified it extracts to the end of the string.

Ex: using substring()
<html>
<script type="text/javascript">
var str="Hello world!";
document.write(str.substring(3));
document.write(str.substring(3,7));
</script>

 

Result :
lo world!
lo w


escape()

  • escape() encodes a string, so it can be read on all computers.
  • It encodes special characters, with the exception of: * @ - _ + . /
  • Use the unescape() function to decode strings encoded with escape().
  • The escape() and unescape() functions should not be used to encode or decode URIs. Use
  • encodeURI() and decodeURI() functions instead!

 

Ex. Escape
<script type="text/javascript">
document.write(escape("Visit W3Schools!") + "<br />");
document.write(escape("?!=()#%&"));
</script>

 

OUTPUT
Visit%20W3Schools%21
%3F%21%3D%28%29%23%25%26

 

WAP to find and replace a given string.  User should enter two words one word which should be replaced and the other word which has to be replaced with. Display the complete string.

WAP to show all the character entities for example &#65; will produce “A”.  So produce all the character entities like “character for &#65; is : A” which should be the display.


Number class functions & properties

 

Properties
The properties which are defined as final variables in class consists of all caps.
Ex.   MAX_VALUE returns largest value that JS can hold, it is 1.7976931348623157 x 10308.

  • Usage : document.write(Number.MAX_VALUE);

Ex. MIN_VALUE returns the smallest value JS can hold, it is 5 x 10-324

 

Properties

Description

Math.E

Constant e base of the natural logarithm

Math.LN2

Natural logarith of 2

Math.LN10

Natural logarith of 10

Math.LOG2E

Base 2 logarith of e

Math.LOG10E

Base 10 logarith of e

Math.PI

The constant pi

Math.SQRT1_2

The reciprocal of the square root of 2

Math.SQRT2

Square root of 2.


Some basic methods of JS Math
These methods can be accessed without an object.  These are final functions given in Math class. 
USAGE : Var a = 7.5
b= Math.ceil(a);
b=Math.floor(a);
b=Math.max(34, 56);
b=Math.pow(34, 2);

 

Properties

Description

Math.abs()

Return an absolute value

Math.acos()

Return an arc cosine

Math.asin()

Return an arc sine

Math.atan()

Return an arc tangent

Math.atan2()

Return angle from an x-axis to a point.

Math.ceil()

Round a number up

Math.cos()

Return a cosine value

Math.exp()

Return an exsponent of constant e

Math.floor()

Round a number down

Math.log()

Return a natural logarithm

Math.max()

Return the largest of two numbers

Math.min()

Return the smaller of two numbers

Math.pow()

Return the power value

Math.random()

Return a random number

Math.round()

Round to the nearest integer

Math.sin()

Return a sine value

Math.sqrt()

Return the square root

Math.tan()

Return a angent value


toExponential()  gives exponential notation.
toPrecision() returns number of precision of the given number.
toFixed() rounds the given number to specified no of decimal places.

 

Ex. Number functions
<html><head><title>Using number properties</title></head><body>
<script type="text/javascript">
document.write(Number.MAX_VALUE);
document.write(Number.MIN_VALUE);
Month = Number.NaN;
document.write(Month);
var num = new Number(10000);
document.write (num.toExponential(1)); //result 1.0 e+4.
var num = new Number(10.000);
document.write (num.toPrecision(4)); //result 10.00
var num = new Number(13.37);
document.write (num.toFixed(1)); //result 13.4
</script></body></html>


Date class
Manipulation of dates like (a) setting date and time, (b) Using system clock for DHTML effects, (c) making a time stamp on a file, (d) knowing the time difference between different time zones while comparing with Universal Time (GMT) etc  are performed with the help of functions available in Date class.

 

Basic functions of Date.

Function

Description

Usage/Example

Date()

Creates a new date object

var d = new Date();

getDay()

returns the day from the date object

var day=d.getDay();

getMonth()

returns the month from the date object

var day=d.getMonth();

getYear()

Returns the year from the date object

var day=d.getYear();

getHours();

Returns hours from the date object

var day=d.getHours();

getMinutes();

Returns minutes from the date object

var day=d.getMinutes();

getSeconds();

Returns seconds from the date object

var day=d.getSeconds();

getMilliSeconds();

Returns milli seconds from the date object.

var day=d.getMilliSeconds();

getUTCHours();

Returns the standard GMT Universal time

var day=d.getUTCHours();

setDate();

Sets the date for the time object

var newday = d.setDate(21);

setMonth();

Sets the Month

var newmonth =d.setMonth(1);

setFullYear();

Sets the Year

var newyear = d.setFullYear(2012);

setHours();

Sets the hours

var newhours = d.setHours(12);

setMinutes();

Sets the minutes

var newMinutes = d.setMinutes(30);

setSeconds();

Sets the seconds

var newSeconds = d.setSeconds(15);

toString();

Changes the date obj into string representation

Date.toString();

toGMTString();

Changes the date into standard GMT time string.

Date.toGMTString();


Ex. Calculations with time
<html>
<body>
<script language="javascript">
var start=new Date();
var startmilsec = start.getTime();
var num=0;
for(var i=0;i<250000;i++) num++;
var stop= new Date();
var stopmilsec = stop.getTime();
var difference = (stopmilsec - startmilsec)/1000;
document.write("It took "+difference+" seconds for calculating the loop");
</script>
</body>
</html>

 

WAP to print the following:

Current Time in Nepal
Good Afternoon Anmol
Hours : 17
Minutes: 39
Seconds: 16.45

Universal time
Mon Jul 2009 11:15:06 GMT+0545 (GMT Daylight Time)


Using System clock
The Window object has “setTimeout()” function which can be used to repeatedly call a function with a specified time gap.  It takes two parameters (a) function which should be called (b) time in milliseconds after which every call should be made.

 

Ex.System clock
<html>
<head><title>Untitled Document</title></head>
<body>
<script language="javascript">
var num=0, tim;
function timeout(){
num++;
if(num==3){
alert("ok- I told you twice");
window.clearInterval(tim);
}
else{
alert("this is 10-second message No :"+num);
tim=window.setTimeout("timeout()",1000);
}
}
timeout();
</script>
</body>
</html>

 

Ex.JS Digital clock
<html>
<head>
<title>digital clock</title>
</head>
<script language="javascript">
function tick(){
//create a new Date Object
var now= new Date();

//extract the current hours, minute and seconds
var hh = now.getHours();
var mn = now.getMinutes();
var ss = now.getSeconds();

//ensure each component has to digits
if(hh <=9) hh = "0"+hh;
if(mn <= 9) mn = "0"+mn;
if(ss <=9) ss="0"+ss;

//assign the current time string to the form field
document.forms.f.clock.value = hh + ": " + mn + ": " + ss;

//set the interval to one second
window.setTimeout("tick()",1000);
}
</script>
<body>
<form name="f">

<input type="text" style="background-color:#000"  name="clock" value=" " size="36" style="width:175;background-color:#000;color:#0F0;font-size:36px;font-family:impact;">

<p><input type="button" name="sb" onClick="tick()" value="click to start the clock"
</form>
</body>
</html>


Boolean class
Var myBool = new Boolean(value);
If the value parameter is omitted, or is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is set to true (even with the string "false")!


Creating Boolean objects
<html><body>
<pre>
<script language="javascript">

//All these objects produce False as result
document.write("value of new Boolean() is: \t\t"+new Boolean()+"<br>");
document.write("value of new Boolean(0) is: \t\t"+new Boolean(0)+"<br>");
document.write("value of new Boolean(null) is: \t\t"+new Boolean(null)+"<br>");
document.write("value of new Boolean(\"\") is: \t\t"+new Boolean("")+"<BR>");
document.write("value of new Boolean(false) is: \t"+new Boolean(false)+"<br>");
document.write("value of new Boolean(NaN) is: \t\t"+new Boolean(NaN)+"<br>");

 

//All the following objects will produce true as result.
document.write("value of new Boolean(true) is: \t\t"+new Boolean(true)+"<br>");
document.write("value of new Boolean(\"true\") is: \t"+new Boolean("true")+"<BR>");
document.write("value of new Boolean(\"false\") is: \t"+new Boolean("false")+"<BR>");
document.write("value of new Boolean(\"Richard\") is: \t"+new Boolean("Richard")+"<BR>");
</script>
</pre>
</body></html>


Classes

  • Classes resemble real time objects containing characteristics called “properties”.
  • When a object is created it forms physically in the memory, while class is only a logical part. 
  • Just like a rubber stamp when stamped on a sheet creates only a impression. Here the rubber stamp is the class and impressions on sheets are objects.
  • JavaScript doesn't have a keyword specific to class we have to develop classes in a different way using functions.
  • “this” keyword refers to the current object of the class.

Significance of “this” keyword in JS

  • “this” keyword refers to the current object.
  • Once the reference is received by the function/program, it can have control over all the properties/methods of the given object.

Ex. <input type=text onChange=”processchange(this)”>
Here “this” sends the reference of the “text component object” to the “processchange()” function.

<form name=”appform” onSumit=”processform(this)”>
Here “this” sends the reference of the “form object” to the “processform()” function. All components of form will be accessible to “processform()”.

 

Ex. “this”  demo

<html><head><script language="javascript">
function disp(a){
var x=a;

          if(a===document.f.myb1){
alert("You have clicked Button");
}
else if(a===document.f.myt){
alert("you have changed text in Text box to "+document.f.myt.value);
}
else if(a===document.f.rbutton1){
alert("You have clicked radio button one");
}
else if(a===document.f.rbutton2){
alert("you have clicked radio button two");
}
else if(a===document.f.myselect){
alert("you have selected "+document.f.myselect.value);
}                 
}
</script><body>
<form name="f">
<p><input type="button" name="myb1" value="Button one" onClick="disp(this)"; />
<p><input type="text" name="myt" value="Text box one" onChange="disp(this)";/>
<p>Radio one <input type="radio" value="Radio button" name="rbutton1" onClick="disp(this)";/>
Radio two <input type="radio" value="rad2" name="rbutton2" onClick="disp(this)"/>
<p>
<select name="myselect" onChange="disp(this)";>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
</select></body></html>

  • “with” keyword lets current process/function/program to “use the given object” and access its properties.

 

Ex : Class demo

<HTML><HEAD><TITLE>Class Demo</TITLE>
<SCRIPT>
function House(rooms,price) {
this.rooms=rooms;
this.price=price;
}
</script>
</head><body>
<script language="javascript">
house1=new House(4,100000);
house2=new House(5,200000);
with (house1) document.write('House 1 has '+rooms+' rooms, '+ 'and costs' +price+'<BR>');
with (house2) document.write('House 2 has '+rooms+' rooms, '+' and costs' +price+'<BR>');
document.write("<h3>Identical code<h3> <hr>");
house3=new Object();
house3.rooms=4;
house3.price=100000;
document.write('House 3 has'+ house3.rooms+' rooms, '+' and costs  '+ house3.price);
</SCRIPT></HEAD></HTML>


Class Methods

The House class has only object properties. Method can replace the repeated statement to see the house details. Method should be mentioned to one of the properties with no braces.

 

Ex.Class Methods Demo
<HTML><HEAD><TITLE>Class Methods Demo</TITLE>
<SCRIPT>
function House(name, price) {
this.name=name;
this.price=price;
this.view=view;
}

function view() {
with (this) document.write(name+' : '+price+'<BR>');
}
house1=new House('House 1',100000);
house2=new House('Big House',200000);
house3=new House();
house4=new House('myhouse');
house5=new House('',230000);
house1.view();
house2.view();
house3.view();
house4.view();
house5.view();
</SCRIPT></HEAD></HTML>


Prototype Methods.
These methods are not described in the object as before, because if 1000 objects created, then thousand times methods are also created.  To avoid this memory overload a key word “prototype” is used to link the method to class object.  That is method is literally created only once but can be accessed by all objects.

 

Ex.Prototype Methods.
<HTML><HEAD><TITLE>Untitled Document</TITLE>
<SCRIPT>
function House(name,price) {
this.name=name;
this.price=price;
}
function view() {
with (this) document.write(name+ ' : '+price+'<BR>');
}
House.prototype.view=view;
house1=new House('House 1',100000);
house2=new House('Big House',200000);
house1.view();
house2.view();
</SCRIPT></HEAD></HTML>


Prototype Variables
Variables can also be added to already existing class object just by linking with the keyword prototype to the variables.

 

Ex.Prototype Variables Demo

<HTML><HEAD><TITLE>Prototype Variables Demo</TITLE>
<SCRIPT>
function House(name, price) {
this.name=name;
this.price=price;
}

function view() {
with (this) document.write(name+' costs &pound;'+price+'<BR>');
}

function totalcost() {
with (this) document.write(name+' has a total cost involved of &pound;'+eval(price+survey+price*salescommission)+'<BR>');
}

House.prototype.view=view;
House.prototype.totalcost=totalcost;
House.prototype.salescommission=.01;
House.prototype.survey=1000;
house1=new House('House 1',100000);
house2=new House('Big House',200000);
house1.view();
house2.view();
house1.totalcost();
house2.totalcost();
</SCRIPT></HEAD></HTML>


Using string Constructor
The constructor property is a reference to the function that created the object.
Syntax  object.constructor

 

Ex:Using String contructor
<html><head><title>Using string constructor</title>
<script type="text/javascript">

function decision(a){

          if (a.constructor==Array) document.write(a+" is an Array <br>");

          if (a.constructor==Boolean) document.write(a+" is a Boolean<br>");

          if (a.constructor==Date) document.write(a+" is a Date<br>");

          if (a.constructor==String) document.write(a+" is a String<br>");
}
</script></head><body>

<script language="javascript">
var a= new String("Mystring");
decision(a);

var a= new Array("One", "two", "Three");
decision(a);

var a = new Date();
decision(a);

var b = new Boolean("True");
decision(b);
</script></body></html>


Using JS inbuild methods for class objects
Objects can also be created using the JS object() constructor.  Properties may then to allocated to the new custorm object declaring a property name and assiginig a value to it.

 

Ex. Creating JS Objects
<html>
<head>
<title>extending js objects</title>
</head>
<body>
<script language="javascript">
//creating a new car object
var car = new Object();

//creating and initializing a maker property
car.maker ="Maruthi";

//creating and initiazing model property
car.model = "2008";

//creating and initializing a color property
car.color = "Red";

//display all the car property value
document.write("First car : " + car.color + "color" + car.maker + " Make " + car.model+" Year model <br>");

//create another object that inherits from the first
var cartwo = new Object();
cartwo.engine = "4.0 liters";
cartwo.make = car;

//display extended class properties
document.write("Extended Car : " + cartwo.make.color + "color" + cartwo.make.maker + " Make " + cartwo.make.model+" Year Model " + cartwo.engine + " Engine Type");

</script>
</body>
</html>


DOM

Document Object Model is a strict hierarchy of objects which are to be used in JS for creating effective web pages.  The pictorial representation of the Document Object Model is given below.  New objects will be added by the w3 consortium as and when needed.  When and how the new objects will be implemented by different browsers, is purely at the discretion of the company.


Event Handling Mechanism
First the event occurs in the browser either initiated by the user by clicking, moving, or pressing keys.  Then the event is notified to all the concerned object handlers.  Handlers can either handle the event or just pass them off. 

 

Events
Events are actions/changes initiated by the user like clicking a button, changing contents in text box, pressing some key on keyboard etc.  Following are the list of events and reasons for occurrence.

 

Attribute

The event occurs when...

onAbort

Loading of an image is interrupted

onBlur

An element loses focus

onChange

The user changes the content of a field

onClick

Mouse clicks an object

ondblClick

Mouse double-clicks an object

onError

An error occurs when loading a document or an image

onFocus

An element gets focus

onKeyDown

A keyboard key is pressed

onKeyPress

A keyboard key is pressed or held down

onKeyUp

A keyboard key is released

onLoad

A page or an image is finished loading

onMouseDown

A mouse button is pressed

onMouseMove

The mouse is moved

onMouseOut

The mouse is moved off an element

onMouseOver

The mouse is moved over an element

onMouseUp

A mouse button is released

onReset

The reset button is clicked

onResize

A window or frame is resized

onSelect

Text is selected

onSubmit

The submit button is clicked

onUnload

The user exits the page


Event Handlers
Event handlers are short system programs or methods which can be used by the programmer to write response code to the user events. 

 

Object

Event Handlers

Selection

onBlur, onChange, onFocus

Text

onBlur, onChange, onFocus, onSelect

TextArea

onBlur, onChange, onFocus, onSelect

Button

onClick

Checkbox

onClick

Radio

onClick

Hypertext link

onClick, onMouseOver

Reset button

onClick

Submit button

onClick

Document

onLoad, onUnload

Window

onLoad, onUnload

Form

onSubmit

 

Event handler can handle the events in two ways (a) by handling it with a function specially coded for such event or (b) handling the event in the tag itself if its small.


Ex: Event handling inside the tag
<html><body>
<form method=”post”>
Enter a value greater than 5 :
<input type=”text” name=”entry” value=”10” onChange=”if(this.value<5) {alert (‘enter value greater than 5’);};>
</form></body></html>


Event methods
In situations when you need to create an event yourself without the user interaction, you can use JS methods.  For ex: if you need to stop user from entering data into a text field use “blur()” method, which will disable the text object automatically.  Common methods for use are:


Method

Description

blur()

Deactivates the object

click()

Clicking event is created on the object

focus()

Activates the object.

select()

Object gets selected

submit()

Browser initiated submit for the form in question.

 

Ex. Creating events

<html><head><SCRIPT language="javascript">
function calculate(form) {
form.square.value=form.entry.value*form.entry.value
form.cube.value=form.entry.value*form.entry.value*form.entry.value
}
</script></head>
<body onLoad=" var name=prompt(‘enter your name’, ‘name’); alert(‘Hi!’+name);">
<form method=post>
Enter a number :<input type="text" name="entry" value="0" onChange="calculate(this.form);"> <br>
Square of number entered :<input type="text" name="square" value="0" onFocus="this.blur();"><br>
Cube of Number Entered : <input type="text" name="cube" value="0" onFocus="this.blur();">
</form></body></html>


Java Script Predefined Objects and classes

 


Properties and methods list of objects in Java Script
Window object is on the top of all the objects.

 

Hierarchy Objects

Object

Properties

Methods

Event Handlers

Window

defaultStatus
frames
opener
parent
scroll
self
status
top
window

alert
blur
close
confirm
focus
open
prompt
clearTimeout
setTimeout

onLoad
onUnload
onBlur
onFocus

Frame

defaultStatus
frames
opener
parent
scroll
self
status
top
window

alert
blur
close
confirm
focus
open
prompt
clearTimeout
setTimeout

none (The onLoad and onUnload event handlers belong to the Window object)

Location

hash
host
hostname
href
pathname
por
protocol
search

reload
replace

none

History

length
forward
go

back

none

Navigator

appCodeName
appName
appVersion
mimeTypes
plugins
userAgent

javaEnabled

none

document

alinkColor
anchors
applets
area
bgColor
cookie
fgColor
forms
images
lastModified
linkColor
links
location
referrer
title
vlinkColor

clear
close
open
write
writeln

none (the onLoad and onUnload event handlers belong to the Window object.

image

border
complete
height
hspace
lowsrc
name
src
vspace
width

none

none

form

action
elements
encoding
FileUpload
method
name
target

submit
reset

onSubmit
onReset

text

defaultValue
name
type
value

focus
blur
select

onBlur
onCharge
onFocus
onSelect


Detailed study of Objects, their properties and methods with examples.

 

Navigator

  • When we know the operating system details then we can make platform specific programs to run on them.  For example Microsoft ActiveX controls does not run on Linux platform to achieve this we have “navigator.platform” property which gives the platform details. 

 

Ex. Displaying browser properties.
<html><body>
<script type="text/javascript">
var x = navigator;
document.write("CodeName=" + x.appCodeName);
document.write("<br />");
document.write("MinorVersion=" + x.appMinorVersion);
document.write("<br />");
document.write("Name=" + x.appName);
document.write("<br />");
document.write("Version=" + x.appVersion);
document.write("<br />");
document.write("CookieEnabled=" + x.cookieEnabled);
document.write("<br />");
document.write("CPUClass=" + x.cpuClass);
document.write("<br />");
document.write("OnLine=" + x.onLine);
document.write("<br />");
document.write("Platform=" + x.platform);
document.write("<br />");
document.write("UA=" + x.userAgent);
document.write("<br />");
document.write("BrowserLanguage=" + x.browserLanguage);
document.write("<br />");
document.write("SystemLanguage=" + x.systemLanguage);
document.write("<br />");
document.write("UserLanguage=" + x.userLanguage);
</script></body></html>

 

  • For knowing the plugins details which are currently installed in the browser we have navigator.plugins array. Whenever a plugin is added to the browser the array will be filled with one more element adding the details of the plugin.  For instance if we add shockwave flash to the browser, an element “navigator.plugins[“shockwave Flash”] is added as an element to the array of plugins.

 

  • The plugin has “name” property which contains the name and version of the plugin and “description” property which gives the details of the plugin.

NOTE: this will work for only Netscape Navigator.

  • Java presence can be detected with the property “navigator.javaEnabled()”.

 

Ex. Checking for Java availability.
<html><head><title>Checking java availability</title></head>
<body><script language="javascript">
if(navigator.javaEnabled()) alert ("Your browser is java enabled");
else alert("Your browser is not java compliant");
</script></body></html>


Window
The below example provides a technique for getting the properties of window under different browsers.  The details of window properties will change from browser to browser and also from version to version.  Every time a DOM object is added to the browser, a property/method/ handler will be added to the existing list.

 

Ex.     <html><head>
<title>window object properties</title>
</head><body>
<script language="javascript">
//show all window properties
for (propertyName in window){
document.write (propertyName + "<br>");
}
</script></body></html>

When run in IE – Version 6 this is the result.
onbeforeunload
onafterprint
top
location
parent
offscreenBuffering
frameElement
onerror
screen
event
clipboardData
onresize
defaultStatus
onblur
window
onload
onscroll
screenTop
onfocus
Option
length
onbeforeprint
frames
self
clientInformation
external
screenLeft
opener
onunload
document
closed
history
Image
navigator
status
onhelp
name

  • Many methods like alert(), prompt(), confirm(), setTimeOut(), clearTimeOut() have already been discussed in earlier chapters.
  • Window.location object contains the full URL address of the current document which is loaded into the browser.  You can get details for each and every part as properties of window.location object.
  • Syntax : protocol : //host / pathname ? # hash

Ex: Details of URL
<html>
<head>
<title>Details of URL</title>
</head>
<body>
<script language="javascript">
var loc=  "Href is  : "+ location.protocol;
var pro=  "Protocol : "+ location.protocol;
var host= "Host is  : "+ location.host;
var path= "Path is  : "+ location.path;
var hash= "Hash is  : "+ location.hash;

//display details

document.write("<h2>"+loc);
document.write("<h2>"+pro);
document.write("<h2"+host);
document.write("<h2>"+path);
document.write("<h2>"+hash);
</script>
</body>
</html>

  • We can access the history object of the browser and navigate to previous or next pages stored in it in the form of URLs. Pages cannot be retrieved but we can make the browser go to previous or next pages/session by using back() and forward() functions.  Window.history.go() function takes one argument .  -1 lead to previous page and 0 will reload the current page 1 will go to next page.

Ex. Using history
<html><head><title>Using history object</title>
<script language="javascript">
function navigate(a){
window.history.go(a)
}
</script></head><body>
<a href="load unload of window.html">click here first to create a url in history</a>
<h1>To navigate push the buttons</h1>
<p><input type="button" value="Previous" onclick="navigate(-1)">
<p><input type="button" value="Next" onclick="navigate(1)">
<p><input type ="button" value="Refresh" onclick="navigate(0)">
</body></html>

  • “window.onload” object is used to initialize/start environment variables which are required for the web page before it is loaded.  Images which have some script attached with it should be loaded before the script starts.  Generally a fuction named as  init() is written in such cases.
  • “window.unload” object is similarly used to remove any database connections, close environment variables, objects created in memory after the user quits the web page.

Ex. Using load and unload objects
<html><head><title>Using load and unload objects</title>
<script language="javascript">
function op(){
var name=prompt("Enter your name");
alert("Hello "+name);
}

function cl(){
alert("Thanks for visiting , Come back soon");
}
</script></head>
<body onLoad="op()", onUnload="cl()">
<script language="javascript">
window.onLoad="op()";
window.onUnload="cl()";
</script></body></html>

  • With “window.status” object, you can set status bar default message to be displayed in the status bar unless it is changed to another message by some object and it will come back to default once again.  Generally the url is shown in the status bar when we hover the mouse over the link but it can be set to different message and return “true” to disable the url display in the status bar.

Ex.Status bar demo
<html><head><title>window status demo</title>
</head><body onLoad="window.defaultStatus='Window Status Demo'">
<p><a href="load unload of window.html" onMouseOver="window.status='No url please';return true">No URL in Status</a>
<p><a href="history object.htm" onMouseOver="window.status='click here'">See the URL in status bar</a>
</body></html>


Pop-up windows :

  • Pop up windows are other windows with own html page inside it.  These windows can be opened with window.open().  Commonly it will take three parameters, (a) html source (b) name of window (c) dimentional features.

Features are :

 


Feature

Description

directories

Adds the links bar

Height

Sets the height in pixels of the document area

Left

The x co-ordinate of the window of the screen

Location

Adds the address bar

menubar

Adds the standard menu bar

resizable

Permits the window to be resized

scrollbars

Enables scrollbars when needed

status

Adds the status bar

Toolbar

Adds the button bar with back & forward buttons

Top

The Y co-ordinate of the window on the screen

Width

Sets the width in pixels of the document area.

 

All the above features may have a value yes/no.  But by just mentioning the property in the open() function itself it is assumed that the feature is on.
Ex. window.open(pop.html,”mywin”,”top=40,left=40”,status,menubar);

 

Ex. Using pop-up windows
<html><head><title>popup window demo</title>
<script language="javascript">
mywinref = 0;
function popup( a ){
if(a=='') alert ("Please select the file and open the pop up window");
else {
mywinref = window.open(a,"mywin","top=40,left=40,width=350,height=400,directories,menubar,toolbar,scrollbars,resizable");
}
}
function setpop(){
if(mywinref==0) alert ("Please open the window first");
else mywinref.close();

}
</script>
</head><body>
<h1>Browse the file you want to open as new pop up and click button</h1>
<p><input type="file" name="myfile">
<p><input type="button" value="Open Pop Up Window" onclick="popup(myfile.value)">
<p><input type="button" value="Close Pop Up Window" onClick="setpop()">
</body></html>


Writing dynamic content to popup-window:
  • We can write dynamically to the pop-up window rather than simply assigning a html file while opening the file. 
  • The “document.open()” method when used with a pop-up window object, opens a stream to the document of the pop up window.
  • After writing contents “document.close()” should be used to close the stream.

Getting Resolution, width and height of user browser:

  • For Internet explorer document.body.clientWidth and document.body.clientHeight gives the width and height of the user borwer. 
  • For Mozilla & netscape window.innerWidth & window.innerHeight will give the width and height values of user browser.
  • Screen.width & screen.height gives the screen resolution of the user browser.

 

Ex. resolution and window dimensions
<html><head><title>window dimensions</title>
<script language="javascript">
var W, H, ScrW, ScrH;
function getwinsize(){
if(document.body.clientHeight){
W = document.body.clientWidth;
H = document.body.clientHeight;
alert("Window Height is : "+H+" Pixels & Width is : "+W+" Pixels");
}
if(window.innerHeight) {
W = innerWidth;
H = innerHeight;
alert("Window Height is : "+H+" Pixels & Width is : "+W+" Pixels");
}
}
function getwinres(){
ScrH = screen.height;
ScrW = screen.width;
alert("Window Resolution is : "+ScrH+" X "+ScrW);
}
</script>
</head><body>
<h1>Resize the window and see different current sizes</h1>
<p><input type="button" value="Get Sizes of Window" onClick="getwinsize()">
<p><input type="button" value="Get Resolution of Window" onClick="getwinres()">
</body></html>


Error Handling

  • Error handling mechanism in JS involves two steps.  The user is given the opportunity to handle the error if not, the system will handle the error itself.  Window.onerror object is used to handle the error, by assining a function to it.  Any function which is assigned to handle the error should take three parameters (a) message, (b) URL (c) Line Number.  It should also return true so that the system is informed that the error has been handled.  With the error handling you can handle the database connections, memory and other environment by yourself.

 

Ex. Error handling
<html><head><title>error handling</title>
<script language="javascript">
window.onerror=errorhandler;
function errorhandler(msg, url, ln){
alert("Error: "+msg + "\n In File : "+url+"\n At Line : "+ln);
return true;
}
</script></head><body>
<script language="javascript">
document.form[the mistatke].value="myButton";
</script></body></html>


DOCUMENT OBJECT

 

Runtime changes in the document with the document.write() function.

  • Understanding Runtime:  Once the document and all its components are loaded into the browser and after that if you are making changes dynamically with java script that is know as runtime changes.
  • Especially when the document.write() function is called after loading the objects in the browser container, then it will open a new document into the current browser window. It will not write to the current document.
  • All the elements, be it functions, java script tags, or html codes, will be loaded into the browser window according to their appearance from top to bottom of the html file.  That is components in head will be loaded first and then components in body will be loaded next.

 

Ex: runtime document demo
<html><head><title>Runtime document demo</title>
<script language="javascript">
function disp(){
document.write("<h1>This is runtime call for document.write() which has resulted in new document");
}

document.write("<h2>This is a simple text from within the head section using script tags and document.write() function");
</script>
</head>
<body>
<hr>
<h1>This is the text generated by HTML h1 tag
<hr>
<form name="f">
<script language="javascript">
document.write("<h2>This is the text generated by document.write() function inside body tag <br>");
</script>
<hr>
<p><input type='button' name="myb" value="click for dynamically calling document.write()" onClick="disp()";><br></p>
</form></body></html>


Cookies

  • Cookies are small programs/code written on the client computer to enable us to recognize that it is the same computer to which we got connected before.
  • A cookie can be maximum of 4 Kb.
  • A web browser will retain at max 20 cookies.
  • The cookies life is only till the browser is “on”, but if we set time for the cookie when we create it, we can hold it longer.
  • All the cookies information is stored in “window.document.cookie” object.
  • Cookies contain variable and value pairs of information.
  • A variable added as “expires” containing a date object as value will set the expiration date for the cookie.  The date object should contain time in GMT only.  We can use Date.toGMTString() method to do so.

 

Ex.Setting a cookie
<html><head><title>Setting Cookies</title>
<script language="javascript">
//the date to be stored in the cokie
var user_account = "Mike McGrath, 000456";

//create a new Date object
var expiry = new Date();

//set the expiry for 7 days time
expiry.setTime( expiry.getTime()+(7*24*60*60*1000));

//create the cookie
document.cookie = "cookiedata="+escape(user_account)+";" + "expires="+expiry.toGMTString()+";";
</script></head><body></body></html>

  • Getting Cookie Information:  JS can detect the presence of cookie by using the “document.cookie” object.  This object will return “true” if there is a cookie else it will return “false”.  document.cookie object will return the string containing as cookie.

 

Ex. Getting cookie info
<html><head><title>Getting cookie information</title></head><body>
<script language="javascript">
//find any cookies
if(document.cookie){
//unescape the cookei data first for use
var cookiedata = unescape(document.cookie);

//split the name & value pairs
var userdata=cookiedata.split("=");

//if the cookie is called cokiedata
if(userdata[0] == "cookiedata"){
//split the comma delimited values
var data = userdata[1].split(",");
var username = data[0];
var useracct = data[1];
}
}
// write out the data retrieved from te cookie
document.write("Welcome " + username+ "<br/>");
document.write("Accont number: " + useracct +".");

</script></body></html>


Images array

  • The window.document.images[] array object contains all the images in the current browser.
  • images[].id property of the images object will return the “id” of that particular image.
  • Images[].src property of the images object will return the “source” of the image.

Ex.      document.write(document.images.length);
document.write(document.images[1].id);
document.write(document.images[1].src);

  • images may also be addressed as “document.images.myimg”, where “myimg” is the name of the image in <img src> tag.

 

Ex. Rollover Images
<html><head><title>Roll over images</title>
<script language="javascript">

function swap(a){
if(a==1) document.images.myimg1.src = 'blue hills.jpg';
if(a==0) document.images.myimg1.src = 'flowers.jpg';
}

</script></head><body>
<img id="myimg1" src="flowers.jpg" width="400" height="300" onMouseOver="swap(1)" onMouseOut="swap(0)"/>
</body></html>

 

Ex.Image details demo
<html><head><title>Roll over images</title>
<script language="javascript">

function imginfo(){
var len = document.images.length;
var msg=" ";
alert ("total Images are : " +len);
for(i=0; i<len; i++){
alert("ID of image "+(i+1)+" is : "+document.images[i].id);
alert("Source of image "+(i+1)+" is : "+document.images[i].src);
}
}

</script></head><body>
<img id="myimg1" src="flowers.jpg" width="200" height="150"/>
<img id="myimg2" src="blue hills.jpg" width="200" height="150"/>
<img id="myimg3" src="one.JPG" width="200" height="150"/>
<p><input type="button" value="Get details of images" onClick="imginfo()"></p>
</body></html>


“last Modified” object:
  • document.lastModified object will contain the information about when the current file been modified last. 
  • This information is supplied by the server.  If the server passes this information it will carry the value or else it will have “0”(zero).
  • The date object can be parsed with the help of “parse()” function available directly with the Date class.

 

Ex. Getting modified date
<html><head><title>Modified details</title></head><body>
<script language="javascript">
if(Date.parse(document.lastModified) != 0){
document.write("page last updated : " + document.lastModified);       
}
</script></body></html>


LAYERS

  • Layers are very useful in creating dynamic effects in Java Script.
  • The advantage of layers is that you can place any text, images etc in a layer and that layer can be positioned anywhere in the browser by mentioning the left and top values for the layers.
  • The distance between the leftmost corner of the browser to the left side of layer is known as X-index or simply left space.
  • The distance between the topmost corner of the browser to the top side of the layer is called as Y-index or simple the top space.
  • One layer can be placed on another layer and so on.
  • The layers are numbered according to the occurrence from the bottom and this is called as the Z-index.
  • The layer Z-Index will have the numbers starting from 0 and every layer placed on the bottom of window will be incremented.ie., 0, 1, 2, 3…..
  • The values for x and y indexes are given in pixels.  That means if x-index is 0(zero) the layer will start from the left most corner of the browser.  And if y-index is 0(zero) the layer will start from the top most corner of the browser.
  • In Java Script we can create layers dynamically by writing the necessary HTML codes in the document.write() method.

 

Ex.Creating layers dynamically
<html><head><title>Modified details</title></head><body>
<script language="javascript">
document.write("<div id='layer1' style='position:absolute; top:20px; left:20px; width:400px;  height:300px; background-color:purple; color:white; z-index:10; border:1px solid black'><h1> Layer # 1</h1></div>");

document.write("<div id='layer1' style='position:absolute; top:100px; left:60px; width:400px;  height:300px; background-color:yellow; color:black; z-index:20; border:1px solid black'><h1> Layer # 2</h1></div>");

</script></body></html>


Transparent layers:

  • Unless specified otherwise, layer will usually be created with the same background as the document body. So it will appear to be transparent.
  • It can explicitly set to transparent by giving “background-color” property to “transparent”.
  • Transparent property is important especially when creating irregular image sizes.

Form Object

  • All the forms in a browser can be displayed as an array with window.document.forms object.  Ex. window.document.forms[0] refers to the first form appearing the document.
  • If the id is given in the <form> tag in html then it can be addressed as document.forms.f. (f is the id for the form).
  • All the properties of the form object can be displayed.

 

Ex.     document.forms.f.method;
document.forms.f.action;
document.forms.f.encoding;

  • All the elements of the forms are given in an array which can be addresed as “window.document.forms[].elements” object.

 

Ex. document.forms.f.elements[0] displays the first element of the form.

  • The elements can also be addressed using the names if used.

 

Ex. document.forms.f.bt1 where bt1 is the name assigned in the html tag of button.

 

Ex. display of form elements
<HTML><HEAD><TITLE>display of form elements</TITLE>
<script language="javascript">
function disp(){
var max = document.forms.f.elements.length;
var i=0;
while(i<max){
document.forms.f.elements[i].Style = "color:'red';font-size:'34pt';";
alert("Type   of Element "+(i+1)+" is : " +document.forms.f.elements[i].type+ "\n Name of Element "+(i+1)+" is : "+document.forms.f.elements[i++].name);

}
}

</script></HEAD><BODY>
<H2 ALIGN=CENTER><U>APPLICATION FORM FOR ADMISSION INTO APTECH FOR MODULE-01 PROGRAM</u></H2>
<BR/></BR>
<form name="f">
1.NAME &nbsp &nbsp &nbsp &nbsp
<input type="text" name="Name" maxlength="20"> <br/><BR/>
2.ADDRESS &nbsp <input type="text" name="Address" maxlength="25"><BR/><BR/>
3.SEX <INPUT TYPE="RADIO" NAME="Gender" VALUE=MALE>MALE
<INPUT TYPE="RADIO" NAME="Gender" VALUE="FEMALE">FEMALE<BR/><BR/>
4.EDUCATION <SELECT NAME="Education">
<OPTION>SLC</OPTION>
<OPTION>DIploma</OPTION>
<OPTION>Under Graduate</OPTION>
<OPTION>Graduate</OPTION>
<OPTION>Post Graduate</OPTION>
<OPTION>Ph D</OPTION>
</select>
<br/><br/>
5.Comments <Textarea name="mytext" cols=35 rows=7> </textarea>
<hr noshare size=4>
<h1> display all the elements of the form</h1>
<input type="button" name="disp button" value="display all the elements" onClick="disp()">
</form></BODY></html>


Dynamically changing the values of attributes of html code/form elements.

  • Dynamically we can change the attributes of HTML tags inside the page.
  • Once the html file is loaded, we can access any component with its name or id and change the value or attribute value of the component. In the below example the functions are changed dynamically.

 

Ex. dynamically changing attributes
<HTML><HEAD><TITLE>display of form elements</TITLE>
<script language="javascript">
var c=0;
function fun1(){
alert("This is a call from fun1");
}

function fun2(){
alert("this is a call from fun2, you have called "+c+ " times ");
c++;
}

function fun3(){
alert("this is from fun3 function");
}

function chan(){
if( c > 0) document.forms.f.b1.onclick=fun3;
else document.forms.f.b1.onclick=fun2;
}

</script></HEAD><body>
<form name="f">
<input type="button" id="b1" value="click" onClick="fun1()">
<input type="button" id="b2" value="change" onClick="chan()">
</form></body><html>


Controlling components dynamically

 

Buttons:
A single button can do two functions and display two labels on it based on the requirement.

 

Ex.dynamic button
<html><head><title>dynamic buttons</title>
<script language="javascript">
//creating global variables
var running=false, num = -1, tim;

//counter function
function count(){
if(running){
num++;
window.status = 'seconds elapsed :'+num;
tim=setTimeout("count()", 1000);
}
else {
num=-1;
clearTimeout(tim);
}
}
function stopgo(){
running = !running;
count();
document.forms.f.btn1.value = (running)? "Stop Counter" : "Start Counter";
}

</script></head><body>
<h2> see the same button works for start and stop & watch status bar</h2>
<hr/>
<form name="f">
<input type="button" name="btn1" value="Start Counter" onclick="stopgo()"/>
</form></body></html>


Dynamic Text Box
The value for text box were simple previously, but now even css can be applied to the text and other components.
NOTE: while giving the values for CSS which contain two words, the second word shall start with a capital letter.
Ex.           font-family will be fontFamily in JS.
font-size  will be fontSize in JS.

 

Ex. dynamic text box
<html><head><title>dynamic text</title>
<script language="javascript">
function set_text(){
with(document.forms.f.txt1){
value="JavaScript";

//setting style
style.fontFamily ="Comic sans ms";
style.fontSize="16pt";
style.color="lime";
style.backgroundColor="black";
}
}
</script></head><body>
<form name="f">
Text : <input type="text" name="txt1" />
<p><input type="button" name="myb" value="change text" onclick="set_text()"/>
</form></body></html>


Validating Password
Password box generally will display only asterisks.  The value should be accepted only after comparing the password and allow the user to enter the first page of the site or else alert him with appropriate message.

 

Ex. Password validation
<html><head><title>Password validation</title>
<script language="javascript">
function validate(){
//conver the input to lower case
var entry = document.forms.f.pwd1.value.toLowerCase();

//relocate the broser if the input is correct
if(entry == "admin") window.location = "bgcolor.html";
else{
alert("Password incorrect - Please retry ...");
document.forms.f.pdw1.value = "";
}

}
</script></head><body>
<form name="f" method="post">
Text : <input type="password" name="pwd1" />
<p><input type="button" name="myb" value="Enter Site" onClick="validate()"/>
</form></body></html>


Radio Buttons

  • Generally the radio buttons will have same name so that they can be grouped with one name.
  • Only one radio button can be selected at a time.
  • All the grouped buttons containing the same name will be held according to DOM in document.form object with the “name” as variable and indexes giving the buttons individually.

Ex. document.forms.f.myradio[0], document.forms.f.myradio[1] etc.

  • document.forms.f.myradio[0].value will give the value contained in the html tag of radio button ex. <input type=”radio” name=”myradio” value=”male”>
  • The “checked” property of the radio element will return true or false.  If the user has checked then this property will be true else it will be false.
  • we can use the “for” loop and see whether the user has selected the button by using this property. Ex. if(document.forms.f.myradio[0].checked);
  • This procedure of checking the values of radio button are known as polling.

 

Ex.Radio button polling.
<html><head><title>Password validation</title>
<script language="javascript">
function polling(){
for(var i=0; i<document.forms.f.rad1.length;i++){
if(document.forms.f.rad1[i].checked)
document.bgColor=document.forms.f.rad1[i].value;
}
}
</script></head><body>
<form name="f" method="post">
<h2>Select the background color</h2>
<input name="rad1" type="radio" value="red" onClick="polling()"/> Red
<input name="rad1" type="radio" value="green" onClick="polling()"/>Green
<input name="rad1" type="radio" value="blue" onClick="polling()"/>Blue
<input name="rad1" type="radio" value="gray" onClick="polling()"/>Gray
<input name="rad1" type="radio" value="teal" onClick="polling()"/>Teal
</form></body></html>


Checkbox

  • Check box have different names for different checkbox component unlike radio buttons.
  • User can have multiple checkboxes selected.
  • The programmer can know whether the check box has been clicked or not with the “checked” property.

Ex. if(document.forms.f.chk1.checked)

  • We can set the value of “checked” property by our self, if we want to make it a default checked item.

Ex. document.forms.f.chk1.checked=true;

  • We can also extract the value of the checkbox with the checkbox object.

Ex. var str = document.forms.f.chk1.value


Select component

  • The select component has an array called options[].
  • This options[] array has two properties “text” and “value”.
  • “Text” will have the text which is displayed in the select options.
  • “value” will contain the value attribute (if mentioned) in the options of select.
  • It also has a “selectedIndex” value ranging from 0, 1, 2, …..
  • We can set the “value” property for the options of the select component.

Ex. document.forms.f.menu.options[0].value=”1”;

  • We can also set the “text” property for the options of the select component.

Ex.document.forms.f.menu.options[2].text=”Three”;

 

Ex.Select options demo
<html><head><title>select options demo</title>
</head>
<script language="javascript">
function getdets(){
var pick = document.forms.f.city.selectedIndex;
document.forms.f.txt1.value=document.forms.f.city.options[pick].text;
document.forms.f.txt2.value=document.forms.f.city.options[pick].value;
}
</script>
<body>
<form name="f">
<h1 align=center>Select the option and display the option values</h1>
<select name="city">
<option value="opt1">LONDON</option>
<option value="opt2">NEW YORK</option>
<option value="opt3">PARIS</option>
<option value="opt4">SYDNEY</option>
<option value="opt5">DETROIT</option>
<option value="opt6">WASHINGTON</option>
</select>
<input type="button" value="Show Selected Values" onClick="getdets()" />
<p>Select Option Text  :        
<input type="text" name="txt1" value=" " />
<p>Select Option Value: 
<input type="text" name="txt2" value=" " />
<hr/>
</form>
</body></html>


Text Areas

  • The text value can be read and written to text area component using JS dynamically.

 

Ex. Dynamic Text area
<html><head><title>dynamic text area</title>
</head>
<script language="javascript">
function writeText(){
document.forms.f.txtarea.value = "Computer in the future may perhaps only wigh 1.5 tons. (Popular Mechanics forecasting the development of computer technology, 1949)";
}
</script>
<body onLoad="writeText()">
<form name="f">

<textarea name='txtarea' rows='4' cols='14'>
document.write("this is smy  a;lth;weht ias;dlknojan[oirgoiearng[na[un[]aeoringoianeineraoivn[oiaernvoianvoinri")
ocument.write
</textarea>
<script language="javascript">
//writeText();
</script></form></body></html>

SIGN UP FOR NEWSLETTER

Sign up to received our free newsletter!
Name:
E-mail ID:

MOST READ

Views: 7159 Times
Circle Hover Effects with CSS3 Transitions READ MORE
Views: 2958 Times
Google launches monthly user-activity feature READ MORE
Views: 2753 Times
Facebook to file motion, discuss Nasdaq role in IPO: report READ MORE
Views: 5405 Times
How to add Hotmail and Live Email Accounts to Outlook 2010? READ MORE
Views: 7403 Times
Learn HTML - Lesson 2 READ MORE

Home|IT News|Computer Tips|Video Tutorials|Download Softwares|Subjects|Contact Us
Copyright © 2018. Jumbo Education (Information Technology). All rights reserved.
Free counter and web stats

Large Visitor Globe