SlideShare une entreprise Scribd logo
1  sur  45
How to Handle Simple Browsers ::
-----------------------------------------
Browsers that do not support JavaScript, will display JavaScript as page content.

To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should
be used to "hide" the JavaScript.

Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment)
after the last JavaScript statement, like this:
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>

The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents
JavaScript from executing the --> tag.

JavaScript Where To
================

JavaScripts in the body section will be executed WHILE the page loads.

JavaScripts in the head section will be executed when CALLED.
Where to Put the JavaScript

JavaScripts in a page will be executed immediately while the page loads into the browser. This is not
always what we want. Sometimes we want to execute a script when a page loads, other times when a
user triggers an event.
Scripts in <head>

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

If you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event"); //It is used to show the Messagebox with content
}
</script>
</head>

<body onload="message()">
</body>
</html>


Scripts in <body>
===============
Scripts to be executed when the page loads go in the body section.

If you place a script in the body section, it generates the content of a page.
Example
<html>
<head>
</head>

<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>

</html>


Scripts in <head> and <body>
=======================
You can place an unlimited number of scripts in your document, so you can have scripts in both the body
and the head section.
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<script type="text/javascript">
....
</script>
</body>

Using an External JavaScript
===================
If you want to run the same JavaScript on several pages, without having to write the same script on every
page, you can write a JavaScript in an external file.

Save the external JavaScript file with a .js file extension.

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

To use the external script, point to the .js file in the "src" attribute of the <script> tag:
Example
<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>
Note: Remember to place the script exactly where you normally would write the script!

****
The semicolon is optional (according to the JavaScript standard), and the browser is supposed to
interpret the end of the line as the end of the statement. Because of this you will often see examples
without the semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.

JavaScript Blocks
============
JavaScript statements can be grouped together in blocks.

Blocks start with a left curly bracket {, and ends with a right curly bracket }.

The purpose of a block is to make the sequence of statements execute together.

This example will write a heading and two paragraphs to a web page:
Example
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>

Declaring (Creating) JavaScript Variables
============================
Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:
var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold the
value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.
Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be
declared.

These statements:
x=5;
carname="Volvo";

have the same effect as:
var x=5;
var carname="Volvo";

Redeclaring JavaScript Variables
=======================
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;

After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.
JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;

The + Operator Used on Strings
=======================
The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains "What a verynice day".

To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

"What a very nice day"
Example :-
<html>
<body>

<script type="text/javascript">
x=5+5;
document.write(x);
document.write("<br />");
x="5"+"5";
document.write(x);
document.write("<br />");
x=5+"5";
document.write(x);
document.write("<br />");
x="5"+5;
document.write(x);
document.write("<br />");
</script>

<p>The rule is: If you add a number and a string, the result will be a string.</p>
</body>
</html>

Output :-
10
55
55
55

The rule is: If you add a number and a string, the result will be a string.


JavaScript Comparison and Logical Operators
===============================

Comparison and Logical operators are used to test for true or false.
Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between
variables or values.

Given that x=5, the table below explains the comparison operators:
Operator          Description                    Example
==           is equal to                        x==8 is false
===     is exactly equal to (value and type)       x===5 is true
x==="5"                                       is false
!=      is not equal                            x!=8 is true
>       is greater than                         x>8 is false
<       is less than                            x<8 is true
>=      is greater than or equal to               x>=8 is false
<=      is less than or equal to                 x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action
depending on the result:
if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:
Operator        Description      Example
&&      and     (x < 10 && y > 1) is true
||      or      (x==5 || y==5) is false
!       not     !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear "; //No Space

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear
President " else it will be assigned "Dear".

JavaScript If...Else Statements
========================

    * if statement - use this statement to execute some code only if a specified condition is true
    * if...else statement - use this statement to execute some code if the condition is true and another code
if the condition is false
    * if...else if....else statement - use this statement to select one of many blocks of code to be executed
    * switch statement - use this statement to select one of many blocks of code to be executed

Example :
if and if else ::
if (condition)
  {
  code to be executed if condition is true
  }
else
  {
  code to be executed if condition is not true
  }

if else if ::
if (condition1)
  {
  code to be executed if condition1 is true
  }
else if (condition2)
  {
  code to be executed if condition2 is true
  }
else
  {
  code to be executed if condition1 and condition2 are not true
  }

Swich Case ::
switch (favoritemovie){
case "Titanic":
alert("Not a bad choice!")
break;
case "Water World":
alert("No comment")
break;
case "Scream 2":
alert("It has its moments")
break;
default : alert("I'm sure it was great");
}
JavaScript Popup Boxes

Alert Box
======================
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box

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

When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");

Example
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>

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

</body>
</html>

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

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

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
confirm("sometext");

Example
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
  {
  document.write("You pressed OK!");
  }
else
  {
  document.write("You pressed Cancel!");
  }
}
</script>
</head>
<body>

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

</body>
</html>

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

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

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
prompt("sometext","defaultvalue");

Example
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  {
  document.write("Hello " + name + "! How are you today?");
  }
}
</script>
</head>
<body>

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

</body>
</html>


Function :::
===============
word function is in lower case
with no parameter
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

Function with return Type :

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>

<body>
<script type="text/javascript">
document.write(product(4,3));
</script>

</body>
</html>

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

While Loop
========

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

Do-While Lop
============
<html>
<body>
<script type="text/javascript">
var i=0;
do
 {
 document.write("The number is " + i);
 document.write("<br />");
 i++;
 }
while (i<=5);
</script>
</body>


The break Statement
====================

The break statement will break the loop and continue executing the code that follows after the loop (if
any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
 {
 if (i==3)
   {
   break;
   }
 document.write("The number is " + i);
 document.write("<br />");
 }
</script>
</body>
</html>


The continue Statement
=======================

The continue statement will break the current loop and continue with the next value.
Example
<html>
<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>

JavaScript For...In Statement(For each Loop)
=====================
The for...in statement loops through the elements of an array or through the properties of an object.
Syntax
for (variable in object)
 {
 code to be executed
 }

Note: The code in the body of the for...in loop is executed once for each element/property.

Note: The variable argument can be a named variable, an array element, or a property of an object.
Example

Use the for...in statement to loop through an array:
Example
<html>
<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(mycars[x] + "<br />");
 }
</script>

</body>
</html>


Events (http://www.w3schools.com/jsref/jsref_events.asp) All events with discription
=======================
By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be
detected by JavaScript.

Every element on a web page has certain events which can trigger a JavaScript. For example, we can
use the onClick event of a button element to indicate that a function will run when a user clicks on the
button. We define the events in the HTML tags.
Examples of events:

  * A mouse click
  * A web page or an image loading
  * Mousing over a hot spot on the web page
  * Selecting an input field in an HTML form
  * Submitting an HTML form
  * A keystroke

Note: Events are normally used in combination with functions, and the function will not be executed
before the event occurs!

For a complete reference of the events recognized by JavaScript, go to our complete Event reference.
onLoad and onUnload

The onLoad and onUnload events are triggered when the user enters or leaves the page.

The onLoad event is often used to check the visitor's browser type and browser version, and load the
proper version of the web page based on the information.

Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a
user enters or leaves a page. For example, you could have a popup asking for the user's name upon his
first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page,
you could have another popup saying something like: "Welcome John Doe!".
onFocus, onBlur and onChange

The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

Below is an example of how to use the onChange event. The checkEmail() function will be called
whenever the user changes the content of the field:
<input type="text" size="30" id="email" onchange="checkEmail()">

onSubmit

The onSubmit event is used to validate ALL form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will be called when the
user clicks the submit button in the form. If the field values are not accepted, the submit should be
cancelled. The function checkForm() returns either true or false. If it returns true the form will be
submitted, otherwise the submit will be cancelled:
<form method="post" action="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut

onMouseOver and onMouseOut are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is
detected:
<a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img
src="w3s.gif" alt="W3Schools" /></a>



JavaScript - Catching Errors(Try.............catch Statement)
===============================
When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a
runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers
but not for users. When users see errors, they often leave the Web page.

This chapter will teach you how to catch and handle JavaScript error messages, so you don't lose your
audience.
The try...catch Statement

The try...catch statement allows you to test a block of code for errors. The try block contains the code to
be run, and the catch block contains the code to be executed if an error occurs.
Syntax
try
  {
  //Run some code here
  }
catch(err)
  {
  //Handle errors here
  }

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript
error!
Example 1

The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a
typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch
block catches the error and executes a custom code to handle it. The code displays a custom error
message informing the user what happened:
Example
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.nn";
  txt+="Error description: " + err.description + "nn";
  txt+="Click OK to continue.nn";
  alert(txt);
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

The next example uses a confirm box to display a custom message telling users they can click OK to
continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the
user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does
nothing:

Example
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.nn";
  txt+="Click OK to continue viewing this page,n";
  txt+="or Cancel to return to the home page.nn";
  if(!confirm(txt))
    {
    document.location.href="http://www.w3schools.com/";
    }
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

JavaScript Special Characters
===========================

In JavaScript you can add special characters to a text string by using the backslash sign.
Insert Special Characters

The backslash () is used to insert apostrophes, new lines, quotes, and other special characters into a text
string.

Look at the following JavaScript code:
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);

In JavaScript, a string is started and stopped with either single or double quotes. This means that the
string above will be chopped to: We are the so-called

To solve this problem, you must place a backslash () before each double quote in "Viking". This
turns each double quote into a string literal:
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.

Here is another example:
document.write ("You & I are singing!");

The example above will produce the following output:
You & I are singing!

The table below lists other special characters that can be added to a text string with the backslash sign:
Code Outputs
'      single quote
"      double quote
&      ampersand
      backslash
n      new line
r      carriage return
t      tab
b      backspace
f      form feed



JavaScript Guidelines
============================

Some other important things to know when scripting with JavaScript.
JavaScript is Case Sensitive

A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the
same as "myvar".

JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables,
objects and functions.
White Space

JavaScript ignores extra spaces. You can add white space to your script to make it more readable.
The following lines are equivalent:
name="Hege";
name = "Hege";

Break up a Code Line

