You are on page 1of 32

JavaScript Tutorial

Developed initially by Netscape in 1995 for use with HTML pages, JavaScript is now a widely used scripting language supported by the majority of Web browsers and diverse Web tools. A registered trademark of Sun Microsystems, Inc., JavaScript works with HTML pages, adding interactive functions that developers can use to create dynamic Web Pages. JavaScript is a less powerful version of Java that is easy to learn and use as it contains simpler syntax and rules . JavaScripts source code is embedded into the header of the HTML page on the client side and compiled into intermediate language (bytecode) on the server side. There are no licensing issues with JavaScript. JavaScript functions as both a procedural language and an object-oriented language. With JavaScript, a developer or programmer can create objects and attach methods and properties. JavaScript reduces the load on the server because most of the data is processed on the client side, resulting in faster processing time for millions of web pages on the Internet. JavaScripts main functionality is in the development of web pages and web sites that are easily interactive and user-friendly. Because of the popularity of JavaScript, career opportunities for JavaScript web developers are available all over the world. Online tutorials on JavaScripts features are available for beginners as well as advanced developers.

JavaScript Introduction
In this JavaScript tutorial, you will learn about introduction to JavaScript, why JavaScript, differences between Java and JavaScript and advantages of JavaScript.

What is JavaScript?
JavaScript was first developed by Netscape as an open scripting language to create interactive web pages. Script is nothing but a small program which is generally very easy to learn and use. JavaScript as an open language implies that it can be used by anyone; no license is required to use JavaScript. Microsoft created Jscript for its Internet Explorer similar to Netscape JavaScript. JavaScript has the ability to function both as an object oriented language as well as procedural language. Using JavaScript you can create objects, attach methods and properties. Though JavaScript can run on both client-side and serverside, it is very popular among client-side scripting languages. Client side means the script runs on client browser. JavaScript are generally embedded in the header of web pages.

Why JavaScript?
JavaScript plays a vital role for adding interactive feature to HTML web pages. JavaScript can respond to several events that occur on web-pages and thereby help in designing dynamic and interactive web-sites. Moreover JavaScript makes it very easier to validate a form, check if any fields are empty and verify correctness of data. JavaScript does all these

at client side even before actually sending the data to server, thereby reducing considerable load on server and thus makes form processing easier and quicker. Millions of web-pages and server applications make use of JavaScript all over the world, there is no doubt that almost all major web-browsers support JavaScript.

My First JavaScript
JavaScript Example

