JavaScript
Was designed to add interactivity to
HTML pages
Is a powerful client-side scripting language
(a scripting language is a lightweight
programming language)
JavaScript code is usually embedded
directly into HTML pages
JavaScript is an interpreted language
(means that scripts execute without
preliminary compilation)
lecture 5 1
What can a JavaScript do
JavaScript gives HTML designers a
programming tool
JavaScript can put dynamic text into an
HTML page
JavaScript can react to events
JavaScript can read and write HTML
elements
JavaScript can be used to validate input data
JavaScript can be used to detect the visitor's
browser
JavaScript can be used to create cookies
lecture 5 2
How to put a JavaScript code into
an HTML page
Use the <script> tag (also use the type
attribute to define the scripting language)
In the HTML page itself:
<html>
<head>
<script language=“javascript”>
// JavaScript code
</script>
</head>
lecture 5 3
Scripts can be in the either <head>
section or <body> section
Can implement in 3 ways
◦ Within the body tag
◦ Inside head tag
◦ In an external file (with .js externsion)
Placing scripts in the Head
<html>
<head>
<script type="text/JavaScript">
....
</script>
</head>
As a file, linked from the HTML page:
Scripts can be provided locally or remotely accessible JavaScript file
using src attribute.
<body>
<script language=“javascript” src=“script.js”>
</script>
</body>
Script.js file
document.write(“hello world”);
Placing scripts in the body
<HTML>
<HEAD>
<TITLE>A First Script</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = “JavaScript”>
document. write("Hello World")
</SCRIPT>
</BODY>
</HTML>
A Simple Program: Printing a Line of
Text in a Web Page
Correct method call syntax:
◦ object.method( “string”, “[additional arguments]” );
document.writeln( “<H1>argument</H1>”
);
◦ Case-sensitive, like all JavaScript functions
◦ Uses the writeln method in the browser’s document
object
◦ Prints the string, which can consist of any text and
HTML tags
◦ String must be surrounded by quotation marks (“…”)
Statement terminators
◦ All statements must end with semi-colons (;)
lecture 7 8
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0
Outline
Transitional//EN">
2 <HTML>
3 <!-- Fig. 8.2: welcome.html -->
4
5 <HEAD>
6 <TITLE>Printing a Line with Multiple
Statements</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript">
9 document.write( "<FONT COLOR='magenta'><H1>Welcome to " );
10 document.writeln( "JavaScript
Programming!</H1></FONT>"
11 </SCRIPT> );
12
13 </HEAD><BODY></BODY>
14 </HTML>
2000 Deitel & Associates, Inc.
Object: document methods:
writeln
◦ Positions output cursor on next line when
finished
write
◦ Leaves the output cursor where it is when done
executing
Both begin output where previous statement
stopped
Line breaks inserted in two ways:
◦ document.writeln( “Have a<br>Nice Day!” )
◦ document.writeln( “Have a\nNice Day!” )
10
JavaScript Comments
JavaScript comments can be used to make
the code more readable.
Comments can be added to explain the
JavaScript, or to make the code more
readable.
Single line comments start with //.
<script type="text/javascript">
// Write a heading
document.write("<h1>This is a
heading</h1>");
// Write two paragraphs:
document.write("<p>This is a
paragraph.</p>");
document.write("<p>This is another
paragraph.</p>");
</script>
JavaScript Multi-Line
Comments
Multi line comments start with /* and end with
*/.
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
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>
Variables
Variables are like storage units.
You can create variables to hold values.
You create a variable with or without the var
statement
◦ var strname = some value
◦ strname = some value
It is ideal to name a variable something that is
logical, so that you'll remember what you are
using it for.
Rules of Javascript variables
They must start with a letter or underscore
("_")
Subsequent characters can also be digits (0-9)
or letters (A-Z and/or a-z).
Remember, JavaScript is case-sensitive.
(That means that My Variable and my Variable
are two different names to JavaScript,
because they have different capitalization.)
Variables scope
When you declare a variable within a
function, the variable can only be accessed
within that function
• If you declare a variable outside a function, all
the functions on your page can access it.
• The lifetime of these variables starts when
they are declared, and ends when the page is
closed
Variables scope
When you declare a variable by assignment
outside of a function, it is called a global
variable, because it is available everywhere
in the current document.
When you declare a variable within a
function, it is called a local variable,
because it is available only within the
function.
JavaScript Popup Boxes
JavaScript has three kinds of popup boxes:
1. Alert box,
2. Confirm box,
3. 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>
<body>
<script type="text/javascript">
alert("Hello world")
</script>
</head>
</body>
</html>
<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.
<html>
<head>
<body>
<script type="text/JavaScript">
var x=window.confirm("Are you sure you are
ok?")
if (x)
window.alert("Good!")
else
window.alert("Too bad")
</script>
</head>
</body>
</html>
Syntax
confirm("sometext");
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
document.write(“congratulations!");
}
else
{
document.write(“bad of you!");
}
}
</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.
User will have to click either "OK" or
"Cancel" to proceed after
entering an input value
syntax
prompt("sometext","defaultvalue")
If the user clicks "OK" the box returns the
input value. If the user clicks "Cancel" the
box returns null.
<html>
<Head>
<body>
<script type="text/javascript">
var y=prompt("please enter your name")
alert(y)
</script>
</head>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name",“jane");
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>
<html>
<head>
<script language="JavaScript">
var n = prompt("Check your number", "Type your number here");
n = parseInt(n);
if (n == 0)
{
document.write(n)
alert("The number is zero");
}
else if (n%2)
{
document.write(n)
alert("The number is odd");
}
else
{
document.write(n)
alert("The number is even");
}
</script>
</head>
JavaScript Operators
JavaScript has many different
operators, which come in
several flavors, including
binary.
Selected assignment operators
An assignment operator assigns a value to
its left operand based on the value of its
right operand.
The basic assignment operator is equal
(=), which assigns the value of its right
operand to its left operand.
Operator Description
= Assign
Add and assign. For example, x+=y
+=
is the same as x=x+y.
Subtract and assign. For example,
-=
x-=y is the same as x=x-y.
Multiply and assign. For example,
*=
x*=y is the same as x=x*y.
Divide and assign. For example,
/=
x/=y is the same as x=x/y.
Modulus and assign. For example,
%=
x%=y is the same as x=x%y.
Comparison operators
A comparison operator compares its
operands and returns a logical value
based on whether the comparison is true
or not.
The operands can be numerical or string
values
Operator Description Example
x == y evaluates
Evaluates to true if the
Equal (= =) to true if x equals
operands are equal.
y.
x != y evaluates
Not equal Evaluates to true if the
to true if x is not
(!=) operands are not equal.
equal to y.
Evaluates to true if left x > y evaluates to
Greater than
operand is greater than true if x is greater
(>)
right operand. than y.
Evaluates to true if left x >= y evaluates
Greater than
operand is greater than to true if x is
or equal
or equal to right greater than or
(>=)
operand. equal to y.
Evaluates to true if left x < y evaluates to
Less than
operand is less than true if x is less
(<)
right operand. than y.
Evaluates to true if left x <= y evaluates
Less than or
operand is less than or to true if x is less
equal (<=)
equal to right operand. than or equal to y.
Arithmetic Operators
Arithmetic operators take numerical
values (either literals or variables) as their
operands Artithmetic Operators
Arithmetic operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder of a division)
++ Increment
-- Decrement
String Operators
In JavaScript, a string is simply a piece of text.
Operator Description
= Assignment
+ Concatenate (join two strings together)
+= Concatenate and assign
Logical Operators
Logical operators take Boolean (logical)
values as operands and return a Boolean
value.
That is, they evaluate whether each sub-
expression within a Boolean expression is
true or false, and then execute the
operation on the respective truth values.
Operator Usage Description
expr1 True if both logical
and
&& expressions expr1 and expr2
(&&)
expr2 are true. False otherwise.
True if either logical
expr1 || expression expr1 or expr2 is
or (||)
expr2 true. False if both expr1 and
expr2 are false.
False if expr is true; true if
not (!) !expr
expr is false.
EXAMPLES:
If x = 4 and y = 7, ((x + y + 2) == 13) &&
(((x + y) / 2) == 2) returns FALSE.
If x = 4 and y = 7, ((y - x + 9) == 12) || ((x
* y) == 2) returns TRUE.
If x = 4 and y = 7, !((x/2 + y) == 9) || ((x *
(y/2)) == 2) returns FALSE.
Functions
Functions are one of the fundamental
building blocks in JavaScript
A function is a JavaScript procedure -- a set
of statements that performs a specific task.
A function contains code that will be
executed by an event or by a call to the
function .
A function definition has these basic parts:
A function definition has these basic
parts:
1. The function keyword
2. A function name
3. A comma-separated list of arguments to
the function in parentheses
4. The statements in the function in curly
braces: { }
You define a function within the
<SCRIPT>...</SCRIPT> tags within the
<HEAD>...</HEAD> tags.
In defining a function, you must also declare
the variables which you will be calling in that
function.
syntax
function functionname(var1,var2,...,varX)
{
some code
}
example
function popupalert()
{
alert('This is an alert box.');
}
Popupalert();
Calling a function
To call a function that takes an argument,
you must supply the argument. If you
know the value of the argument, you can
provide it:
<html>
<head>
<script language="JavaScript">
function test()
{
document.write("Hi there");
}
test();
</script>
</head>
</html>
<html>
<head>
<script language="JavaScript">
function area(w1, w2, h){
var area=(w1+w2)*h/2
alert(area+" sq ft")
}
area(2,3,7)
area(5,7,4)
area(3,2,1)
</script>
</head>
</html>
<html>
<head>
<Script Language="JavaScript">
function showAddress()
{
document.write(“170-90200 Kitui Kenya ");
}
</Script>
<Script Language="JavaScript">
showAddress();
</Script>
</head>
</html>
<html>
<head>
<title>Module two students</title>
<Script Language="JavaScript">
function welcomeMessage()
{
document.write("<b>Welcome to module two class!</b>");
}
</Script>
</head>
<body>
<h1>Module 2 class of 2011</h1>
<h3>Processing of transcripts</h3>
<Script Language="JavaScript">
welcomeMessage();
</Script>
</body>
</html>
<html>
<head>
<Script Language="JavaScript">
function circleArea(radius)
{
var area;
area = radius * radius * 3.14159;
document.write("The area of the circle is ", area);
}
</Script>
<Script Language="JavaScript">
circleArea(7)
</Script>
</head>
</html>
Calculating Sum of two numbers
<html>
<head>
<script language="JavaScript">
function sum(a,b)
{
var sum;
sum=a+b;
document.write("The sum is ", sum);
}
</script>
<script language="JavaScript">
var num1,num2;
num1 = 3;
num2 = 2;
sum(num1, num2);
</Script>
</head>
<html>
<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>
Using Prompt to calculate the area
of a rectangle
<html>
<head>
<Script Language="JavaScript">
function rectangleArea(length, height)
{
var area;
area = length * height ;
document.write("The area of the rectangle is ", area);
}
</Script>
<Script Language="JavaScript">
var L, H;
L = prompt("enter L",3);
H = prompt("enter H",2);
rectangleArea(L, H);
</Script>
</head>
<html>
Functions that return a value
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
a=window.prompt("enter a value",4);
b=window.prompt("enter a vlaue",6);
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product());
</script>
</body>
</html>
Thankyou…