You can break up a code line within a text string with a backslash. The example below will be displayed
properly:
document.write("Hello 
World!");

However, you cannot break up a code line like this:
document.write 
("Hello World!");


JavaScript Objects Introduction
=============================
JavaScript Objects Introduction
previous next

JavaScript is an Object Oriented Programming (OOP) language.

An OOP language allows you to define your own objects and make your own variable types.
Object Oriented Programming

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define
your own objects and make your own variable types.

Properties

Properties are the values associated with an object.

In the following example we are using the length property of the String object to return the number of
characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>

The output of the code above will be:
12


JavaScript Objects Introduction


JavaScript is an Object Oriented Programming (OOP) language.

An OOP language allows you to define your own objects and make your own variable types.
Object Oriented Programming

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define
your own objects and make your own variable types.

However, creating your own objects will be explained later, in the Advanced JavaScript section. We will
start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each
built-in JavaScript object in detail.

Note that an object is just a special kind of data. An object has properties and methods.

Properties
==================
Properties are the values associated with an object.

In the following example we are using the length property of the String object to return the number of
characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>

The output of the code above will be:
12
Methods
================
Methods are the actions that can be performed on objects.

In the following example we are using the toUpperCase() method of the String object to display a text in
uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>

The output of the code above will be:
HELLO WORLD!


String Functions :
=================

<html>
<body>

<script type="text/javascript">

var txt="Hello World!";

document.write("<p>Big: " + txt.big() + "</p>");                                  O/p Big: Hello World!
document.write("<p>Small: " + txt.small() + "</p>");                              O/p :Small: Hello
World!

document.write("<p>Bold: " + txt.bold() + "</p>");                                   O/p :Bold: Hello
World!
document.write("<p>Italic: " + txt.italics() + "</p>");                              O/p :Italic: Hello
World!

document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>");          O/p :Blink: Hello
World! (does not work in IE) //here Hello World will continue blink !
document.write("<p>Fixed: " + txt.fixed() + "</p>");                              O/p: Fixed: Hello World!
document.write("<p>Strike: " + txt.strike() + "</p>");                             O/P:Strike: Hello
World!

document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>");                   O/P:Fontsize: Hello
World!
document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>");                       Lowercase: hello
world!

document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>");                      Uppercase: HELLO
WORLD!
document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>");

document.write("<p>Subscript: " + txt.sub() + "</p>");                             Subscript: Hello World!
// O/p is not shown in wordpad properly

document.write("<p>Superscript: " + txt.sup() + "</p>");                          Superscript: Hello
World! //O/p is not shown in wordpad properly
document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>");                  Link: Hello World
//Now it becomes link now
</script>

</body>
</html>


<html>
<body>


String always starts from zero(0)

index function
=============
<script type="text/javascript">
var str="Hello world!";
document.write(str.indexOf("Hello") + "<br />");                          O/p : 1
document.write(str.indexOf("World") + "<br />");                          O/p : -1(because "W" not found its is
"w")
document.write(str.indexOf("world"));                                     O/p : 6
</script>

</body>
</html>

match function
=========
It will return string/string portion whereever it will be found .........return null if not match
<html>
<body>

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

</body>
</html>

Replace Function
===============
it will replace string
it is necessary to pass the Forward slash in the starting and in the end of string that is need to
replace


<html>
<body>

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

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


Definition and usage
=========================

The constructor property is a reference to the function that created the object.::::::::::::::::
Syntax
object.constructor

Example

In this example we will show how to use the constructor property:
<script type="text/javascript">

var test=new String();
if (test.constructor==Array)
{
document.write("This is an Array");
}
if (test.constructor==Boolean)
{
document.write("This is a Boolean");
}
if (test.constructor==Date)
{
document.write("This is a Date");
}
if (test.constructor==String)
{
document.write("This is a String");
}

</script>

The output of the code above will be:
This is a String


The prototype property allows you to add properties and methods to an object. ::::::::::::::
Syntax
object.prototype.name=value

Example

In this example we will show how to use the prototype property to add a property to an object:
<script type="text/javascript">

function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}

var fred=new employee("Fred Flintstone","Caveman",1970): /// employee is not the class while even
we can creates its object and assign the values to its property and create too.
employee.prototype.salary=null; /// created new property
fred.salary=20000;

document.write(fred.salary);

</script>

The output of the code above will be:
20000


The anchor() method is used to create an HTML anchor. ::::::::::::::::::::::::
Syntax
stringObject.anchor(anchorname)

Parameter        Description
anchorname       Required. Defines a name for the anchor

Example

In this example we will add an anchor to a text:
<script type="text/javascript">

var txt="Hello world!";
document.write(txt.anchor("myanchor"));

</script>

The code above could be written in plain HTML, like this:
<a name="myanchor">Hello world!</a>


The charAt() method returns the character at a specified position::::::::::::::::::::::::::::::::::
Syntax
stringObject.charAt(index)

Parameter    Description
index Required. A number representing a position in the string

Tips and Notes

Note: The first character in the string is at position 0.
Example

In the string "Hello world!", we will return the character at position 1:
<script type="text/javascript">

var str="Hello world!";
document.write(str.charAt(1));
</script>

The output of the code above will be:
e


The charCodeAt() method returns the Unicode of the character at a specified position::::::::::::::::::::::
Syntax
stringObject.charCodeAt(index)

Parameter    Description
index Required. A number representing a position in the string

Tips and Notes

Note: The first character in the string is at position 0.
Example

In the string "Hello world!", we will return the Unicode of the character at position 1:
<script type="text/javascript">

var str="Hello world!";
document.write(str.charCodeAt(1));

</script>

The output of the code above will be:
101

The concat() method is used to join two or more strings.::::::::::::::::::::::::
Syntax
stringObject.concat(stringX,stringX,...,stringX)

Parameter      Description
stringX Required. One or more string objects to be joined to a string

Example

In the following example we will create two strings and show them as one using concat():
<script type="text/javascript">

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

</script>

The output of the code above will be:
Hello world!

The fromCharCode() takes the specified Unicode values and returns a string.:::::::::::::::::::
Syntax
String.fromCharCode(numX,numX,...,numX)

Parameter   Description
numX Required. One or more Unicode values
Tips and Notes

Note: This method is a static method of String - it is not used as a method of a String object that
you have created. The syntax is always String.fromCharCode() and not
myStringObject.fromCharCode().
Example

In this example we will write "HELLO" and "ABC" from Unicode:
<script type="text/javascript">

document.write(String.fromCharCode(72,69,76,76,79));
document.write("<br />");
document.write(String.fromCharCode(65,66,67));

</script>

The output of the code above will be:
HELLO
ABC


The lastIndexOf() method returns the position of the last occurrence of a specified string value,
searching backwards from the specified position in a string.::::::
Syntax
stringObject.lastIndexOf(searchvalue,fromindex)

Parameter     Description
search Required. Specifies a string value to search for
fromindex     Optional. Specifies where to start the search. Starting backwards in the string

Tips and Notes

Note: The lastIndexOf() method is case sensitive!

Note: This method returns -1 if the string value to search for never occurs.
Example

In this example we will do different searches within a "Hello world!" string:
<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>

The output of the code above will be:
0
-1
6


The search() method is used to search a string for a specified value.::::::::::::::::
This method supports regular expressions. You can learn about the RegExp object in our JavaScript
tutorial.
Syntax
stringObject.search(searchstring)

Parameter        Description
searchstring     Required. The value to search for in a string. To perform a case-insensitive search add
an 'i' flag

Tips and Notes

Note: search() is case sensitive.

Note: The search() method returns the position of the specified value in the string. If no match was found
it returns -1.
Example 1 - Standard Search

In the following example we will search for the word "W3Schools":
<script type="text/javascript">

var str="Visit W3Schools!";
document.write(str.search(/W3Schools/));

</script>

The output of the code above will be:
6

Note: In the following example the word "w3schools" will not be found (because the search()
method is case sensitive):
<script type="text/javascript">

var str="Visit W3Schools!";
document.write(str.search(/w3schools/));

</script>

The output of the code above will be:
-1


The slice() method extracts a part of a string and returns the extracted part in a new
string.::::::::::::::::::

Syntax
stringObject.slice(start,end) /// It is based on position not on length unlike substring(based on
length see below)

Parameter    Description
start Required. Specify where to start the selection. Must be a number. Starts at 0
end   Optional. Specify where to end the selection. Must be a number

Tips and Notes

Tip: You can use negative index numbers to select from the end of the string.
Note: If end is not specified, slice() selects all characters from the specified start position and to the end of
the string.
Example 1

In this example we will extract all characters from a string, starting at position 0:
<script type="text/javascript">

var str="Hello happy world!";
document.write(str.slice(0));

</script>

The output of the code above will be:
Hello happy world!

Example 2

In this example we will extract all characters from a string, starting at position 6:
<script type="text/javascript">

var str="Hello happy world!";
document.write(str.slice(6));

</script>

The output of the code above will be:
happy world!

Example 3

In this example we will extract only the first character from a string:
<script type="text/javascript">

var str="Hello happy world!";
document.write(str.slice(0,1));

</script>

The output of the code above will be:
H


The split() method is used to split a string into an array of strings.::::::::::::;;
Syntax
stringObject.split(separator, howmany)

Parameter      Description
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

Tips and Notes

Note: If an empty string ("") is used as the separator, the string is split between each character.
Example
In this example we will split up a string in different ways:
<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>

The output of the code above will be:
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


The substr() method extracts a specified number of characters in a string, from a start
index.:::::::::::
Syntax
stringObject.substr(start,length)

Parameter     Description
start  Required. Where to start the extraction. Must be a numeric value
length Optional. How many characters to extract. Must be a numeric value.

Tips and Notes

Note: To extract characters from the end of the string, use a negative start number (This does not work in
IE).

Note: The start index starts at 0.

Note: If the length parameter is omitted, this method extracts to the end of the string.
Example 1

In this example we will use substr() to extract some characters from a string:
<script type="text/javascript">

var str="Hello world!";
document.write(str.substr(3));

</script>

The output of the code above will be:
lo world!

