You are on page 1of 21

Indian Institute of Technology Kharagpur

Javascript – Part I

Prof. Indranil Sen Gupta


Dept. of Computer Science & Engg.
I.I.T. Kharagpur, INDIA

Lecture 25: 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:
document.bgcolor = “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.

document.write (“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>
document.writeln ("<H1>Hello Good Day</H1>");
document.writeln ("<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)
window.location="http://www.iitkgp.ac.in";
else
window.location="http://www.google.com";
}
</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”);
window.location = “http://www.iitkgp.ac.in”;
}
</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 (document.bgColor == "#0000ff")
document.bgColor = "#00ff00";
else if (document.bgColor == "#00ff00")
document.bgColor = "#ff0000";
else document.bgColor = "#0000ff";
}
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Color"
onClick="change_color()">
</FORM>
>

12
Example 6 :: read user input

<SCRIPT>
document.writeln ("<H2> Guess the Weather /H2>");
function forecast (f)
{
a = confirm ("Will it rain today?");
if (a) f.option.value = "RAIN"
else f.option.value = "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 (myform.C.value);
fahr = (cent * 1.8) + 32;
myform.F.value = fahr;
}
</SCRIPT>

<FORM>
Centigrade: <INPUT TYPE=text NAME=C SIZE=6> <P>
<INPUT TYPE="button" VALUE="Convert"
onClick="c_to_f(this.form)">
<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 (f.favcolor[0].selected)
alert ("Favorite color is red");
if (f.favcolor[1].selected)
alert ("Favorite color is yellow");
if (f.favcolor[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(this.form)" >
</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 = sport.length
document.write ("<H2>Best sportspersons of
India </H2>" + "<P>");
for (i=0;i<number;i++)
document.write ("Rank " + (i+1) + ": " + sport[i]
+ "<P>");
</SCRIPT>
</BODY>
</HTML>

>

16
SOLUTIONS TO QUIZ
QUESTIONS ON
LECTURE 24

17
Quiz Solutions on Lecture 24

1. How do we specify an associative array


using the ‘=>’ operator?
%directory = (
Rabi => “258345”,
Chandan => “325129”,
Atul => “445287”,
Sruti => “237221”
);

Quiz Solutions on Lecture 24

2. How can you convert a normal array to an


associative array?
@list = qw (Rabi 258345 Chandan
325129 Atul 445287 Sruti 237221);
%directory = @list;

18
Quiz Solutions on Lecture 24

3. How can you delete a (hash key,


value) pair from an associative array?
@list = qw (Rabi 258345 Chandan
325129 Atul 445287 Sruti 237221);
%directory = @list;
delete $directory{Atul};

Quiz Solutions on Lecture 24

4. How are arguments passed to subroutines?

Through the special array $_.

Individual arguments can also be


accessed as $_[0], $_[1], $_[2], etc.

5. What is the significance of ‘my’ variables?

Used to define local variables within a


function.

19
Quiz Solutions on Lecture 24

6. With the help of an example, illustrate how


the CGI.pm library can be used to create
CGI script programs.

#!/usr/bin/perl -wT
use CGI qw(:standard);
print header (“text/html”);
print start_html ("Hello World");
print "<h2>Hello, world!</h2>\n";
print end_html;

QUIZ QUESTIONS ON
LECTURE 25

20
Quiz Questions on Lecture 25

1. What is the main difference between


Java and Javascript programs with
respect to their execution?
2. How is Javascript made platform
independent?
3. Give an example of a Javascript object
and a method.
4. What is the difference between the
“confirm()” and the “alert()” methods?

Quiz Questions on Lecture 25

5. Give an example to show how the


value of a form field can be accessed.
6. Where does “document.write()”
produce its output?

21

You might also like