Javascript – Part I
On completion, the student will be able to:
1. Understand how Javascript executes, and its
differences with Java.
2. The concept of objects and methods in Javascript.
3. Run a Javascript code on the browser.
4. Write useful Javascript codes using simple
constructs.
1
Introduction
• What is Javascript?
An object-oriented scripting language that
is designed primarily for people who are
building web pages using HTML.
Javascript programs are embedded within
HTML documents in source code form.
The script is interpreted by the browser.
Platform independence.
• Javascript code added to HTML can
perform a wide variety of functions:
Decision making.
Submitting forms.
Performing complex mathematical
calculations.
Data entry validation, etc.
2
• Javascript is object-oriented.
It allows interaction with the properties of
objects that it recognizes.
Internal built-in objects (e.g. window object).
Browser objects (e.g. document object).
• Javascript programs can run both on the
client and the server sides.
Client side:
by the browser after downloading the HTML
document.
Server side:
requires Netscape Livewire environment.
Javascript and Java
• Although the names resemble quite
closely, they are different languages.
• Some facts:
Both are object-oriented languages.
Javascript programs are interpreted in
source code form.
Java programs are first compiled into a
device independent byte code format,
which is then interpreted.
3
Javascript is a small language and does
not have many features that exist in Java.
Java is a powerful language and can be
used in extremely sophisticated
applications.
Javascripts Objects and Methods
• In the context of Javascript:
An object is a collection of properties and
methods which can be viewed, modified
and interacted with.
A simple example of property is color, which is
rather easy to visualize.
They can be directly manipulated by referring
to the object and the property by name and
then setting its value.
For example, the background color of a page
can be changed as:
[Link] = “blue”;
4
In the object-oriented paradigm, methods
refer to functions that can be used to
manipulate objects and their properties.
Example: The method write(), which
when invoked on the document object,
causes a specific string of characters to
be outputted.
[Link] (“Hello Good Day”);
Methods which are defined on an object
give the range of choices available for
interacting with the object. Some examples:
A window object can be opened or closed using
the open() and close() methods respectively.
A form object has a submit() method which
transmits the contents of the form to the web
server.
The sequential list of a user’s path through a
number of URLs is represented by the history
object, which has forward() and backward()
methods to move through the list.
5
Apart from the pre-defined methods, it is
also possible to create user-defined
methods.
Control the rate with which a line of text scrolls
across the screen.
Determine the path of an animated object
across the display.
Event handlers can be coded in Javascript.
They are triggered in response to certain
conditions in some objects.
Can be used to control the sequence of
activities in response to some object state.
Running Scripts
• Scripts written in Javascript must either be
embedded within a HTML document, or be
referenced as an external file which is loaded
with the HTML document.
All recent browsers can detect and
interpret inline Javascript code directly.
The <SCRIPT> tag is used.
<SCRIPT LANGUAGE=“JavaScript”>
……
……
</SCRIPT>
6
Language=“JavaScript” is optional.
For browsers that do not understand
Javascript, it is possible to use the HTML
comment tag “<!--” and “-->” to bracket
out the Javascript code.
The marked block is treated as hidden by the
browsers that do not understand Javascript.
These tags are ignored by browsers that can
interpret Javascript.
• A typical HTML page:
<HTML>
<HEAD>
<TITLE> For Illustration </TITLE>
<SCRIPT LANGUAGE = “JavaScript”>
<!-- ……… ………. -->
</SCRIPT>
</HEAD>
<BODY> ……… ………. </BODY>
</HTML>
7
Javascript Examples
Example 1
• Simple message output in varying sizes.
<HTML>
<TITLE> Displaying Text </TITLE>
<BODY>
<SCRIPT>
[Link] ("<H1>Hello Good Day</H1>");
[Link] ("<H3>Best of Luck.</H3>");
</SCRIPT>
</BODY>
</HTML>
>
8
Javascript Confirm Box
• A Javascript confirmation box is a handy
way to give the visitor a choice of whether or
not an action is to be performed.
• A confirmation box will pop up, and will allow
the visitor to press an “OK” or “Cancel”
button.
• The basic command is:
confirm (“The question to ask …”);
Example 2
• Simple event handler with a confirm box.
<SCRIPT>
function respond()
{
confirm (“Hello there!”);
}
</SCRIPT>
<H2>Click on the following button</H2>
<FORM>
<INPUT TYPE="button" VALUE="Click and See"
onClick=“respond()" >
</FORM>
>
9
More on Confirm Box
• The confirm() method returns a boolean
value.
“true” if “OK” is pressed
“false” if “Cancel” is pressed
• The return value can be used in
decision logic.
Illustrated in the next example.
Example 3 :: confirm box / decision
<SCRIPT language="JavaScript">
function goto_page()
{
var c = confirm("Visit IITKGP??");
if (c == true)
[Link]="[Link]
else
[Link]="[Link]
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Click and See"
onClick=“goto_page()" >
</FORM>
>
10
Javascript Alerts
• A Javascript alert box, when clicked,
displays a text, and waits until the
visitor presses the “OK” button.
• The basic command is:
alert (“Any message to be displayed”);
Example 4 :: alert
<SCRIPT>
function respond()
{
alert (“Hello!!”);
alert (“Good Day”);
[Link] = “[Link]
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Click Here"
onClick="respond()" >
</FORM>
>
11
Changing Background Color
• Modify the bgColor attribute of the
document class.
• An example:
On mouse click, the background color
toggles between blue, green, and red.
Example 5 :: toggle color
<SCRIPT>
function change_color()
{
if ([Link] == "#0000ff")
[Link] = "#00ff00";
else if ([Link] == "#00ff00")
[Link] = "#ff0000";
else [Link] = "#0000ff";
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Color"
onClick="change_color()">
</FORM>
>
12
Example 6 :: read user input
<SCRIPT>
[Link] ("<H2> Guess the Weather /H2>");
function forecast (f)
{
a = confirm ("Will it rain
today?"); if (a)
[Link] = "RAIN"
else [Link] = "NO RAIN";
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Click"
onClick="forecast(form)" >
<P> Forecast: <INPUT TYPE="text" NAME="option" SIZE="7" >
</FORM>
>
Simple mathematical Calculation
• This example will show how to:
Extract data from a form field into a
variable.
Perform mathematical calculations on that
variable.
Store the result back into a form field.
13
Example 7 :: temperature conversion
<SCRIPT>
function c_to_f (myform)
{
var cent = parseFloat ([Link]);
fahr = (cent * 1.8) + 32;
[Link] = fahr;
}
</SCRIPT>
<FORM>
Centigrade: <INPUT TYPE=text NAME=C SIZE=6> <P>
<INPUT TYPE="button" VALUE="Convert"
onClick="c_to_f([Link])">
<P> Fahrenheit: <INPUT TYPE=text NAME=F SIZE=6>
</FORM>
>
Accessing Form Data
• This example will show how to:
Extract the individual selected fields from
a drop-down menu.
Use the selected value for further
processing.
Here the value is simply echoed back through
an alert box.
14
Example 8
<SCRIPT>
function cat(f)
{
if ([Link][0].selected)
alert ("Favorite color is red");
if ([Link][1].selected)
alert ("Favorite color is yellow");
if ([Link][2].selected)
alert ("Favorite color is green");
}
</SCRIPT>
Example 8 (contd.)
<FORM>
My favorite color:
<SELECT NAME="favcolor">
<OPTION> Red
<OPTION> Yellow
<OPTION> Green
</SELECT>
<P> <INPUT TYPE="button"
VALUE="Done"
onClick="cat([Link])" >
</FORM>
>
15
Example 9 :: using arrays
<HTML>
<HEAD>
<TITLE> List most popular sportspersons </TITLE>
<SCRIPT LANGUAGE="JavaScript">
sport = new Array(3);
sport[0] = "Sachin Tenduldar";
sport[1] = "Sania Mirza";
sport[2] = "Vishwanathan Anand";
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
var number = [Link]
[Link] ("<H2>Best sportspersons of
India </H2>" + "<P>");
for (i=0;i<number;i++)
[Link] ("Rank " + (i+1) + ": " + sport[i]
+ "<P>");
</SCRIPT>
</BODY>
</HTML>
>
16