Example 2

In this example we will use substr() to extract some characters from a string:
<script type="text/javascript">

var str="Hello world!";
document.write(str.substr(3,7)); // Start from 3 and count 7 characters from there

</script>
The output of the code above will be:
lo worl


Java Script Regular Expression :
==========================
JavaScript global Property ::::

JavaScript global Property
RegExp Object Reference Complete RegExp Object Reference
Definition and Usage

The global property is used to return whether or not the "g" modifier is used in the regular expression.

The "g" modifier is set if the regular expression should be tested against all possible matches in the string.

This property is "TRUE" if the "g" modifier is set, "FALSE" otherwise.
Syntax
RegExpObject.global

<html>
<body>

<script type="text/javascript">
var str = "Visit W3Schools";
var patt1 = new RegExp("s","g");

if(patt1.global)
  {
  document.write("Global property is set");
  }
else
  {
  document.write("Global property is NOT set.");
  }
</script>

</body>
</html>
o/p Global property is set

JavaScript ignoreCase Property

JavaScript ignoreCase Property
RegExp Object Reference Complete RegExp Object Reference
Definition and Usage

The ignoreCase property is used to return whether or not the "i" modifier is used in the regular
expression.

The "i" modifier is set if the regular expression should ignore the case of characters.

This property is "TRUE" if the "i" modifier is set, "FALSE" otherwise.
Syntax
RegExpObject.ignoreCase
<html>
<body>

<script type="text/javascript">
var str = "Visit W3Schools";
var patt1 = new RegExp("S","i");

if(patt1.ignoreCase)
  {
  document.write("ignoreCase property is set");
  }
else
  {
  document.write("ignoreCase property is NOT set.");
  }
</script>

</body>
</html>
o/p=ignoreCase property is set

JavaScript input Property

The input property is the string the pattern match is performed.
<html>
<body>

<script type="text/javascript">
function getRegInput()
{
var patt1 = new RegExp("W3");
var str = document.frm1.txtinput.value;
patt1.test(str);     ///????

if(RegExp.input)
  {
  alert("The input is: " + RegExp.input);
  }
else
  {
  alert("The input does not contain W3");
  }
}
</script>

<form name="frm1">
Enter some text and click outside:
<input type="text" name="txtinput" onChange='getRegInput()' /><br />
Input will only show if text contains W3.
</form>

</body>
</html>
JavaScript lastIndex Property
The lastIndex property specifies the index (placement) in the string where to start the next match.

The index is a number specifying the placement of the first character after the last match.

This property only works if the "g" modifier is set.
Syntax
RegExpObject.lastIndex

<html>
<body>

<script type="text/javascript">
var str = "The rain in Spain stays mainly in the plain";
var patt1 = new RegExp("ain", "g");
for(i = 0; i < 4; i++)
 {
 patt1.test(str);
 document.write("ain found. index now at: " + patt1.lastIndex);
 document.write("<br />");
 }
</script>

</body>
</html>

Output :
ain found. index now at: 8
ain found. index now at: 17
ain found. index now at: 28
ain found. index now at: 43


JavaScript lastMatch Property

The lastMatch property is the last matched characters.
Syntax
RegExp.lastMatch

<html>
<body>

<script type="text/javascript">
var str = "The rain in Spain stays mainly in the plain";
var patt1 = new RegExp("ain", "g");
for(i = 0; i < 4; i++)
  {
  patt1.test(str);
  document.write(RegExp.lastMatch);
 // document.write(" found. index now at: " + patt1.lastIndex);
  document.write("<br />");
  }
</script>

</body>
</html>
o/p
ain
ain
ain
ain

JavaScript leftContext Property(Nice)

The leftContext property is the substring in front of the characters most recently matched.

This property contains everything from the string from before the match.
Syntax
RegExp.leftContext


<html>
<body>

<script type="text/javascript">
var str = "The rain in Spain stays mainly in the plain";
var patt1 = new RegExp("ain", "g");
for(i = 0; i < 4; i++)
 {
 patt1.test(str)
 document.write(RegExp.lastMatch);
 document.write(" found. Text before match: " + RegExp.leftContext);
 document.write("<br />");
 }
</script>

</body>
</html>

o/p :
ain found. Text before match: The r
ain found. Text before match: The rain in Sp
ain found. Text before match: The rain in Spain stays m
ain found. Text before match: The rain in Spain stays mainly in the pl




JavaScript multiline Property

The multiline property is used to return whether or not the "m" modifier is used in the regular expression.

The "m" modifier is set if the regular expression should be tested against possible matches over multiple
lines.

This property is "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Syntax
RegExpObject.multiline
<html>
<body>
<script type="text/javascript">
var str = "Visit W3Schools";
var patt1 = new RegExp("s","m");

if(patt1.multiline)
  {
  document.write("Multiline property is set");      o/p multiline property is set
  }
else
  {
  document.write("Multiline property is NOT set.");
  }
</script>

</body>
</html>

JavaScript rightContext Property
The rightContext property is the substring from after the characters most recently matched.

This property contains everything from the string from after the match.
Syntax
RegExp.rightContext

<html>
<body>

<script type="text/javascript">
var str = "The rain in Spain stays mainly in the plain";
var patt1 = new RegExp("ain", "g");

for(i = 0; i < 4; i++)
 {
 patt1.test(str);
 document.write(RegExp.lastMatch);
 document.write(" found. Text after match: " + RegExp.rightContext);
 document.write("<br />");
 }
</script>

</body>
</html>

ain found. Text after match: in Spain stays mainly in the plain
ain found. Text after match: stays mainly in the plain
ain found. Text after match: ly in the plain
ain found. Text after match:

JavaScript source Property

The source property is used to return the text used for pattern matching.

The returned text is everything except the forward slashes and any flags.
Syntax
RegExpObject.source
<html>
<body>

<script type="text/javascript">
var str = "Visit W3Schools";
var patt1 = new RegExp("W3S","g");

document.write("The regular expression is: " + patt1.source);
</script>

</body>
</html>
o/p::The regular expression is: W3S


JavaScript compile() Method


The compile() method is used to change the regular expression.
Syntax
RegExpObject.compile(regexp)

Parameter     Description
regexp Required. The new regular expression to search for

Example

In the following example we change the pattern from "Microsoft" to "W3Schools", and then test if we find
the specified pattern in a string:
<script type="text/javascript">
var str="Visit W3Schools";
var patt=new RegExp("Microsoft");

document.write("Test if we find " + patt + " in " + str + ": ")

if (patt.test(str)==true)
  {
  document.write("Match found!")
  }
else
  {
  document.write("Match not found")
  }

patt.compile("W3Schools");

document.write("<br />")
document.write("Test if we find " + patt + " in " + str + ": ")

if (patt.test(str)==true)
  {
  document.write("Match found!")
  }
else
  {
  document.write("Match not found")
  }
</script>

The output of the code above will be:
Test if we find /Microsoft/ in Visit W3Schools: Match not found
Test if we find /W3Schools/ in Visit W3Schools: Match found!



JavaScript exec() Method


The exec() method searches a string for a specified value.

This method returns the matched text if a match is found, and null if not.
Syntax
RegExpObject.exec(string)

Parameter     Description
RegExpObject Required. The regular expression to use
string Required. The string to search

Example

In the following example we will search for "W3Schools" in a string:
<script type="text/javascript">

var str="Visit W3Schools";
var patt=new RegExp("W3Schools");

document.write(patt.exec(str));

</script>

The output of the code above will be:
W3Schools


JavaScript test() Method
The test() method searches a string for a specified value.

This method returns true if a match is found, and false if not.
Syntax
RegExpObject.test(string)

Parameter     Description
RegExpObject Required. The regular expression to use
string Required. The string to search

Example

In the following example we change the pattern from "Microsoft" to "W3Schools", and then test if we find
the specified pattern in a string:
<script type="text/javascript">

var str="Visit W3Schools";
var patt=new RegExp("Microsoft");
document.write("Test if we find " + patt + " in " + str + ": ")

if (patt.test(str)==true)
  {
  document.write("Match found!")
  }
else
  {
  document.write("Match not found")
  }

patt.compile("W3Schools");

document.write("<br />")
document.write("Test if we find " + patt + " in " + str + ": ")

if (patt.test(str)==true)
  {
  document.write("Match found!")
  }
else
  {
  document.write("Match not found")
  }

</script>

The output of the code above will be:
Test if we find /Microsoft/ in Visit W3Schools: Match not found
Test if we find /W3Schools/ in Visit W3Schools: Match found!


JavaScript isFinite() Function

The isFinite() function is used to check if a value is a finite number.
Syntax
isFinite(number)

Parameter        Description
number           Required. The value to be tested

Example

In this example we use isFinite() to check for finite numbers:
<script type="text/javascript">

document.write(isFinite(123)+ "<br />");
document.write(isFinite(-1.23)+ "<br />");
document.write(isFinite(5-2)+ "<br />");
document.write(isFinite(0)+ "<br />");
document.write(isFinite("Hello")+ "<br />");
document.write(isFinite("2005/12/12")+ "<br />");

</script>
The output of the code above will be:
true
true
true
true
false
false


JavaScript Number() Function

The Number() function converts the value of an object to a number.
Syntax
Number(object)

Parameter     Description
object Required. A JavaScript object

Tips and Notes

Note: If the parameter is a Date object, the Number() function returns the number of milliseconds
since midnight January 1, 1970 UTC.

Note: If the object's value cannot be converted to a number, the Number() function returns NaN.
Example

In this example we will try to convert different objects to numbers:
<script type="text/javascript">

var test1= new Boolean(true);
var test2= new Boolean(false);
var test3= new Date();
var test4= new String("999");
var test5= new String("999 888");

document.write(Number(test1)+ "<br />");
document.write(Number(test2)+ "<br />");
document.write(Number(test3)+ "<br />");
document.write(Number(test4)+ "<br />");
document.write(Number(test5)+ "<br />");

</script>

The output of the code above will be:
1
0
1247394276301
999
NaN


JavaScript isNaN() Function


The isNaN() function is used to check if a value is not a number.
Syntax
isNaN(number)