<HTML> <HEAD> <TITLE>My </HEAD> <BODY> <H1 <BR <SCRIPT document.write("My </SCRIPT> </H1> </BODY> </HTML>

First

JavaScript</TITLE>

/><BR First

/><BR

ALIGN=CENTER> /> LANGUAGE="JavaScript"> JavaScript")

Output

JavaScript can be used in different ways within an HTML file.

1. header scripts In this type, JavaScript is embedded between <SCRIPT> tags within the <HEAD> tag and is used for initializing variables and or create functions that can be called from anywhere of the entire script. JavaScript in header is executed once when the page is loaded. 2. body scripts In this type, JavaScript is embedded between <SCRIPT> tags within the <BODY> tag. JavaScript within Body Tags are used for handling various events.

3. called directly when certain events occur In this type, JavaScript are called when certain events occur. Example of events include onLoad, onClick, onError, onSelect, onSubmit, onChange etc.,

Differences between Java and JavaScript:


1. JavaScript is different from Java programming language, Unlike Java, which needs compilation; JavaScript is dynamic and is interpreted in run-time. Though there are some similarities like both Java and JavaScript are client-side programming language, both descend from C++ yet both Java and JavaScript differ in many ways.

2. Java was developed by Sun Microsystems while JavaScript was developed by Netscape. . 3. JavaScript is a high-level scripting language whereas Java is an Object Oriented Programming language. . 4. JavaScript is easy to learn and use whereas Java is comparatively difficult. . 5. In case of Java programming language the code is first written and then compiled. In JavaScript the script can be executed without any compilation. . 6. JavaScript as conveyed can be directly embedded or placed in HTML but it is not possible in case of Java. One cannot write Java code directly into HTML. .

JavaScript was mainly developed for web pages or web sites to add interactive facility or feature and there by making programming effort easier, enable users to interact with web sites and there by making it user-friendly. In addition to interactive facility JavaScript also helps in giving a dynamic functionality for a webpage which helps JavaScript to handle large volume of data during online processing.

Advantages of JavaScript:
1. JavaScript offers numerous features which makes it popular. Few among them are listed below:

2. JavaScript is a dynamic open scripting language with simple syntax and rules which makes it easier to use and learn for programmers. This has made JavaScript a popular Client-side scripting language. . 3. It is an interpreted language meaning that it could be used or executed with ease without pre-compilation. . 4. JavaScript is very useful for creating interactive web pages or web sites. . 5. JavaScript helps in adding dynamic functionality to websites . 6. JavaScript makes it very easier to validate a form at the client side without connecting to server. JavaScript has the ability to instantly notify users in case there is any mistake in input data.

JavaScript Features
In this JavaScript tutorial, you will learn about features of JavaScript, JavaScript as a programming tool, dynamic effects, browser detection, DOM control and other popular JavaScript features.

A Great Programming Tool for HTML:


Professional Web designers are undoubtedly adept in using HTML and proficient in website design but not necessarily skillful in computer programming. JavaScript is a programming tool for such a situation. JavaScript is a powerful scripting language that helps HTML

designers to effectively and interactively design websites and web pages in a very simple and efficient way.

Handles Dynamic Effects:


JavaScript is such a powerful scripting language which has features to achieve dynamic effects in web pages. Using the features available in JavaScript, the designer can decide to have dynamically placed text at run time.

Browser Detection:
One of the powerful feature of JavaScript is its ability to detect client browser. Browser detection feature of JavaScript helps to achieve independent platforms. JavaScript can detect the type of browser the visitor is using and programatically switch the page to show customised pages designed for different browsers. Thus by making use of browser detection feature of JavaScript, the designer gets better control over the browser.

Saves Time:
JavaScript also has the feature of validating data submitted at the client level. This helps in saving the processing time of the server because JavaScript initially creates the validation on the client side.

DOM:
Client side JavaScript is embedded inside HTML This embedded JavaScript is used along with DOM (Document Object Model) for control over the browser by means of objects.

Popular Scripting language:


JavaScript has simple rules and procedures that make it easier to use and learn for programmers. This has made JavaScript a popular client-side scripting language.

Interpreted Language:
It is an interpreted language, meaning that it can be used or executed with ease without pre-compilation.

Visual JavaScript:
Visual JavaScript is a component-based visual development tool for the Netscape Open Network Environment used by programmers who want to build cross-platform web-based applications.

Generators and Iterators:


The newer version of JavaScript features built-in Generators and Iterators.

There are other important features in JavaScript such as variables, arrays, objects, methods, event handlers, etc. which will be explained in detail in the following sections of this tutorial.

JavaScript Variables
In this JavaScript tutorial, you will learn about JavaScript variables, rules for variable names in JavaScript, declaration of variable in JavaScript, variables usage, JavaScript in external file, how to place the JavaScript in external file and how to execute this JavaScript placed in external file. Just like any programming language, variables in JavaScript are also used to store values. The value of the variable can be edited as required by the programmer.

Rules for Variable Names in JavaScript:


Some of the rules for forming variable names are as follows:

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

Now let us see how to declare a variable name.

Declaration of Variable in JavaScript:


This is done by using the var statement. The syntax of var statement is var variable name = value In any programming language, a variable must first be declared. Storage location must be allocated for the variable before using the variable. In JavaScript, it is possible to skip the command var and directly assign value to variable names. For Example: variable name = value

Using the variable name Exforsys and the notion that a programmer wants to assign the value Training to this variable it can be written two ways: var Exforsys = Training or It can also be done as follows: Exforsys = Training

Variables Usage:
The variables can be declared and used in two ways namely: Locally Globally

When a programmer declares a JavaScript variable within a function, the variable can only be accessed within that function. When the control moves out of the function, the variable is destroyed. These variables are called local variables. Each of the local variables placed with the same name in different functions are different because they are recognized only within the function in which they are declared. If a programmer declares a JavaScript variable outside a function, all the functions on the page can access the variable. The lifetime of these variables starts when they are declared, and ends when the page is closed.

JavaScript in External File: There may be scenarios in which the same functionality of
script needs to be executed in several places in the program. Instead of writing the same JavaScript in several places (which would cause poor optimization of code) the programmer can place the JavaScript in an external file thereby allowing programmers to make use of single external file at more the one place.

How to place the JavaScript in External file:


This process is very simple. The code or the JavaScript that needs to be executed in several places in the program is written separately in a file and then saved with extension as .js for that file.

How to execute this JavaScript placed in External File:


This is performed using the attribute src for the <script> tag. The script tag is placed as needed in either the HEAD section or the BODY section using the src attribute as follows:

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

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

How to use JavaScript in HTML page


In this JavaScript tutorial you will learn how to use JavaScript in HTML page, how to write output to a page, different places where JavaScript can be paced in HTML, JavaScript in external file and how to place and execute JavaScript in external file.

How to Insert JavaScript into a HTML page:


You can insert JavaScript into an HTML page by using <script> tag. JavaScript is placed between tags starting with <script type = text/javascript> and ending with </script>. General syntax of JavaScript is as follows:

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

How to write output to a page:


The JavaScript command used for writing output to a page is document.write. The document.write command takes the argument as the text required for producing output. The example below shows how to place JavaScript command inside an HTML page : Example:

<html> <body> <script type="text/javascript"> document.write("EXFORSYS Training") </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

Observe that semicolons have not been placed to mark the end of statement, which differs from code writing style in programming languages C and C++. In JavaScript, the placement of a semicolon is optional. If a programmer wants to place more than one statement on a single line then the programmer can make use of the semicolon.

Different places where JavaScript can be paced in HTML:


JavaScript can be placed in various locations in HTML such as JavaScript in HEAD section JavaScript in BODY section JavaScript in both HEAD and BODY section JavaScript in External File

The placing of JavaScript in the above location differs in the timing of their execution. JavaScript placed in the HEAD section of HTML will be executed when called whereas, JavaScript placed in the BODY section of HTML will be executed only when the page is loaded. The general structure for placing a JavaScript in the HEAD section is:

<html> <head> <script type="text/javascript"> ..... ..... //JavaScript written in HEAD Section </script> </head>

<body> </body> </html>

The general structure for placing a JavaScript in the BODY section is

<html> <head> </head>

<body> <script type="text/javascript"> ..... ..... //JavaScript written in BODY Section </script> </body> </html>

If a programmer wants to execute JavaScript when called, or when an event is triggered, then JavaScript is placed in the HEAD section. JavaScript is placed in the HEAD Section because scripts gets loaded first. When a programmer wants to execute JavaScript when the page loads then JavaScript should be placed in the BODY section. In addition to these, you can also place JavaScripts in both HEAD and BODY sections of an HTML page. Moreover, you can place any number of scripts in an HTML page.

The general structure of JavaScript for placement in both head and body sections is as follows:

<html> <head> <script type="text/javascript"> //JavaScript written in HEAD Section document.write("JavaScript placed in HEAD Section") </script>

</head>

<body> <script type="text/javascript"> //JavaScript written in BODY Section document.write("JavaScript placed in BODY Section") </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

JavaScript in External File: There may be scenarios in which the same functionality of script needs to be executed in several places in program. For handling this scenario instead of writing the same JavaScript in several places which would cause poor optimization of code one can place the JavaScript in external file.

How to place the JavaScript in External file: This process is very simple. The code or the JavaScript which needs to be executed in several places in the program is written separately in a file and is saved with extension as .js for the file. How to execute this JavaScript placed in External File: This is done by using the attribute named as src for the <script> tag. Te general syntax of this is as follows:

<html> <head> <script src="filename"> </script>

</head> <body> </body> </html>

The script tag is placed as needed in either HEAD section or BODY section as seen in earlier chapter but with the src attribute as follows: It is important to note that external JavaScript file cannot contain HTML tags. Suppose if the JavaScript placed in external file is named as exforsys.js then it is executed by placing it as

<html> <head> <script src="exforsys.js"> </script> </head> <body>

</body> </html>

JavaScript Conditional Statements Part 1 In this JavaScript tutorial, you will learn about the conditional statements available in JavaScript for decision making, if statement and if...else statement.
Just like any other programming language, conditional statements in JavaScript are used for decision making purpose. The conditional statements available in JavaScript for decision making are: if statement if...else statement if...else if....else statement switch statement

NOTE: All syntax specified above must be written exactly as above since JavaScript is a case-sensitive language.

if statement:
If a programmer wants to execute certain statements only when a desired condition is satisfied or has true value then conditional if statement is used. General syntax of if statement in JavaScript is as follows:

if (condition) { //Statements executed if condition is true }

Let us see an example to understand this concept:

<html> <body> <script type="text/javascript"> var exforsys = 20 if (exforsys < 30) {

document.write("<b>Welcome</b>")

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

Output of the above script as produced in a HTML page is shown below:

In the above example, if block will be executed only when value of the variable is less than 30. In our example, the value of variable exforsys is 20 (which is less than 30) hence if block is executed and the output Welcome is printed.

if...else statement:
This conditional structure is used in JavaScript if a programmer wants to execute a certain block of statements if a condition is true and execute another block of statements if the condition returns false value.

General syntax of this if...else structure in a JavaScript is as follows:

if (condition) { //Statements executed if condition is true } else { //Statements executed if condition is false

<html> <body> <script type="text/javascript"> var exforsys = 40 if (exforsys < 30) { document.write("<b>Welcome</b>") } else { document.write("<b>Thank You!</b>") } </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

In this example, if block is executed only when the value of variable exforsys is less than 30, otherwise else block will get executed, since the value of variable exforsys in our example is 40, else block is executed and the output Thank You! is printed.

JavaScript Conditional Statements Part 2


In continuation of JavaScript Conditional Statements Part 1, this tutorial will help you learn about remaining conditional statements in JavaScript, if...else if...else statement and switch statement.

if...else if....else statement


If there are many branching or conditions to be decided (based on which actions must be executed) then the programmer can use the if...else if....else statement. General structure of if...else if....else statement in JavaScript is:

<html> <body> <script type="text/javascript"> if (condition1)

.........

.........

//executed if condition1 is true

else if (condition2)

.........

......... //executed if condition2 is true

else

.......

.......

//executed if condition1 & condition2 are false

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

An example for if...else if....else statement in JavaScript is shown below

<html> <body> <script type="text/javascript"> var exforsys = 20 if (exforsys < 5) {

document.write("<b>Welcome</b>")

else if (exforsys > 5 && exforsys < 10)

document.write("<b>Have a nice day!</b>")

else

document.write("<b>Thank You!</b>")

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

Output of the above script as produced in a HTML page is shown below:

In the above example variable exforsys takes the value 20 (which is not less than 5) then statements in condition1 are not executed. The value (if greater than 5 but not less than 10) of statements in condition2 are not executed, therefore the else structure is executed and the output is Thank You.

switch statement:
A programmer makes use of switch statement whenever one out of the many blocks of code needs to be executed. General structure for switch statement in Java Script is as follows:

switch (variable) { case value1: statements in block 1 break case value2: statements in block 2 break ........

........ default: statements to be executed if variable is different from case value1 or value2, and so on }

For Example

<html> <body> <script type="text/javascript"> var exforsys = 5 switch (exforsys) { case 2: document.write("<b>Hi!</b>")

break case 3: document.write("<b>Welcome</b>") break case 4: document.write("<b>Thank You!</b>") break default: document.write("<b>Have a Great Day!</b>") } </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

This is because the value of the variable exforsys is assigned as 5 which does not satisfy the value of any of the case values and hence default block is execute which gives the output as above.

JavaScript Alert Box


In this JavaScript tutorial, you will learn about JavaScript alert box along with code for placing the alert box when page is loaded There are three types of popup boxes that can be created using JavaScript. Depending on the needs of user, the programmer can create any of these types of popup boxes using JavaScript. Three kinds of popup boxes created using JavaScript are: Alert Box Confirm Box Prompt Box

Let us now learn how to create each of these popup boxes using JavaScript.

Alert Box:
This type of popup box is a dialog box used when a programmer wants to make sure that the information is passed to the user. The alert box pops up with an OK button which the user has to press to continue further.

General syntax of alert box is alert(textmessage) For example: alert(Exforsys) The above statement will display a dialog box with message Exforsys and a OK button. The dialog box remains in view until the user presses the OK button. When no text message is placed alert() This would display an empty dialog box with an OK button that the user must press to proceed. It is also possible to display messages with values of variables in an alert box. For example:

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

var exam_score = 56 alert ("Exam Score is:" + exam_score)

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

In the above script alert box displays the value of variable exam_score concatenated with a string. The plus sign acts as a concatenation symbol. Output of the above script as produced in a HTML page is shown below:

It is vital to understand that the alert box can be placed in different locations or events. Depending on the placing of the alert box and based on the place of usage, the alert box will be activated. For example, 1. it is possible to place the alert box so that it pops up when a page is loaded. 2. it is possible to place the alert box to be activated when a button is clicked. Here is an example of JavaScript code for placing the alert box to be executed when a page is loaded.

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

Output of the above script as produced in a HTML page is shown below:

JavaScript Confirm Box In the previous section of this tutorial JavaScript Alert Box, we discussed about alert boxes. In this section, you will learn about JavaScript confirm box and prompt box. Confirm Box:
The confirm box is a box that pops up with both an OK and a Cancel button. The confirm box is used to verify acceptance from the user. If the user accepts, then the user presses the OK button and the confirm box returns with a true value. If the user rejects with the Cancel button, then the confirm box returns false value. General syntax for a confirm box is confirm (textmessage) A simple confirm box example:

<html> <body> <script type="text/javascript"> if (confirm("Wish to accept or Cancel")) {

alert ("Agreed and hence True value returned")

else

alert ("Not Agree and hence False value returned")

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

In the above example, the conditional statement ifelse is used and the alert box and the confirm box are written together.

Output of the above script as produced in a HTML page is shown below:

The confirm box pops up with the message: Wish to accept or Cancel Showing two buttons (OK and Cancel) that the user can choose from. If the user presses OK in the confirm box then the value returned would be true, executing the if block of statements. This results in the alert box popping up with the message. Agreed and hence true value returned. If the user presses the Cancel button in the confirm box then the value returned would be false, executing the else block of statements. This results in the alert box popping up with the message Not Agreed and hence false value returned

Prompt Box:
The prompt box is used when a users input value is desired before entering a page. The prompt box pops up with two buttons (OK and Cancel). If the user presses OK then the prompt box returns with the value entered by user but if the user presses the Cancel button then the prompt box returns with a null value. General syntax of prompt box is as follows: prompt(textmessage,value_default) A simple prompt box example:

<html> <body> <script type="text/javascript"> name = prompt ("Input the Training Company Name","Exforsys") </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

In the above example, the default value is stored with value Exforsys and the prompt box pops up with the message Input the Training Company Name with a default value as Exforsys and two buttons (OK and Cancel). When the user presses the OK button, the value Exforsys is returned by prompt box, which is stored in the variable name. If the user presses Cancel, then null value is retuned by the prompt box

JavaScript Objects
Object oriented Programming in an important aspect of JavaScript. It is possible to use built-in objects available in JavaScript. It is also possible for a JavaScript programmer to define his own objects and variable types. In this JavaScript tutorial, you will learn how to make use of built-in objects available in JavaScript.

Built-in objects in JavaScript:


Some of the built-in objects available in JavaScript are: 1. Date 2. Math 3. String 4. Array 5. Object Of the above objects, the most widely used one is the String object.

Objects are nothing but special kind of data. Each object has Properties and Methods associated with it.

Properties of an Object:
Property is the value that is tagged to the object. For example let us consider one of the properties associated with the most popularly used String object - the length property. Length property of the string object returns the length of the string, that is in other words the number of characters present in the string. General syntax of using the length property of the string object is as below: variablename.length Here variablename is the name of the variable to which the string is assigned and length is the keyword. For example consider the JavaScript below:

<html> <body> <script type="text/javascript"> var exf="Welcome" document.write(exf.length)

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

The output of the above is 7 We see that the property of an object is the value associated with the object.

Method of an Object: Method of an object refers to the actions than can be performed
on the object. For example in String Object there are several methods available in JavaScript. Some of the Methods associated with String Object are:

toUpperCase() toLowerCase()

substring() indexOf lastIndexOf All these methods are used to perform actions on the String object. For example the substring method of the String Object in JavaScript is used for extracting a specific portion of the string. If a programmer wants the value of String object in lowercase then the method toLowerCase() is used on String Object To convert a string to upper case, the method toUpperCase() is used. If a programmer wants to know the position of a characters or group of characters in a String Object it can be determined by applying indexof method to the String. Example to understand how method can be used in an Object. In the example below, we have used toUpperCase method of String object.

<html> <body> <script type="text/javascript"> var exf="Welcome" document.write(exf.toUpperCase()) </script> </body> </html

The output of the above script is WELCOME In the above script since the method toUpperCase is applied to the string object exf which has value initialized as Welcome all letters get converted as upper case and hence the output is as above.

Purpose of String Object in JavaScript:


The main purpose of String Object in JavaScript is for storing text.

General method of using String Object is to declare a variable and assign a string, in other words a text to the variable. var exf="Welcome" assigns the text Welcome to the variable exf defined. We have seen in earlier section that some of the methods used in String Objects are: 1. .indexOf 2. lastIndexOf 3. substring() 4. toUpperCase() 5. toLowerCase()

indexOf method of String Object:


If a programmer wants to know the position of a characters or group of characters in a String Object it can be obtained by applying the indexOf method to the String. In other words indexOf method of the String Object returns the position of the first occurrence of a specified string value in a string. General syntax of the indexOf method of String Object in JavaScript is as follows: indexOf(substr, [start]) Here the substr given in argument is searched in the string and if it found the index number of the searched character is or substring within the string is returned. If it is not found then -1 is returned. The default returned value is 0. The start is an optional argument specifying the position within string to begin the search.

For example:

<html> <body> <script type="text/javascript"> var exf="Welcome members" document.write(exf.indexOf("Welcome") + "<br />") document.write(exf.indexOf("Members") + "<br />")

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

Output of the above program is: 0 -1 This is because the first write statement has Welcome given as substring in the indexOf method and since it occurs in the starting of the String Object the value 0 is printed. The second write statement has Members given as substring in the indexOf method and since it does not occur in the string the value -1 is printed. Only members is present in the String Object and not Members so -1 is printed.

lastIndexOf method of String Object:


General syntax of lastIndexOf method of String Object is as follows: lastIndexOf(substr, [start]) In this the substring given in parameters is searched for in the String and if it is found the index number of the searched character or substring within the string is returned. Here the order of search is from end to beginning of the String. If it is not found the value returned is -1. Start is an optional argument specifying the position within string to begin the search. Default is string.length-1.

For example "exfor".lastIndexOf("o")

will give a value of 3. This is because the position of text o appearing in the string is counted from the end of string and the end of string is equal to stringlenth -1 which is equal to 4 and so position of o appearing in the string is 3. substring method of String Object:
General syntax of substring method of String Object in JavaScript is as follows: substring(from, [to])

In this method characters in the string between from and to indexes is returned "to" is optional, and if omitted, characters up to the end of the string is returned. For example:

<html> <body> <script type="text/javascript"> var exf="Welcome" document.write(exf.substring(0,3)); document.write(exf.substring(3,0));

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

Output of the above program is Wel ome

You might also like