Chapter 4
JavaScript Programming
1
JavaScript
• JavaScript is used in millions of Web pages to
improve the design, validate forms, detect
browsers, create cookies, and much more.
• JavaScript is the most popular scripting
language on the internet, and works in all
major browsers, such as Internet Explorer,
Firefox, and Opera
2
Cont…
• Scripting languages are usually interpreted
rather than compiled.
• A script is a small piece of program that can
add interactivity to your website.
• For example, a script could generate a pop-up
alert box message, or provide a dropdown
menu.
• This script could be written using JavaScript or
VBScript.
3
Cont…
• You can write various small functions, called
event handlers using any of the scripting
language and then you can trigger those
functions using HTML attributes.
4
Purposes of Java script
• JavaScript gives HTML designers a programming
tool - JavaScript is a scripting language with a very
simple syntax!
• JavaScript can put dynamic text into an HTML
page - A JavaScript statement like this:
[Link]("<h1>" + name + "</h1>") can
write a variable text into an HTML page .
<script type="text/javascript">
var name="Internet Programming";
[Link]("<h1>" + name + "</h1>")
</script> 5
Cont…
• JavaScript can react to events - A JavaScript can
be set to execute when something happens, like
when a page has finished loading or when a
user clicks on an HTML element.
• JavaScript can read and write HTML elements -
A JavaScript can read and change the content of
an HTML element.
6
Cont…
• JavaScript can be used to validate data - A
JavaScript can be used to validate form data
before it is submitted to a server. This saves
the server from extra processing .
• JavaScript can be used to detect the visitor's
browser - A JavaScript can be used to identify
the visitor's browser, and - depending on the
browser - load another page specifically
designed for that browser
7
Cont…
• JavaScript can be used to create cookies - A
JavaScript can be used to store and retrieve
information on the visitor's computer
8
Running the JavaScript
• Any time including JavaScript in an HTML
document, we must enclose those lines inside
a <SCRIPT>...</SCRIPT> tag pair.
• These tags alert the browser program to begin
interpreting all the text between these tags as
a script.
• JavaScript is case-sensitive.
9
Cont…
<SCRIPT LANGUAGE=”text/JavaScript”>
//your script here
</SCRIPT>
Or
<SCRIPT type=”text/JavaScript”>
//your script here
</SCRIPT>
• The attribute name called LANGUAGE & TYPE
can be used interchangeably.
• But, commonly we use type attribute.
10
Cont…
• Here are some Tips to remember when writing
JavaScript commands:
• JavaScript code is case sensitive (e.g. age and
Age are different variables)
• White space between words and tabs are ignored
• Line breaks are ignored except within a statement
• JavaScript statements end with a semicolon (;)
but not always
11
Cont…
• Javascript can come at different places.
• There is a flexibility given to include JavaScript
code anywhere in an HTML document.
• But there are following most preferred ways to
include JavaScript in an HTML file.
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and
<head>...</head> sections.
• Script in and external file and then include in
<head>...</head> section. 12
External JavaScript
• If we want to run the same JavaScript on several pages,
without having to write the same script on every page,
we can write a JavaScript in an external file.
• Save the external JavaScript file with a .js file
extension.
• The external script cannot contain the <script>
</script> tags.
• To use the external script, point to the .js file in the
"src" attribute of the <script> tag.
<SCRIPT type = "JavaScript" SRC = " url of javascript file">
</SCRIPT>
13
Script between <head>…..</head>
• Scripts to be executed when they are called, or when an event is
triggered, are placed in functions.
<html>
<head>
<script language="javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body ></body>
</html> 14
Scripts in <body> tags
• If we don't want our script to be placed inside a function,
or if our script should write page content, it should be
placed in the body section.
<html>
<head> </head>
<body>
<script language="java script">
[Link] ("This message is written by JavaScript");
</script>
</body>
</html>
15
Scripts in both <head>…..</head> and <body>…..</body> tags
• We can place an unlimited number of scripts
in our document, so we can have scripts in
both the body and the head section.
16
Input-Output in Java/ Message Boxes
• In JavaScript, input-output can be done in
different ways
1. [Link]
• This method writes a string to the web page.
• Anything between double quotes will be
displayed as it is in the web page.
• However, if there is something out of quotes, it
is evaluated as expression and the result will be
sent to the web page.
17
Cont…
2. alert
• This method produces a browser alert box.
The Syntax is
• [Link]("sometext"); or simply write as
alert(“some text”)
18
Cont…
<html>
<head>
<script language="javascript">
[Link]("This message is written by JavaScript");
function message()
{
alert("message to display");
}
</script>
</head>
<body ><br><br><br><br><br><br>
<h1>I THANK YOU FOR EVERY THING YOU MADE!!!</H1>
</body>
</html> 19
Cont…
3. Prompt box:- is used to allow a user to enter
something according to the promotion.
• It is written as [Link]("please enter your
name") or simply write as prompt(“some text”)
Example:-
<script>
var y=[Link]("please enter your name")
[Link](y)
</script>
20
Cont…
4. Confirm Box
• A confirm box is often used if we 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 [Link]("sometext"); or
simply write confirm(“some text”)
21
Cont…
<script>
var x=[Link]("Are you sure you want
to quit")
if (x)
[Link]("Thank you.")
x="You pressed OK!";
else
22
Cont..
[Link]("Good choice.")
x="You pressed Cancel!";
[Link] (x);
</script>
23
Cont…
5. The Page Printing
• JavaScript helps us to implement this
functionality using print function of window
object.
• The JavaScript print function [Link]()
will print the current web page when executed.
• We can call this function directly using onclick
event as follows:
24
Cont…
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body>
<form><input type="button" value="Print"
/>
</form> </body>
25
Working with Variables and Data
• Variable is a location which is used to store
information and each variable is represented
by a symbolic name called variable name.
• Variable name is used to write and read data
to/from the variable.
26
Cont…
Declaring Variables
• To declare variable, we use the var keyword,
followed by the name we want to give to the
variable.
Syntax
var variablename;
27
Rules for JavaScript Variable names
Do not use reserved words
Use descriptive/meaningful names
Do not use symbols like @,#, “,/\}%$ etc except
_(underscore)
Must begin with characters
can not contain spaces
Variable names are case sensitive(means Salary and
salary are two different variable names)
Note: Using lowercase for variable names and
underscore to separate a variable name with
multiple words is advisable to make it more readable
28
Cont…
Example for Valid variable declaration
• var firstName;
• var he89;
• var TH_;
Example for Wrong variable names:
• Var first name; //space not allowed
• Var 89he; //can’t start with digit
• Var TH.; //punctuation mark not allowed
29
Assigning Values to Variables
• In declaration the variables are empty which
means they have no data values yet.
• After declaring a variable, it is possible to assign a
value to it by using equal sign (=) as follows:
• var myAge;
• myAge = 25;
• However, we can also assign values to the
variables as:
• var age=5;
30
Assigning Values to Undeclared Variables
• To assign values to variables that have not yet
been declared, the variables will automatically
be declared. These statements:
• age=5;
• The above statements have the same effect as:
• var age=5;
31
Redeclaring JavaScript Variables
• If we redeclare a JavaScript variable, it will not
lose its original value.
• var age=5;
• var age;
• After the execution of the statements above,
the variable age will still have the value of 5.
The value of age is not reset (or cleared) when
we redeclare it.
32
Comment in JavaScript
• Comments are ignored by the interpreter.
• The purpose of including comments is to
remind us how our script works after long
period has passed when we see our code.
• JavaScript supports two types of comments:
1. Comments on a single line are preceded by a
double-slash (//).
2. Comments that span multiple lines are
preceded by /* and followed by */
33
Java script Data type
• is defined by the value assigned to it. It can be
– Numeric: JavaScript supports both integers and
floating point numbers. Such as 1, 2, 2.3, 5.6
– String: is a collection of characters enclosed in
either single quotes or double quotes. Such
‘Welcome’,”5” etc
– Boolean: logical values that have only one of two
values, true or false.
34
Operators and Expressions
Arithmetic Operators
• Arithmetic operators are used to perform
arithmetic operations between variables or
values. +, -, *, /, %, ++, --
JavaScript Assignment Operators
• Assignment operators are used to perform
arithmetic operation and then assign the
result to variables. Includes:- =, +=, -=, *=, /=
and %=
35
Comparison Operators
• Comparison operators help to compare two or
more values .
• These kinds of comparisons return a value of
the Boolean type true or false.
• Includes: - >, >=, <, <=, ==, and! =
36
Cont…
Logical Operators
• Logical operators are used to determine the
logic between variables or values:- &&, ||
37
The Bitwise Operators
Bitwise AND operator &
• The output of bitwise AND(&) is 1 if the
corresponding bits of two operands is 1. If
either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.
• Eg. Let us suppose the bitwise AND operation
of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
38
Bitwise OR operator |
The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1.
Bitwise OR Operation of 12 and 25
0000 1100
| 0001 1001
0001 1101 = 29 (In decimal)
39
Bitwise XOR (exclusive OR) operator ^
• The result of bitwise XOR operator is 1 if the
corresponding bits of two operands are
opposite. It is denoted by ^.
Bitwise XOR Operation of 12 and 25
0000 1100
| 0001 1001
0001 0101 = 21 (In decimal)
40
Bitwise complement operator ~
• Bitwise compliment operator is an unary
operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
• 35 = 00100011 (In Binary)
• Bitwise complement Operation of 35 ~
00100011
11011100 = 220 (In decimal)
41
Right Shift Operator
• Right shift operator shifts all bits towards right
by certain number of specified bits. It is
denoted by >>.
• 212 = 11010100 (In binary)
• 212>>2 = 00110101 (In binary) [Right shift by
two bits]
• 212>>7 = 00000001 (In binary)
• 212>>8 = 00000000
• 212>>0 = 11010100 (No Shift)
42
Left Shift Operator
• Left shift operator shifts all bits towards left by
certain number of specified bits. It is denoted
by <<.
• 212 = 11010100 (In binary)
• 212<<1 = 110101000 (In binary) [Left shift by
one bit]
• 212<<0 =11010100 (Shift by 0)
• 212<<4 = 110101000000 (In binary) =3392(In decimal)
43
Cont…
• Assume variable A holds 2 and variable B
holds 3 then.
44
Cont…
Operator Description Example
& Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments. (A & B) is 2 .
| Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments. (A | B) is 3.
^ Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer (A ^ B) is 1.
arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
~ Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand. (~B) is -4 .
<< Called Bitwise Shift Left Operator. It moves all bits in its first operand to the left by the number of places (A << 1) is 4.
specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is
equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.
>> Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number (A >> 1) is 1.
of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original
operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed
in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value
right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is
equivalent to integer division by 4, and so on.
>>> Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits (A >>> 1) is 1.
shifted in on the left are always zero,
45
Java Scrpit Statements
• Conditional statements are used to perform
different actions based on different conditions.
• The following are JavaScript conditional
statements:
– if statement
– if…else statement
– if…else if…else statement
– switch statement
46
if statement
Used to execute statements only if the specified condition is true
Syntax:
if(condition)
{
Statement to be executed;
}
Example:
<script type=“text/javascript”>
var x=10;
var y=“10”;
if(x==y)
{
[Link](x+”is equal to “+y);
}
</script> 47
if … else statement
• Is used to execute some code if a condition is true and another code if the condition is not
true.
Syntax:
if(condition)
{
Statement to be executed;
}
else
{
Statement to be executed;
}
Example:
<script type=“text/javascript”>
var x=10;
var y=“10”;
if(x==y)
{ [Link](x+”is equal to “+y); }
else
{ [Link](x+”\&”+y+”are not equal”); }
48
</script>
if...else if…else statement
49
switch statement
• Can be used if you want to select one of many blocks of code
to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n doesn’t match any of the cases
} 50
Cont…
Example:
<script type=“text/javascript”>
var n=2;
switch(n)
{
case 1:
[Link](“You choose 1”);
break;
case 2:
[Link](“You choose 2”);
break;
case 3:
[Link](“You choose 3”);
break;
default:
[Link](“Your choice is invalid”);
}
</script>
51
JavaScript loop Statements
• Loops execute a block of codes a number
of time as long as a specified condition is
true.
• In JavaScript the following loops are used
▫ for loop
▫ while loop
▫ do while loop
52
for loop
• Used when you know in advance how many times the script
should run.
Syntax:
for (var a=startvalue; a<=endvalue;var=a++/--increment)
{
code to be executed;
}
Example:
<script type=“text/javascript”>
for(x=1;x<=20;x++)
{
[Link](x+”<br>”);
}
</script. 53
While loop
• loops through a block of codes while a specified condition is true.
Syntax:
while (var<=endvalue)
{
code to be executed
}
Example: <script type=“text/javascript”>
var y=100;
while(y>=10)
{
[Link](y+”<br>”);
y--;
}
</script>
54
do while loop
• execute the block of code ONCE, and then it will repeat the loop as long as
the specified condition is true.
Syntax:
do
{
code to be executed
}
while (var<=endvalue);
Example:
<script type=“text/javascript”>
var y=7;
do
{
[Link](y+”is between 10 and 20”);
y--;
}
while(y>=10); 55
Using Arrays
• An array is a special variable, which can hold
more than one value, at a time.
• An array can hold all your variable values
under a single name.
• you can access the values by referring to the
array name.
• Each element in the array has its own
ID(subscript number) so that it can be
accessed easily.
56
Creating an array
• An array can be created in three ways
1. var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2. var myCars=new Array("Saab","Volvo","BMW");
3. var myCars=["Saab","Volvo","BMW"];
Accessing an Array
• You can refer to a particular element in an array by
referring to the name of the array and the index
number. The index number starts at 0.
[Link](myCars[0]);
Modifying values in an array myCars[0]=“Volvo”; 57
JavaScript Function
• A function contains code that will be executed
by an event or by a call to the function.
• functions are also a great time saver for doing
repetitive tasks.
• Function can be called anywhere in the page or
external JavaScript file.
• Function can be defined both in the head and
body section of the document.
• It is advisable to define function under head
section of a document
58
How to define function?
Function with no parameter
Syntax:
function functionname()
{
Some code;
}
Function with parameter
Syntax:
function functionname(var1,var2,..varn)
{
some code;
}
• The parameters var1, var2, etc. are variables or values passed into
the function.
• Function with parameter should return value when it is called. 59
Example
Function with no parameter:
<html><head><script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script></head><body>
<form>
<input type="button" value="Click me!" />
</form></body></html>
Function with parameter:
<html><head><script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script></head><body>
<script type="text/javascript">
[Link](product(4,3)); 60
</script></body></html>
Events in JavaScript
• allows you to write JavaScript code that reacts to certain
situations.
• starts with the word on, and each event handler deals
with a certain type of event
• Events are defined in the html tag and are normally used
in combination with functions, and the function will not
be executed before the event occurs.
Examples of events:
– A mouse click
– A web page or an image loading
– Mouse over a hot spot on the web page
– Selecting an input field in an HTML form
– Submitting an HTML form
61
– A keystroke
Input Events
• onchange - When a user selects a dropdown
value
• onfocus - When an input field gets focus
• onselect - When input text is selected
• onsubmit - When a user clicks the submit
button
• onreset - When a user clicks the reset button
• onkeydown - When a user is pressing/holding
down a key
• onkeyup - When the user releases a key
62
Mouse Events
• onmouseover/onmouseout - When the
mouse passes over an element
• onmousedown - When mouse is clicked: Alert
which button
• onmousemove/onmouseout - When moving
the mouse pointer over/out of an image
63
Click Events
Acting to the onclick event
• onclick - When button is clicked
• ondblclick - When a text is double-clicked
64
onLoad
• are triggered when the user enters the page.
Example:
<html><head><script type=“text/javascript”>
function getname()
{
var name=prompt(“Enter your name”);
[Link](“Your name is ”+name);
}
</script></head>
<body ></body></html> 65
Load Events
• onload - When the page has been loaded
• onerror - When an error occurs when loading
an image
• onunload - When the browser closes the
document
• onresize - When the browser window is
resized
66
JavaScript Form Validation
• JavaScript can be used to validate data in HTML forms before
sending off the content to a server.
• Form data that typically are checked by a JavaScript could be:
– has the user left required fields empty?
– has the user entered a valid e-mail address?
– has the user entered a valid date?
– has the user entered text in a numeric field?
Example:
• To validate text box
if( [Link]==“”)
{
alert(“Please enter your name”)
return false;
} 67
Cont…
• To validate email
if([Link]=“”||[Link]('@', 0) == -1) ||
[Link]('.') == -1)
{
alert(“Please enter your email”)
return (false);
}
• To validate radio button
if ( ( [Link][0].checked == false ) && ( [Link][1].checked == false ) )
{ alert ( "Please choose your Gender: Male or Female" );
return (false); }
• To validate checkbox
if ( [Link] == false ) { alert ( "Please check the Terms & Conditions
box." ); return (false); }
• To validate dropdown lists
if ( [Link] == 0 ) { alert ( "Please select your Age." ); return 68
.
The End.
Thanks a
lot!
69
QUIZ
1. Write down the three ways that you can
create JavaScript arrays with three elements?
2. Write a JavaScript program that will display
the following array elements?
Abebe,Kebede Alemu, Almaz
3. Write a java script program that calculates the
sum of three numbers using function?
70