Parameter        Description
number           Required. The value to be tested

Example

In this example we use isNaN() to check some values:
<script type="text/javascript">

document.write(isNaN(123)+ "<br />");
document.write(isNaN(-1.23)+ "<br />");
document.write(isNaN(5-2)+ "<br />");
document.write(isNaN(0)+ "<br />");
document.write(isNaN("Hello")+ "<br />");
document.write(isNaN("2005/12/12")+ "<br />");

</script>

The output of the code above will be:
false
false
false
false
true
true


JavaScript escape() Function


The escape() function encodes a string, so it can be read on all computers.
Syntax
escape(string)

Parameter     Description
string Required. The string to be encoded

Tips and Notes

Note: The escape() function encodes special characters, with the exception of:
*@-_+./

Tip: Use the unescape() function to decode strings encoded with escape().

Note: The escape() and unescape() functions should not be used to encode or decode URIs. Use
encodeURI() and decodeURI() functions instead!
Example

In this example we use escape() to encode strings:
<script type="text/javascript">

document.write(escape("Visit W3Schools!") + "<br />");
document.write(escape("?!=()#%&"));

</script>
The output of the code above will be:
Visit%20W3Schools%21
%3F%21%3D%28%29%23%25%26



JavaScript unescape() Function

The unescape() function decodes a string encoded with escape().
Syntax
unescape(string)

Parameter     Description
string Required. The string to be decoded

Tips and Notes

Note: The escape() and unescape() functions should not be used to encode or decode URIs. Use
encodeURI() and decodeURI() functions instead!
Example

In this example we first encode the strings with the escape() function, and then decode them with the
unescape() function:
<script type="text/javascript">

var test1="Visit W3Schools!";

test1=escape(test1);
document.write (test1 + "<br />");

test1=unescape(test1);
document.write(test1 + "<br />");

</script>

The output of the code above will be:
Visit%20W3Schools%21
Visit W3Schools!


JavaScript eval() Function // Its important to make the code more smaller.......nice one


The eval() function evaluates a string and executes it as if it was script code.
Syntax
eval(string)

Parameter     Description
string Required. The string to be evaluated

Example

In this example we use eval() on some strings and see what it returns:
<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)");
document.write("<br />");

document.write(eval("2+2"));
document.write("<br />");

var x=10;
document.write(eval(x+17));
document.write("<br />");

</script>

The output of the code above will be:
200
4
27


JavaScript String() Function

The String() function converts the value of an object to a string.
Syntax
String(object)

Parameter     Description
object Required. A JavaScript object

Tips and Notes

Note: The String() function returns the same value as toString() of the individual objects.
Example

In this example we will try to convert different objects to strings:
<script type="text/javascript">

var test1= new Boolean(1);
var test2= new Boolean(0);
var test3= new Boolean(true);
var test4= new Boolean(false);
var test5= new Date();
var test6= new String("999 888");
var test7=12345;

document.write(String(test1)+ "<br />");
document.write(String(test2)+ "<br />");
document.write(String(test3)+ "<br />");
document.write(String(test4)+ "<br />");
document.write(String(test5)+ "<br />");
document.write(String(test6)+ "<br />");
document.write(String(test7)+ "<br />");

</script>

The output of the code above will be:
true
false
true
false
Sun Jul 12 2009 15:55:47 GMT+0530 (India Standard Time)
999 888
12345

Examples for Events ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

JavaScript onclick Event

<html>
<body>

Field1: <input type="text" id="field1" value="Hello World!">
<br />
Field2: <input type="text" id="field2">
<br /><br />
Click the button below to copy the content of Field1 to Field2.
<br />
<button onclick="document.getElementById('field2').value=
document.getElementById('field1').value">Copy Text</button>

</body>
</html>

onfocus event
<html>
<head>
<script type="text/javascript">
function setStyle(x)
{
document.getElementById(x).style.background="yellow";
}
</script>
</head>
<body>

First name: <input type="text"
onfocus="setStyle(this.id)" id="fname">
<br />
Last name: <input type="text"
onfocus="setStyle(this.id)" id="lname">

</body>
</html>

onkeydown Event

Browser differences: Internet Explorer uses event.keyCode to retrieve the character that was
pressed and Netscape/Firefox/Opera uses event.which.

<html>
<body>
<script type="text/javascript">
function noNumbers(e)
{
var keynum;
var keychar;
var numcheck;

if(window.event) // IE
         {
         keynum = e.keyCode;
         }
else if(e.which) // Netscape/Firefox/Opera
         {
         keynum = e.which;
         }
keychar = String.fromCharCode(keynum);
numcheck = /d/;
return !numcheck.test(keychar);
}
</script>

<form>
Type some text (numbers not allowed):
<input type="text" onkeydown="return noNumbers(event)" />
</form>

</body>
</html>


Date and Time Section ::::
<html>
<body>

<script type="text/javascript">

document.write(Date());

</script>

</body>
</html>

o/p Sun Jul 12 2009 16:16:31 GMT+0530 (India Standard Time)


<html>
<body>

<script type="text/javascript">
var minutes = 1000*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var d = new Date();
var t = d.getTime();
var y = t/years;
document.write("It's been: " + y + " years since 1970/01/01!");
</script>
</body>
</html>

O.p It's been: 39.554654748414514 years since 1970/01/01!


<html>
<body>

<script type="text/javascript">

var d = new Date();
d.setFullYear(1992,10,3);
document.write(d);

</script>

</body>
</html>

O/p :Tue Nov 03 1992 16:16:32 GMT+0530 (India Standard Time)

<html>
<body>

<script type="text/javascript">

var d = new Date();
document.write (d.toUTCString());

</script>

</body>
</html>

Sun, 12 Jul 2009 10:46:34 GMT


<html>
<body>

<script type="text/javascript">

var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.write("Today it is " + weekday[d.getDay()]); // getDay function will return the number
</script>

</body>
</html>

Today is Sunday

Clock

<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}
</script>
</head>

<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

return current time 16:39:02


Mathematical Function :
Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are also
several methods available.

The following example uses the round() method of the Math object to round a number to the nearest
integer:
document.write(Math.round(4.7));

The code above will result in the following output:
5
Random method


The following example uses the random() method of the Math object to return a random number between
0 and 1:
document.write(Math.random());

The code above can result in the following output:
0.6388059778069849

The following example uses the floor() and random() methods of the Math object to return a random
number between 0 and 10:
document.write(Math.floor(Math.random()*11));

The code above can result in the following output:
4


<html>
<body>

<script type="text/javascript">

document.write(Math.random());

</script>

</body>
</html>

<html>
<body>

<script type="text/javascript">

document.write(Math.round(0.60) + "<br />");
document.write(Math.round(0.50) + "<br />");
document.write(Math.round(0.49) + "<br />");
document.write(Math.round(-4.40) + "<br />");
document.write(Math.round(-4.60));

</script>

</body>
</html>

The innerHTML property sets or returns the text of a link.
It will redirect u to the microsoft site
<html>
<head>
<script type="text/javascript">
function changeLink()
{
document.getElementById('myAnchor').innerHTML="Visit W3Schools";
document.getElementById('myAnchor').href="http://www.w3schools.com";
document.getElementById('myAnchor').target="_blank";
}
</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
<p>In this example we change the text and the URL of a hyperlink. We also change the target attribute.
The target attribute is by default set to "_self", which means that the link will open in the same window.
By setting the target attribute to "_blank", the link will open in a new window.</p>
</body>

</html>

Regular Expression(RegExp)

What is RegExp

RegExp, is short for regular expression.

When you search in a text, you can use a pattern to describe what you are searching for. RegExp IS this
pattern.
A simple pattern can be a single character.

A more complicated pattern consists of more characters, and can be used for parsing, format checking,
substitution and more.

You can specify where in the string to search, what type of characters to search for, and more.
Defining RegExp

The RegExp object is used to store the search pattern.

We define a RegExp object with the new keyword. The following code line defines a RegExp object called
patt1 with the pattern "e":
var patt1=new RegExp("e");

When you use this RegExp object to search in a string, you will find the letter "e".
Methods of the RegExp Object

The RegExp Object has 3 methods: test(), exec(), and compile().
test()

The test() method searches a string for a specified value. Returns true or false
Example
var patt1=new RegExp("e");

document.write(patt1.test("The best things in life are free"));

Since there is an "e" in the string, the output of the code above will be:
true



Navigator Object
Properties                    Description
----------------------------------------------------------------------------------------------------
appCodeName The code name of the browser.
appName                       The name of the browser (ie: Microsoft Internet Explorer).
appVersion                   Version information for the browser (ie: 4.75 [en] (Win98; U)).
appMinorVersion             The minor version number of the browser.
cookieEnabled                Boolean that indicates whether the browser has cookies enabled. cpuClass
                   The type of CPU which may be "x86"
language                     Returns the default language of the browser version (ie: en-US). NS
                             and Firefox only.
mimeTypes[]                  An array of all MIME types supported by the client. NS and Firefox
                             only.
platform[]                   The platform of the client's computer (ie: Win32).
plugins            An array of all plug-ins currently installed on the client. NS and
          Firefox only.
systemLanguage               Returns the default language of the operating system (ie: en-us). IE
                             only.
userAgent                    String passed by browser as user-agent header. (ie: Mozilla/4.0
                   (compatible; MSIE 6.0; Windows NT 5.1))
userLanguage                 Returns the preferred language setting of the user (ie: en-ca). IE only.
 mimeTypes                   An array of MIME type descriptive strings that are supported by the
                             browser.
 onLine                      A boolean value of true or false.



Image Map Example
<html>
<head>
<script type="text/javascript">
function writeText(txt)
{
document.getElementById("desc").innerHTML=txt;
}
</script>
</head>

<body>
<img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" />

<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onMouseOver="writeText('The Sun and the gas giant planets like Jupiter are by far the largest
objects in our Solar System.')"
href ="sun.htm" target ="_blank" alt="Sun" />

<area shape ="circle" coords ="90,58,3"
onMouseOver="writeText('The planet Mercury is very difficult to study from the Earth because
it is always so close to the Sun.')"
href ="mercur.htm" target ="_blank" alt="Mercury" />
<area shape ="circle" coords ="124,58,8"
onMouseOver="writeText('Until the 1960s, Venus was often considered a twin sister to the
Earth because Venus is the nearest planet to us, and because the two planets seem to share
many characteristics.')"
href ="venus.htm" target ="_blank" alt="Venus" />
</map>

<h4 id="desc"></h4>

</body>
</html>


Timing Object
<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</script>
</head>

<body>
<form>
<input type="button" value="Display timed alertbox!" onClick = "timedMsg()">
</form>
<p>Click on the button above. An alert box will be displayed after 5 seconds.</p>
</body>

</html>

Contenu connexe

Tendances (20)

Java Script An Introduction By HWA
Java Script An Introduction By HWAJava Script An Introduction By HWA
Java Script An Introduction By HWA
 
Java script
Java scriptJava script
Java script
 
Java Script
Java ScriptJava Script
Java Script
 
Java script
Java scriptJava script
Java script
 
Javascript
JavascriptJavascript
Javascript
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
Java script
Java scriptJava script
Java script
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Java script
Java scriptJava script
Java script
 
Java script
Java scriptJava script
Java script
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Web programming
Web programmingWeb programming
Web programming
 
Java Script
Java ScriptJava Script
Java Script
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Java scipt
Java sciptJava scipt
Java scipt
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Java script
Java scriptJava script
Java script
 

En vedette (6)

Variables
VariablesVariables
Variables
 
Shore
ShoreShore
Shore
 
Presentation
PresentationPresentation
Presentation
 
Performing calculations using java script
Performing calculations using java scriptPerforming calculations using java script
Performing calculations using java script
 
Spintronics
SpintronicsSpintronics
Spintronics
 
Groovy scripts with Groovy
Groovy scripts with GroovyGroovy scripts with Groovy
Groovy scripts with Groovy
 

Similaire à Java scripts

Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptArti Parab Academics
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.pptBArulmozhi
 
Javascript conditional statements 1
Javascript conditional statements 1Javascript conditional statements 1
Javascript conditional statements 1Jesus Obenita Jr.
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]srikanthbkm
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdfHASENSEID
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statementsnobel mujuji
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4SURBHI SAROHA
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript poojanov04
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scriptingpkaviya
 

Similaire à Java scripts (20)

Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Janakiram web
Janakiram webJanakiram web
Janakiram web
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
 
UNIT 3.ppt
UNIT 3.pptUNIT 3.ppt
UNIT 3.ppt
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
 
Javascript conditional statements 1
Javascript conditional statements 1Javascript conditional statements 1
Javascript conditional statements 1
 
Javascript
JavascriptJavascript
Javascript
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
 
Java script
Java scriptJava script
Java script
 
FSJavaScript.ppt
FSJavaScript.pptFSJavaScript.ppt
FSJavaScript.ppt
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statements
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 

Dernier

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Dernier (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Java scripts

  • 1. How to Handle Simple Browsers :: ----------------------------------------- Browsers that do not support JavaScript, will display JavaScript as page content. To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript. Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this: <html> <body> <script type="text/javascript"> <!-- document.write("Hello World!"); //--> </script> </body> </html> The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag. JavaScript Where To ================ JavaScripts in the body section will be executed WHILE the page loads. JavaScripts in the head section will be executed when CALLED. Where to Put the JavaScript JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Scripts in <head> Scripts to be executed when they are called, or when an event is triggered, go in the head section. If you place a script in the head section, you will ensure that the script is loaded before anyone uses it. Example <html> <head> <script type="text/javascript"> function message() { alert("This alert box was called with the onload event"); //It is used to show the Messagebox with content } </script> </head> <body onload="message()"> </body> </html> Scripts in <body>
  • 2. =============== Scripts to be executed when the page loads go in the body section. If you place a script in the body section, it generates the content of a page. Example <html> <head> </head> <body> <script type="text/javascript"> document.write("This message is written by JavaScript"); </script> </body> </html> Scripts in <head> and <body> ======================= You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section. <html> <head> <script type="text/javascript"> .... </script> </head> <body> <script type="text/javascript"> .... </script> </body> Using an External JavaScript =================== If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. Note: The external script cannot contain the <script> tag! To use the external script, point to the .js file in the "src" attribute of the <script> tag: Example <html> <head> <script type="text/javascript" src="xxx.js"></script> </head> <body> </body> </html> Note: Remember to place the script exactly where you normally would write the script! **** The semicolon is optional (according to the JavaScript standard), and the browser is supposed to
  • 3. interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end. Note: Using semicolons makes it possible to write multiple statements on one line. JavaScript Blocks ============ JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket {, and ends with a right curly bracket }. The purpose of a block is to make the sequence of statements execute together. This example will write a heading and two paragraphs to a web page: Example <script type="text/javascript"> { document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); } </script> Declaring (Creating) JavaScript Variables ============================ Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var statement: var x; var carname; After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them: var x=5; var carname="Volvo"; After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo. Note: When you assign a text value to a variable, use quotes around the value. Assigning Values to Undeclared JavaScript Variables If you assign values to variables that have not yet been declared, the variables will automatically be declared. These statements: x=5; carname="Volvo"; have the same effect as: var x=5; var carname="Volvo"; Redeclaring JavaScript Variables =======================
  • 4. If you redeclare a JavaScript variable, it will not lose its original value. var x=5; var x; After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it. JavaScript Arithmetic As with algebra, you can do arithmetic operations with JavaScript variables: y=x-5; z=y+5; The + Operator Used on Strings ======================= The + operator can also be used to add string variables or text values together. To add two or more string variables together, use the + operator. txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; After the execution of the statements above, the variable txt3 contains "What a verynice day". To add a space between the two strings, insert a space into one of the strings: txt1="What a very "; txt2="nice day"; txt3=txt1+txt2; or insert a space into the expression: txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; After the execution of the statements above, the variable txt3 contains: "What a very nice day" Example :- <html> <body> <script type="text/javascript"> x=5+5; document.write(x); document.write("<br />"); x="5"+"5"; document.write(x); document.write("<br />"); x=5+"5"; document.write(x); document.write("<br />"); x="5"+5; document.write(x); document.write("<br />"); </script> <p>The rule is: If you add a number and a string, the result will be a string.</p>
  • 5. </body> </html> Output :- 10 55 55 55 The rule is: If you add a number and a string, the result will be a string. JavaScript Comparison and Logical Operators =============================== Comparison and Logical operators are used to test for true or false. Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true x==="5" is false != is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true How Can it be Used Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document.write("Too young"); You will learn more about the use of conditional statements in the next chapter of this tutorial. Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2
  • 6. Example greeting=(visitor=="PRES")?"Dear President ":"Dear "; //No Space If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear President " else it will be assigned "Dear". JavaScript If...Else Statements ======================== * if statement - use this statement to execute some code only if a specified condition is true * if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false * if...else if....else statement - use this statement to select one of many blocks of code to be executed * switch statement - use this statement to select one of many blocks of code to be executed Example : if and if else :: if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } if else if :: if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true } Swich Case :: switch (favoritemovie){ case "Titanic": alert("Not a bad choice!") break; case "Water World": alert("No comment") break; case "Scream 2": alert("It has its moments") break; default : alert("I'm sure it was great"); }
  • 7. JavaScript Popup Boxes Alert Box ====================== JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box. Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax alert("sometext"); Example <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } </script> </head> <body> <input type="button" onclick="show_alert()" value="Show alert box" /> </body> </html> Confirm Box ========================= A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax confirm("sometext"); Example <html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Press a button"); if (r==true) { document.write("You pressed OK!"); } else { document.write("You pressed Cancel!"); }
  • 8. } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" /> </body> </html> Prompt Box =========================== A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax prompt("sometext","defaultvalue"); Example <html> <head> <script type="text/javascript"> function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body> <input type="button" onclick="show_prompt()" value="Show prompt box" /> </body> </html> Function ::: =============== word function is in lower case with no parameter <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head>
  • 9. <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" /> </form> </body> </html> Function with return Type : <html> <head> <script type="text/javascript"> function product(a,b) { return a*b; } </script> </head> <body> <script type="text/javascript"> document.write(product(4,3)); </script> </body> </html> The for Loop ========= <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> While Loop ======== <html> <body> <script type="text/javascript"> var i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; }
  • 10. </script> </body> </html> Do-While Lop ============ <html> <body> <script type="text/javascript"> var i=0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i<=5); </script> </body> The break Statement ==================== The break statement will break the loop and continue executing the code that follows after the loop (if any). Example <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> The continue Statement ======================= The continue statement will break the current loop and continue with the next value. Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) {
  • 11. if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> JavaScript For...In Statement(For each Loop) ===================== The for...in statement loops through the elements of an array or through the properties of an object. Syntax for (variable in object) { code to be executed } Note: The code in the body of the for...in loop is executed once for each element/property. Note: The variable argument can be a named variable, an array element, or a property of an object. Example Use the for...in statement to loop through an array: Example <html> <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(mycars[x] + "<br />"); } </script> </body> </html> Events (http://www.w3schools.com/jsref/jsref_events.asp) All events with discription ======================= By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.
  • 12. Examples of events: * A mouse click * A web page or an image loading * Mousing over a hot spot on the web page * Selecting an input field in an HTML form * Submitting an HTML form * A keystroke Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! For a complete reference of the events recognized by JavaScript, go to our complete Event reference. onLoad and onUnload The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()"> onSubmit The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.htm" onsubmit="return checkForm()"> onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a> JavaScript - Catching Errors(Try.............catch Statement) =============================== When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a
  • 13. runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page. This chapter will teach you how to catch and handle JavaScript error messages, so you don't lose your audience. The try...catch Statement The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax try { //Run some code here } catch(err) { //Handle errors here } Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error! Example 1 The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened: Example <html> <head> <script type="text/javascript"> var txt="" function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.nn"; txt+="Error description: " + err.description + "nn"; txt+="Click OK to continue.nn"; alert(txt); } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> The next example uses a confirm box to display a custom message telling users they can click OK to
  • 14. continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing: Example <html> <head> <script type="text/javascript"> var txt="" function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.nn"; txt+="Click OK to continue viewing this page,n"; txt+="or Cancel to return to the home page.nn"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> JavaScript Special Characters =========================== In JavaScript you can add special characters to a text string by using the backslash sign. Insert Special Characters The backslash () is used to insert apostrophes, new lines, quotes, and other special characters into a text string. Look at the following JavaScript code: var txt="We are the so-called "Vikings" from the north."; document.write(txt); In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called To solve this problem, you must place a backslash () before each double quote in "Viking". This turns each double quote into a string literal: var txt="We are the so-called "Vikings" from the north."; document.write(txt);
  • 15. JavaScript will now output the proper text string: We are the so-called "Vikings" from the north. Here is another example: document.write ("You & I are singing!"); The example above will produce the following output: You & I are singing! The table below lists other special characters that can be added to a text string with the backslash sign: Code Outputs ' single quote " double quote & ampersand backslash n new line r carriage return t tab b backspace f form feed JavaScript Guidelines ============================ Some other important things to know when scripting with JavaScript. JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar". JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables, objects and functions. White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: name="Hege"; name = "Hege"; Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello World!"); However, you cannot break up a code line like this: document.write ("Hello World!"); JavaScript Objects Introduction =============================
  • 16. JavaScript Objects Introduction previous next JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. Object Oriented Programming JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. Properties Properties are the values associated with an object. In the following example we are using the length property of the String object to return the number of characters in a string: <script type="text/javascript"> var txt="Hello World!"; document.write(txt.length); </script> The output of the code above will be: 12 JavaScript Objects Introduction JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. Object Oriented Programming JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail. Note that an object is just a special kind of data. An object has properties and methods. Properties ================== Properties are the values associated with an object. In the following example we are using the length property of the String object to return the number of characters in a string: <script type="text/javascript"> var txt="Hello World!"; document.write(txt.length); </script> The output of the code above will be: 12
  • 17. Methods ================ Methods are the actions that can be performed on objects. In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: <script type="text/javascript"> var str="Hello world!"; document.write(str.toUpperCase()); </script> The output of the code above will be: HELLO WORLD! String Functions : ================= <html> <body> <script type="text/javascript"> var txt="Hello World!"; document.write("<p>Big: " + txt.big() + "</p>"); O/p Big: Hello World! document.write("<p>Small: " + txt.small() + "</p>"); O/p :Small: Hello World! document.write("<p>Bold: " + txt.bold() + "</p>"); O/p :Bold: Hello World! document.write("<p>Italic: " + txt.italics() + "</p>"); O/p :Italic: Hello World! document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>"); O/p :Blink: Hello World! (does not work in IE) //here Hello World will continue blink ! document.write("<p>Fixed: " + txt.fixed() + "</p>"); O/p: Fixed: Hello World! document.write("<p>Strike: " + txt.strike() + "</p>"); O/P:Strike: Hello World! document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>"); O/P:Fontsize: Hello World! document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>"); Lowercase: hello world! document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>"); Uppercase: HELLO WORLD! document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>"); document.write("<p>Subscript: " + txt.sub() + "</p>"); Subscript: Hello World! // O/p is not shown in wordpad properly document.write("<p>Superscript: " + txt.sup() + "</p>"); Superscript: Hello World! //O/p is not shown in wordpad properly
  • 18. document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>"); Link: Hello World //Now it becomes link now </script> </body> </html> <html> <body> String always starts from zero(0) index function ============= <script type="text/javascript"> var str="Hello world!"; document.write(str.indexOf("Hello") + "<br />"); O/p : 1 document.write(str.indexOf("World") + "<br />"); O/p : -1(because "W" not found its is "w") document.write(str.indexOf("world")); O/p : 6 </script> </body> </html> match function ========= It will return string/string portion whereever it will be found .........return null if not match <html> <body> <script type="text/javascript"> var str="Hello world!"; document.write(str.match("world") + "<br />"); world document.write(str.match("World") + "<br />"); null document.write(str.match("worlld") + "<br />"); null document.write(str.match("world!")); world! </script> </body> </html> Replace Function =============== it will replace string it is necessary to pass the Forward slash in the starting and in the end of string that is need to replace <html> <body> <script type="text/javascript">
  • 19. var str="Visit Microsoft!"; document.write(str.replace(/Microsoft/,"W3Schools")); Visit W3Schools! </script> </body> </html> Definition and usage ========================= The constructor property is a reference to the function that created the object.:::::::::::::::: Syntax object.constructor Example In this example we will show how to use the constructor property: <script type="text/javascript"> var test=new String(); if (test.constructor==Array) { document.write("This is an Array"); } if (test.constructor==Boolean) { document.write("This is a Boolean"); } if (test.constructor==Date) { document.write("This is a Date"); } if (test.constructor==String) { document.write("This is a String"); } </script> The output of the code above will be: This is a String The prototype property allows you to add properties and methods to an object. :::::::::::::: Syntax object.prototype.name=value Example In this example we will show how to use the prototype property to add a property to an object: <script type="text/javascript"> function employee(name,jobtitle,born) { this.name=name;
  • 20. this.jobtitle=jobtitle; this.born=born; } var fred=new employee("Fred Flintstone","Caveman",1970): /// employee is not the class while even we can creates its object and assign the values to its property and create too. employee.prototype.salary=null; /// created new property fred.salary=20000; document.write(fred.salary); </script> The output of the code above will be: 20000 The anchor() method is used to create an HTML anchor. :::::::::::::::::::::::: Syntax stringObject.anchor(anchorname) Parameter Description anchorname Required. Defines a name for the anchor Example In this example we will add an anchor to a text: <script type="text/javascript"> var txt="Hello world!"; document.write(txt.anchor("myanchor")); </script> The code above could be written in plain HTML, like this: <a name="myanchor">Hello world!</a> The charAt() method returns the character at a specified position:::::::::::::::::::::::::::::::::: Syntax stringObject.charAt(index) Parameter Description index Required. A number representing a position in the string Tips and Notes Note: The first character in the string is at position 0. Example In the string "Hello world!", we will return the character at position 1: <script type="text/javascript"> var str="Hello world!"; document.write(str.charAt(1));
  • 21. </script> The output of the code above will be: e The charCodeAt() method returns the Unicode of the character at a specified position:::::::::::::::::::::: Syntax stringObject.charCodeAt(index) Parameter Description index Required. A number representing a position in the string Tips and Notes Note: The first character in the string is at position 0. Example In the string "Hello world!", we will return the Unicode of the character at position 1: <script type="text/javascript"> var str="Hello world!"; document.write(str.charCodeAt(1)); </script> The output of the code above will be: 101 The concat() method is used to join two or more strings.:::::::::::::::::::::::: Syntax stringObject.concat(stringX,stringX,...,stringX) Parameter Description stringX Required. One or more string objects to be joined to a string Example In the following example we will create two strings and show them as one using concat(): <script type="text/javascript"> var str1="Hello "; var str2="world!"; document.write(str1.concat(str2)); </script> The output of the code above will be: Hello world! The fromCharCode() takes the specified Unicode values and returns a string.::::::::::::::::::: Syntax String.fromCharCode(numX,numX,...,numX) Parameter Description numX Required. One or more Unicode values
  • 22. Tips and Notes Note: This method is a static method of String - it is not used as a method of a String object that you have created. The syntax is always String.fromCharCode() and not myStringObject.fromCharCode(). Example In this example we will write "HELLO" and "ABC" from Unicode: <script type="text/javascript"> document.write(String.fromCharCode(72,69,76,76,79)); document.write("<br />"); document.write(String.fromCharCode(65,66,67)); </script> The output of the code above will be: HELLO ABC The lastIndexOf() method returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string.:::::: Syntax stringObject.lastIndexOf(searchvalue,fromindex) Parameter Description search Required. Specifies a string value to search for fromindex Optional. Specifies where to start the search. Starting backwards in the string Tips and Notes Note: The lastIndexOf() method is case sensitive! Note: This method returns -1 if the string value to search for never occurs. Example In this example we will do different searches within a "Hello world!" string: <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> The output of the code above will be: 0 -1 6 The search() method is used to search a string for a specified value.::::::::::::::::
  • 23. This method supports regular expressions. You can learn about the RegExp object in our JavaScript tutorial. Syntax stringObject.search(searchstring) Parameter Description searchstring Required. The value to search for in a string. To perform a case-insensitive search add an 'i' flag Tips and Notes Note: search() is case sensitive. Note: The search() method returns the position of the specified value in the string. If no match was found it returns -1. Example 1 - Standard Search In the following example we will search for the word "W3Schools": <script type="text/javascript"> var str="Visit W3Schools!"; document.write(str.search(/W3Schools/)); </script> The output of the code above will be: 6 Note: In the following example the word "w3schools" will not be found (because the search() method is case sensitive): <script type="text/javascript"> var str="Visit W3Schools!"; document.write(str.search(/w3schools/)); </script> The output of the code above will be: -1 The slice() method extracts a part of a string and returns the extracted part in a new string.:::::::::::::::::: Syntax stringObject.slice(start,end) /// It is based on position not on length unlike substring(based on length see below) Parameter Description start Required. Specify where to start the selection. Must be a number. Starts at 0 end Optional. Specify where to end the selection. Must be a number Tips and Notes Tip: You can use negative index numbers to select from the end of the string.
  • 24. Note: If end is not specified, slice() selects all characters from the specified start position and to the end of the string. Example 1 In this example we will extract all characters from a string, starting at position 0: <script type="text/javascript"> var str="Hello happy world!"; document.write(str.slice(0)); </script> The output of the code above will be: Hello happy world! Example 2 In this example we will extract all characters from a string, starting at position 6: <script type="text/javascript"> var str="Hello happy world!"; document.write(str.slice(6)); </script> The output of the code above will be: happy world! Example 3 In this example we will extract only the first character from a string: <script type="text/javascript"> var str="Hello happy world!"; document.write(str.slice(0,1)); </script> The output of the code above will be: H The split() method is used to split a string into an array of strings.::::::::::::;; Syntax stringObject.split(separator, howmany) Parameter Description 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 Tips and Notes Note: If an empty string ("") is used as the separator, the string is split between each character. Example
  • 25. In this example we will split up a string in different ways: <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> The output of the code above will be: 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 The substr() method extracts a specified number of characters in a string, from a start index.::::::::::: Syntax stringObject.substr(start,length) Parameter Description start Required. Where to start the extraction. Must be a numeric value length Optional. How many characters to extract. Must be a numeric value. Tips and Notes Note: To extract characters from the end of the string, use a negative start number (This does not work in IE). Note: The start index starts at 0. Note: If the length parameter is omitted, this method extracts to the end of the string. Example 1 In this example we will use substr() to extract some characters from a string: <script type="text/javascript"> var str="Hello world!"; document.write(str.substr(3)); </script> The output of the code above will be: lo world! Example 2 In this example we will use substr() to extract some characters from a string: <script type="text/javascript"> var str="Hello world!"; document.write(str.substr(3,7)); // Start from 3 and count 7 characters from there </script>
  • 26. The output of the code above will be: lo worl Java Script Regular Expression : ========================== JavaScript global Property :::: JavaScript global Property RegExp Object Reference Complete RegExp Object Reference Definition and Usage The global property is used to return whether or not the "g" modifier is used in the regular expression. The "g" modifier is set if the regular expression should be tested against all possible matches in the string. This property is "TRUE" if the "g" modifier is set, "FALSE" otherwise. Syntax RegExpObject.global <html> <body> <script type="text/javascript"> var str = "Visit W3Schools"; var patt1 = new RegExp("s","g"); if(patt1.global) { document.write("Global property is set"); } else { document.write("Global property is NOT set."); } </script> </body> </html> o/p Global property is set JavaScript ignoreCase Property JavaScript ignoreCase Property RegExp Object Reference Complete RegExp Object Reference Definition and Usage The ignoreCase property is used to return whether or not the "i" modifier is used in the regular expression. The "i" modifier is set if the regular expression should ignore the case of characters. This property is "TRUE" if the "i" modifier is set, "FALSE" otherwise. Syntax RegExpObject.ignoreCase
  • 27. <html> <body> <script type="text/javascript"> var str = "Visit W3Schools"; var patt1 = new RegExp("S","i"); if(patt1.ignoreCase) { document.write("ignoreCase property is set"); } else { document.write("ignoreCase property is NOT set."); } </script> </body> </html> o/p=ignoreCase property is set JavaScript input Property The input property is the string the pattern match is performed. <html> <body> <script type="text/javascript"> function getRegInput() { var patt1 = new RegExp("W3"); var str = document.frm1.txtinput.value; patt1.test(str); ///???? if(RegExp.input) { alert("The input is: " + RegExp.input); } else { alert("The input does not contain W3"); } } </script> <form name="frm1"> Enter some text and click outside: <input type="text" name="txtinput" onChange='getRegInput()' /><br /> Input will only show if text contains W3. </form> </body> </html>
  • 28. JavaScript lastIndex Property The lastIndex property specifies the index (placement) in the string where to start the next match. The index is a number specifying the placement of the first character after the last match. This property only works if the "g" modifier is set. Syntax RegExpObject.lastIndex <html> <body> <script type="text/javascript"> var str = "The rain in Spain stays mainly in the plain"; var patt1 = new RegExp("ain", "g"); for(i = 0; i < 4; i++) { patt1.test(str); document.write("ain found. index now at: " + patt1.lastIndex); document.write("<br />"); } </script> </body> </html> Output : ain found. index now at: 8 ain found. index now at: 17 ain found. index now at: 28 ain found. index now at: 43 JavaScript lastMatch Property The lastMatch property is the last matched characters. Syntax RegExp.lastMatch <html> <body> <script type="text/javascript"> var str = "The rain in Spain stays mainly in the plain"; var patt1 = new RegExp("ain", "g"); for(i = 0; i < 4; i++) { patt1.test(str); document.write(RegExp.lastMatch); // document.write(" found. index now at: " + patt1.lastIndex); document.write("<br />"); } </script> </body> </html>
  • 29. o/p ain ain ain ain JavaScript leftContext Property(Nice) The leftContext property is the substring in front of the characters most recently matched. This property contains everything from the string from before the match. Syntax RegExp.leftContext <html> <body> <script type="text/javascript"> var str = "The rain in Spain stays mainly in the plain"; var patt1 = new RegExp("ain", "g"); for(i = 0; i < 4; i++) { patt1.test(str) document.write(RegExp.lastMatch); document.write(" found. Text before match: " + RegExp.leftContext); document.write("<br />"); } </script> </body> </html> o/p : ain found. Text before match: The r ain found. Text before match: The rain in Sp ain found. Text before match: The rain in Spain stays m ain found. Text before match: The rain in Spain stays mainly in the pl JavaScript multiline Property The multiline property is used to return whether or not the "m" modifier is used in the regular expression. The "m" modifier is set if the regular expression should be tested against possible matches over multiple lines. This property is "TRUE" if the "m" modifier is set, "FALSE" otherwise. Syntax RegExpObject.multiline <html> <body>
  • 30. <script type="text/javascript"> var str = "Visit W3Schools"; var patt1 = new RegExp("s","m"); if(patt1.multiline) { document.write("Multiline property is set"); o/p multiline property is set } else { document.write("Multiline property is NOT set."); } </script> </body> </html> JavaScript rightContext Property The rightContext property is the substring from after the characters most recently matched. This property contains everything from the string from after the match. Syntax RegExp.rightContext <html> <body> <script type="text/javascript"> var str = "The rain in Spain stays mainly in the plain"; var patt1 = new RegExp("ain", "g"); for(i = 0; i < 4; i++) { patt1.test(str); document.write(RegExp.lastMatch); document.write(" found. Text after match: " + RegExp.rightContext); document.write("<br />"); } </script> </body> </html> ain found. Text after match: in Spain stays mainly in the plain ain found. Text after match: stays mainly in the plain ain found. Text after match: ly in the plain ain found. Text after match: JavaScript source Property The source property is used to return the text used for pattern matching. The returned text is everything except the forward slashes and any flags. Syntax RegExpObject.source <html>
  • 31. <body> <script type="text/javascript"> var str = "Visit W3Schools"; var patt1 = new RegExp("W3S","g"); document.write("The regular expression is: " + patt1.source); </script> </body> </html> o/p::The regular expression is: W3S JavaScript compile() Method The compile() method is used to change the regular expression. Syntax RegExpObject.compile(regexp) Parameter Description regexp Required. The new regular expression to search for Example In the following example we change the pattern from "Microsoft" to "W3Schools", and then test if we find the specified pattern in a string: <script type="text/javascript"> var str="Visit W3Schools"; var patt=new RegExp("Microsoft"); document.write("Test if we find " + patt + " in " + str + ": ") if (patt.test(str)==true) { document.write("Match found!") } else { document.write("Match not found") } patt.compile("W3Schools"); document.write("<br />") document.write("Test if we find " + patt + " in " + str + ": ") if (patt.test(str)==true) { document.write("Match found!") } else { document.write("Match not found") }
  • 32. </script> The output of the code above will be: Test if we find /Microsoft/ in Visit W3Schools: Match not found Test if we find /W3Schools/ in Visit W3Schools: Match found! JavaScript exec() Method The exec() method searches a string for a specified value. This method returns the matched text if a match is found, and null if not. Syntax RegExpObject.exec(string) Parameter Description RegExpObject Required. The regular expression to use string Required. The string to search Example In the following example we will search for "W3Schools" in a string: <script type="text/javascript"> var str="Visit W3Schools"; var patt=new RegExp("W3Schools"); document.write(patt.exec(str)); </script> The output of the code above will be: W3Schools JavaScript test() Method The test() method searches a string for a specified value. This method returns true if a match is found, and false if not. Syntax RegExpObject.test(string) Parameter Description RegExpObject Required. The regular expression to use string Required. The string to search Example In the following example we change the pattern from "Microsoft" to "W3Schools", and then test if we find the specified pattern in a string: <script type="text/javascript"> var str="Visit W3Schools"; var patt=new RegExp("Microsoft");
  • 33. document.write("Test if we find " + patt + " in " + str + ": ") if (patt.test(str)==true) { document.write("Match found!") } else { document.write("Match not found") } patt.compile("W3Schools"); document.write("<br />") document.write("Test if we find " + patt + " in " + str + ": ") if (patt.test(str)==true) { document.write("Match found!") } else { document.write("Match not found") } </script> The output of the code above will be: Test if we find /Microsoft/ in Visit W3Schools: Match not found Test if we find /W3Schools/ in Visit W3Schools: Match found! JavaScript isFinite() Function The isFinite() function is used to check if a value is a finite number. Syntax isFinite(number) Parameter Description number Required. The value to be tested Example In this example we use isFinite() to check for finite numbers: <script type="text/javascript"> document.write(isFinite(123)+ "<br />"); document.write(isFinite(-1.23)+ "<br />"); document.write(isFinite(5-2)+ "<br />"); document.write(isFinite(0)+ "<br />"); document.write(isFinite("Hello")+ "<br />"); document.write(isFinite("2005/12/12")+ "<br />"); </script>
  • 34. The output of the code above will be: true true true true false false JavaScript Number() Function The Number() function converts the value of an object to a number. Syntax Number(object) Parameter Description object Required. A JavaScript object Tips and Notes Note: If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC. Note: If the object's value cannot be converted to a number, the Number() function returns NaN. Example In this example we will try to convert different objects to numbers: <script type="text/javascript"> var test1= new Boolean(true); var test2= new Boolean(false); var test3= new Date(); var test4= new String("999"); var test5= new String("999 888"); document.write(Number(test1)+ "<br />"); document.write(Number(test2)+ "<br />"); document.write(Number(test3)+ "<br />"); document.write(Number(test4)+ "<br />"); document.write(Number(test5)+ "<br />"); </script> The output of the code above will be: 1 0 1247394276301 999 NaN JavaScript isNaN() Function The isNaN() function is used to check if a value is not a number. Syntax
  • 35. isNaN(number) Parameter Description number Required. The value to be tested Example In this example we use isNaN() to check some values: <script type="text/javascript"> document.write(isNaN(123)+ "<br />"); document.write(isNaN(-1.23)+ "<br />"); document.write(isNaN(5-2)+ "<br />"); document.write(isNaN(0)+ "<br />"); document.write(isNaN("Hello")+ "<br />"); document.write(isNaN("2005/12/12")+ "<br />"); </script> The output of the code above will be: false false false false true true JavaScript escape() Function The escape() function encodes a string, so it can be read on all computers. Syntax escape(string) Parameter Description string Required. The string to be encoded Tips and Notes Note: The escape() function encodes special characters, with the exception of: *@-_+./ Tip: Use the unescape() function to decode strings encoded with escape(). Note: The escape() and unescape() functions should not be used to encode or decode URIs. Use encodeURI() and decodeURI() functions instead! Example In this example we use escape() to encode strings: <script type="text/javascript"> document.write(escape("Visit W3Schools!") + "<br />"); document.write(escape("?!=()#%&")); </script>
  • 36. The output of the code above will be: Visit%20W3Schools%21 %3F%21%3D%28%29%23%25%26 JavaScript unescape() Function The unescape() function decodes a string encoded with escape(). Syntax unescape(string) Parameter Description string Required. The string to be decoded Tips and Notes Note: The escape() and unescape() functions should not be used to encode or decode URIs. Use encodeURI() and decodeURI() functions instead! Example In this example we first encode the strings with the escape() function, and then decode them with the unescape() function: <script type="text/javascript"> var test1="Visit W3Schools!"; test1=escape(test1); document.write (test1 + "<br />"); test1=unescape(test1); document.write(test1 + "<br />"); </script> The output of the code above will be: Visit%20W3Schools%21 Visit W3Schools! JavaScript eval() Function // Its important to make the code more smaller.......nice one The eval() function evaluates a string and executes it as if it was script code. Syntax eval(string) Parameter Description string Required. The string to be evaluated Example In this example we use eval() on some strings and see what it returns: <script type="text/javascript">
  • 37. eval("x=10;y=20;document.write(x*y)"); document.write("<br />"); document.write(eval("2+2")); document.write("<br />"); var x=10; document.write(eval(x+17)); document.write("<br />"); </script> The output of the code above will be: 200 4 27 JavaScript String() Function The String() function converts the value of an object to a string. Syntax String(object) Parameter Description object Required. A JavaScript object Tips and Notes Note: The String() function returns the same value as toString() of the individual objects. Example In this example we will try to convert different objects to strings: <script type="text/javascript"> var test1= new Boolean(1); var test2= new Boolean(0); var test3= new Boolean(true); var test4= new Boolean(false); var test5= new Date(); var test6= new String("999 888"); var test7=12345; document.write(String(test1)+ "<br />"); document.write(String(test2)+ "<br />"); document.write(String(test3)+ "<br />"); document.write(String(test4)+ "<br />"); document.write(String(test5)+ "<br />"); document.write(String(test6)+ "<br />"); document.write(String(test7)+ "<br />"); </script> The output of the code above will be: true false
  • 38. true false Sun Jul 12 2009 15:55:47 GMT+0530 (India Standard Time) 999 888 12345 Examples for Events :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: JavaScript onclick Event <html> <body> Field1: <input type="text" id="field1" value="Hello World!"> <br /> Field2: <input type="text" id="field2"> <br /><br /> Click the button below to copy the content of Field1 to Field2. <br /> <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy Text</button> </body> </html> onfocus event <html> <head> <script type="text/javascript"> function setStyle(x) { document.getElementById(x).style.background="yellow"; } </script> </head> <body> First name: <input type="text" onfocus="setStyle(this.id)" id="fname"> <br /> Last name: <input type="text" onfocus="setStyle(this.id)" id="lname"> </body> </html> onkeydown Event Browser differences: Internet Explorer uses event.keyCode to retrieve the character that was pressed and Netscape/Firefox/Opera uses event.which. <html> <body> <script type="text/javascript"> function noNumbers(e) {
  • 39. var keynum; var keychar; var numcheck; if(window.event) // IE { keynum = e.keyCode; } else if(e.which) // Netscape/Firefox/Opera { keynum = e.which; } keychar = String.fromCharCode(keynum); numcheck = /d/; return !numcheck.test(keychar); } </script> <form> Type some text (numbers not allowed): <input type="text" onkeydown="return noNumbers(event)" /> </form> </body> </html> Date and Time Section :::: <html> <body> <script type="text/javascript"> document.write(Date()); </script> </body> </html> o/p Sun Jul 12 2009 16:16:31 GMT+0530 (India Standard Time) <html> <body> <script type="text/javascript"> var minutes = 1000*60; var hours = minutes*60; var days = hours*24; var years = days*365; var d = new Date(); var t = d.getTime(); var y = t/years; document.write("It's been: " + y + " years since 1970/01/01!"); </script>
  • 40. </body> </html> O.p It's been: 39.554654748414514 years since 1970/01/01! <html> <body> <script type="text/javascript"> var d = new Date(); d.setFullYear(1992,10,3); document.write(d); </script> </body> </html> O/p :Tue Nov 03 1992 16:16:32 GMT+0530 (India Standard Time) <html> <body> <script type="text/javascript"> var d = new Date(); document.write (d.toUTCString()); </script> </body> </html> Sun, 12 Jul 2009 10:46:34 GMT <html> <body> <script type="text/javascript"> var d=new Date(); var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; document.write("Today it is " + weekday[d.getDay()]); // getDay function will return the number
  • 41. </script> </body> </html> Today is Sunday Clock <html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); } function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> return current time 16:39:02 Mathematical Function : Mathematical Methods In addition to the mathematical constants that can be accessed from the Math object there are also several methods available. The following example uses the round() method of the Math object to round a number to the nearest integer: document.write(Math.round(4.7)); The code above will result in the following output: 5
  • 42. Random method The following example uses the random() method of the Math object to return a random number between 0 and 1: document.write(Math.random()); The code above can result in the following output: 0.6388059778069849 The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10: document.write(Math.floor(Math.random()*11)); The code above can result in the following output: 4 <html> <body> <script type="text/javascript"> document.write(Math.random()); </script> </body> </html> <html> <body> <script type="text/javascript"> document.write(Math.round(0.60) + "<br />"); document.write(Math.round(0.50) + "<br />"); document.write(Math.round(0.49) + "<br />"); document.write(Math.round(-4.40) + "<br />"); document.write(Math.round(-4.60)); </script> </body> </html> The innerHTML property sets or returns the text of a link. It will redirect u to the microsoft site <html> <head> <script type="text/javascript"> function changeLink() { document.getElementById('myAnchor').innerHTML="Visit W3Schools";
  • 43. document.getElementById('myAnchor').href="http://www.w3schools.com"; document.getElementById('myAnchor').target="_blank"; } </script> </head> <body> <a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a> <input type="button" onclick="changeLink()" value="Change link"> <p>In this example we change the text and the URL of a hyperlink. We also change the target attribute. The target attribute is by default set to "_self", which means that the link will open in the same window. By setting the target attribute to "_blank", the link will open in a new window.</p> </body> </html> Regular Expression(RegExp) What is RegExp RegExp, is short for regular expression. When you search in a text, you can use a pattern to describe what you are searching for. RegExp IS this pattern. A simple pattern can be a single character. A more complicated pattern consists of more characters, and can be used for parsing, format checking, substitution and more. You can specify where in the string to search, what type of characters to search for, and more. Defining RegExp The RegExp object is used to store the search pattern. We define a RegExp object with the new keyword. The following code line defines a RegExp object called patt1 with the pattern "e": var patt1=new RegExp("e"); When you use this RegExp object to search in a string, you will find the letter "e". Methods of the RegExp Object The RegExp Object has 3 methods: test(), exec(), and compile(). test() The test() method searches a string for a specified value. Returns true or false Example var patt1=new RegExp("e"); document.write(patt1.test("The best things in life are free")); Since there is an "e" in the string, the output of the code above will be: true Navigator Object
  • 44. Properties Description ---------------------------------------------------------------------------------------------------- appCodeName The code name of the browser. appName The name of the browser (ie: Microsoft Internet Explorer). appVersion Version information for the browser (ie: 4.75 [en] (Win98; U)). appMinorVersion The minor version number of the browser. cookieEnabled Boolean that indicates whether the browser has cookies enabled. cpuClass The type of CPU which may be "x86" language Returns the default language of the browser version (ie: en-US). NS and Firefox only. mimeTypes[] An array of all MIME types supported by the client. NS and Firefox only. platform[] The platform of the client's computer (ie: Win32). plugins An array of all plug-ins currently installed on the client. NS and Firefox only. systemLanguage Returns the default language of the operating system (ie: en-us). IE only. userAgent String passed by browser as user-agent header. (ie: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)) userLanguage Returns the preferred language setting of the user (ie: en-ca). IE only. mimeTypes An array of MIME type descriptive strings that are supported by the browser. onLine A boolean value of true or false. Image Map Example <html> <head> <script type="text/javascript"> function writeText(txt) { document.getElementById("desc").innerHTML=txt; } </script> </head> <body> <img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" /> <map name="planetmap"> <area shape ="rect" coords ="0,0,82,126" onMouseOver="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')" href ="sun.htm" target ="_blank" alt="Sun" /> <area shape ="circle" coords ="90,58,3" onMouseOver="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')" href ="mercur.htm" target ="_blank" alt="Mercury" />
  • 45. <area shape ="circle" coords ="124,58,8" onMouseOver="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')" href ="venus.htm" target ="_blank" alt="Venus" /> </map> <h4 id="desc"></h4> </body> </html> Timing Object <html> <head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert('5 seconds!')",5000); } </script> </head> <body> <form> <input type="button" value="Display timed alertbox!" onClick = "timedMsg()"> </form> <p>Click on the button above. An alert box will be displayed after 5 seconds.</p> </body> </html>