JavaScript
Introduction to JavaScript
Lesson Objectives
• To understand the following topics:
Basic Concepts of JavaScript
JavaScript and Java
Embedding JavaScript in HTML
2
1.1: Basic Concepts of JavaScript
Basic Concepts of JavaScript
3
1.1: Basic Concepts of JavaScript > 1.1.1: What is JavaScript?
What is JavaScript ?
• JavaScript is Netscape's cross-platform, object-based scripting
language.
• It is lines of executable computer code that can be inserted into a
HTML page.
• It is a lightweight programming language.
• Client-side JavaScript extends the core language by supplying
objects to control a browser and its Document Object Model.
• Server-side JavaScript extends the core language by supplying
objects relevant to running JavaScript on a server.
4
1.2: JavaScript and Java
JavaScript and Java
JavaScript Java
Interpreted Compiled (bytecodes) and
interpreted
Object based Object oriented
Codes embedded in HTML Applets distinct from HTML
Variable data types not declared Variable data types declared
5
1.3: Embedding JavaScript in HTML
Embedding JavaScript in HTML
• The <SCRIPT> tag
<SCRIPT>
JavaScript statements …
</SCRIPT>
• Ending statements with a semicolon?
• Specifying the JavaScript version
<SCRIPT LANGUAGE=“JavaScript1.2”>
6
1.3: Embedding JavaScript in HTML
Embedding JavaScript in HTML
• The <SCRIPT> tag
<SCRIPT>
JavaScript statements …
</SCRIPT>
• Ending statements with a semicolon?
• Specifying the JavaScript version
<SCRIPT LANGUAGE=“JavaScript1.2”>
7
Embedding JavaScript in HTML (Contd.)
• Hiding Scripts with Comment tags
<script type=“text/javascript”>
<!--
some statements …
// -->
</script>
• Specifying a File of JavaScript code
<SCRIPT SRC=“common.js”></SCRIPT>
8
Embedding JavaScript in HTML (Contd.)
• Using Quotation Marks
document.write(“<A HREF=„A.HTML‟>Link to next page”)
9
Embedding JavaScript in HTML (Contd.)
• Specifying alternate content with the NOSCRIPT tag
<NOSCRIPT>
Your browser has JavaScript turned off.
</NOSCRIPT>
10
1.3: Embedding JavaScript in HTML > 1.3.1: Where to Write JavaScript?
Where to write JavaScript ?
• Head Section Html Page
<head></head>
• Body Section <script
language=
• External File “JavaScript”> <body></body>
</script>
External file
//script statement
11
1.3.1: Where to Write JavaScript? > 1.3.1.1: JavaScript in Head Section
JavaScript in Head Section
<HTML>
<HEAD>
<TITLE>Script tag in Head Section</TITLE>
<SCRIPT language="Javascript">
<!--
document.write("<h1>message displayed due to script in head</h1>")
- ->
</ SCRIPT >
</HEAD>
<BODY>
</BODY>
</HTML>
12
1.3.1: Where to Write JavaScript? > 1.3.1.2: JavaScript in Body Section
JavaScript in Body Section
<HTML>
<HEAD>
<TITLE>Script tag in Body</TITLE>
</HEAD>
<BODY >
<SCRIPT language=“Javascript">
document.write("<h1>message displayed due to script in body</h1>")
</SCRIPT>
</BODY>
</HTML>
13
1.3.1: Where to Write JavaScript? > 1.3.1.3: JavaScript in External File
JavaScript in External File
<HTML>
<HEAD>
<TITLE>script tag in external file</TITLE>
<SCRIPT src="common.js">
<!– No javascript statements can be written here
</ SCRIPT>
</HEAD>
<BODY>
< SCRIPT>
document.write("Display value of a variable”+msg)
</ SCRIPT >
</BODY>
</HTML>
14
External js File
var msg
msg=“<h1>declared in external js file</h1>"
Contents of Common.js
15
Demo
• Hello.html
• Head_section.html
• Extern_file.html
• Comm.js
• Var_ex.html
• Confirm_ex.html
16
JavaScript
The JavaScript Language
Lesson Objectives
• To understand the following topics:
Data Types and Variables
JavaScript Operators
Control Structures and Loops
JavaScript Functions
18
Overview
• JavaScript Language:
Data Types and Variables
JavaScript Operators and Expressions
String Operator
Control Structures and Looping
Functions
Using the arguments Array
Predefined Functions
Using Global and Local Variables
Summary
19
2.1: Data Types and Variables
Data Types in JavaScript
• JavaScript is a free-form language. You do not have to
declare all variables, classes, and methods.
• Data Types in JavaScript are:
Number (4.156, 39)
String (“This is JavaScript”)
Boolean (true or false)
Null (null)
20
Data Types in JavaScript (Contd..)
• JavaScript variables are said to be loosely typed
• Defining variables: var variableName = value
• Rules when choosing a variable name:
Can include letters of the alphabet, digits 0-9 and the underscore
(_) character and is case-sensitive.
Cannot include spaces or any other punctuation characters.
First character of the variable name must be either a letter or the
underscore character.
No official limit on the length of a variable name, but must fit
within a line.
21
Data Types in JavaScript (Contd..)
• Scope of variables
<script language=“Javascript”>
var Global Variable
companyName=“MyCompany”
function f(){ Local Variable
var employeeName=“Tom”to ”+companyName+”,
document.write(“Welcome
“+employeeName)
}
</script>
22
2.2: JavaScript Operators > 2.2.1: Arithmetic Operator
JavaScript Operators : Arithmetic
Operator Description Example Result
+ Addition 2+2 4
- Subtraction 5–2 3
* Multiplication 4*5 20
/ Division 5/2 2.5
% Modulus 10 % 8 2
++ Increment x = 5; x++ x=6
-- Decrement x = 5; x-- x=4
23
2.2: JavaScript Operators > 2.2.2: Comparison Operator
JavaScript Operators : Comparison
Operator Description Example Result
== is equal to 5 == 8 false
!= is not equal 5 != 8 true
> is greater than 5>8 false
< is less than 5 <= 8 true
>= is greater or equal 5 >= 8 false
<= is less or equal 5 <= 8 true
24
2.2: JavaScript Operators > 2.2.3: Assignment Operator
JavaScript Operators : Assignment
Operator Example Is same as
+= x += y x=x+y
-= x -= y x=x–y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
25
2.2: JavaScript Operators > 2.2.4: Logical Operator
JavaScript Operators : Logical
Operator Description Example
&& and x = 6; y = 3
x < 10 && y > 1 returns true
|| or x = 6; y = 3
x < 10 || y > 5 returns true
! not x = false
!x returns true
26
2.2: JavaScript Operators > 2.2.5: String Operator
String Operator (+)
txt1 = “What a very”
Output
txt2 = “nice day!” What a verynice day!
txt3 = txt1 + txt2
txt1 = “What a very” Output
txt2 = “nice day!” What a very nice day!
txt3 = txt1 + “ ” + txt2
27
2.2: JavaScript Operators > 2.2.6: typeof Operator
typeof Operator
typeof undefinedvariable “undefined”
typeof 33 “number”
typeof “abcdef” “string”
typeof true “boolean”
typeof null “object”
28
Demo
• Typeof_ex.html
29
2.3: Control Structures and Loops
Control Structures and Loops
• JavaScript supports the usual control structures:
the conditionals: if, if...else, and switch;
the iterations: for, while, break, and continue
30
2.3: Control Structures and Loops > 2.3.1: „if‟ Statement
The if Statement
if(condition) {
if(a>10) {
statement 1
document.write(“Greater than
} else {
10”)
statement 2
} else {
}
document.write(“Less than 10”)
}
Shorthand
document.write( (a>10) ? “Greater than 10” : “Less than 10”
);
31
2.3: Control Structures and Loops > 2.3.2: Switch Statement
The Switch Statement
switch (variable) { switch (day) {
case outcome1 :{ case “Monday” : {
//stmts for outcome 1 } document.write(“weekday”)
case outcome2 :{ break;}
//stmts outcome 2 } case “Saturday”: {
… document.write(“weekday”)
default: { break}
//none of the outcomes …
is chosen } default: {
document.write(“Invalid day of the week”)
}
32
2.3: Control Structures and Loops > 2.3.3: „for‟ and „while‟ Statements
The for and while Statements
for( [initial expression;][condition;][increment expression] ) {
statements
}
for(var i=0;i<10;i++){
document.write(“Hello”);}
while(condition) { while(i<10) {
statements document.write(“Hello”);
} i++;}
33
The for and while Statements (contd..)
while(condition) {
statements
}
34
2.3: Control Structures and Loops > 2.3.4: „Break‟ and „Continue‟ Statements
The Break and Continue Statements
• Break
Writing break inside a switch, for, while control structure will
cause the program to jump to the end of the block. Control
resumes after the block, as if the block had finished.
• Continue
Writing continue inside a loop will cause the program to jump
to the test condition of the structure and re-evaluate and
perform instruction of the loop. Control resumes at the next
iteration of the loop.
35
Demo -for loop
• For_ex.html
36
2.4: JavaScript Functions
The Function Statement
• The function statement
function myFunction (arg1, arg2, arg3) {
statements
return } The return keyword returns a value.
• How to call a function
myFunction( “abc”, “xyz”, 4 )
or
myFunction()
37
2.4: JavaScript Functions > 2.4.1: Argument Arrays and How to call a Function
The Function Statement (Contd..)
• Using the arguments array:
arguments[i]
functionName.arguments[i]
i – ordinal number of the argument starting at zero
arguments.length – Total number of arguments
38
The Function Statement (Contd..)
function myConcat(separator) {
result = “”
for(var i=1; i<arguments.length;i++) {
result += arguments[i] + separator
}
return result
}
myConcat( “,” , “red” , “orange” , “blue”)
// returns “red, orange, blue”
39
2.4: JavaScript Functions > 2.4.3: Predefined Functions
Predefined Functions
• eval:
Evaluates a string of JavaScript code without reference
to a particular object.
eval (expr)
where expr is a string to be evaluated
• isFinite:
Evaluates an argument to determine whether it is a
finite number.
40
Predefined Functions (Contd..)
isFinite (number)
where number is the number to evaluate
• isNaN :
Evaluates an argument to determine if it is “NaN” (not a
number)
isNaN (testValue)
where testValue is the value you want to evaluate
41
Predefined Functions (Contd..)
• parseInt and parseFloat:
Returns a numeric value for string argument.
parseInt (str)
parseFloat (str)
parseInt(str, radix)
returns an integer of the specified radix of the string
argument
42
Predefined Functions (Contd..)
• Number and String :
Convert an object to a number or a string.
Number (objectReference)
String (objectReference)
D = new Date (430054663215)
x = String(D)
// returns “Thu Aug 18 04:37:43 GMT-0700 (PDT) 1983”
43
2.4: JavaScript Functions > 2.4.5: Global and Local Variables
Global and Local Variables
• Variables that exist only inside a function are called
Local variables.
• The values of such Local variables cannot be changed
by the main code or other functions.
• Variables that exist throughout the script are called
Global variables.
• Their values can be changed anytime in the code and
even by other functions.
44
Demo
• If_ex.html
• Switch_ex.html
• Break_con_ex.html
• Fun_ex.html
• Num_string_fun.html
46
JavaScript
Arrays
Lesson Objectives
• The above tasks will be learnt under the
following topics in this lesson:
Creating an Empty Array
Populating an Array
Deleting Arrays and Array Entries
Array Object Properties
Array Object Methods
48
5.1: Array Objects
Concept of Array Objects
• An array is the sole JavaScript data structure provided
for storing and manipulating ordered collections of data.
• For creating an empty array, you can use the following:
var myArray = new Array()
var myCDCollection = new Array(500)
myCDCollection [700] = “Gloria Estefan/Destiny”
collectionSize = myCDCollection.length // result = 701
49
5.2: Populating an Array
Concept of Populating an Array
• Populating an array:
solarSys = new Array(2)
solarSys[0] = "Mercury"
solarSys[1] = "Venus“
solarSys = new Array(“Mercury”, “Venus”, “Earth”, “Mars”,
“Jupiter”, “Saturn”, “Uranus”, “Neptune”, “Pluto”)
onePlanet = solarSys[4] // result = “Jupiter”
50
Concept of Populating an Array
earth = new Array()
earth.diameter = "7920 miles"
earth.distance = "93 million miles"
earth.year = "365.25 days"
earth.day = "24 hours"
earth.length // result = 4
earth.diameter // result = “7920 miles”
earth[“diameter”] // result = “7920 miles”
earth[0] // result = null
52
5.3: Deleting an Array Entry
Concept of Deleting an Array Entry
• Deleting an array element eliminates the index from
the list of accessible index values.
• This does not reduce the array‟s length, as in the given
sequence of statements.
myArray.length// result: 5
delete myArray[2]
myArray.length// result: 5
myArray[2] // result: undefined
53
5.4: Array Object Methods
Concept of Array Object Methods
• JavaScript provides the following array object methods:
arrayObject.reverse()
arrayObject.slice(startIndex, [endIndex])
arrayObject.join(separatorString)
• The code snippet here shows the usage of join method.
In this, myArray contents will be joined and placed into
arrayText by using the comma separator"
var arrayText = myArray.join(“,”)
54
Concept of Array Object Methods
arrayObject.sort([compareFunction])
myArray = new Array(12, 5, 200, 80)
function function compare(a,b) {
compare(a,b) { // last character of array strings
return a - b var aComp = a.charAt(a.length
} - 1)
myArray.sort(compar var bComp = b.charAt(b.length
e) - 1)
if (aComp < bComp) {return -1}
if (aComp > bComp) {return 1}
return 0
}
55
JavaScript
Working with Objects
Lesson Objectives
• To understand the following topics:
Object and Properties
Creating New Objects
Creating New Objects: An Example
Deleting Objects
61
Overview
• Working with Objects
Objects and Properties
Creating New Objects
Defining Properties for an Object Type
Using this for Object References
Defining Methods for an Object Type
A Complete Example
Deleting Objects
Summary
62
3.1: Objects and Properties
Working with Objects
• JavaScript is designed on a simple object-based
paradigm.
• An object is a construct with properties that are
JavaScript variables or other objects.
• An object has functions associated with it that are
known as the object's methods.
• In addition to predefined objects in JavaScript, you can
define your own objects.
63
3.2: Creating New Objects > 3.2.1: Using Initializers
Creating New Objects
• Using Object Initializers
objName = {property1:value1, property2:value2, … }
myHonda = {color:“red”, wheels:4, engine:{cylinders:4,
size:2}}
64
3.2: Creating New Objects > 3.2.2: Using Constructors
Creating New Objects (Contd.)
• Using Constructors
Define the object type by writing a constructor function.
Create an instance of the object with new.
function car(make, model, year) { mycar = new car(
this.make = make “Eagle” ,
this.model = model “Talon Tsi” ,
this.year = year 1993)
}
65
Creating New Objects (Contd..)
Function person(name, age) {
this.name = name function car(make, model, year, owner) {
this.age = age this.make = make
} this.model = model
this.year = year
this.owner = owner
}
ken = new person( “Ken” ,
33 )
car1 = new car( “Mazda” , “Miata”, 1990, ken )
67
3.2: Creating New Objects > 3.2.3: Defining Properties for an Object Type
Creating New Objects (Contd..)
• Accessing properties
car1.year=2000
document.write(car1.model)
document.write(car1.owner.name)
car1.color = “black”
• Adding properties to a previously defined object
68
3.2: Creating New Objects > 3.2.3: Defining Methods for an Object Type
Creating New Objects (Contd.)
• Defining properties for an object type:
car.prototype.color = null
car1.color = “black”
• Defining methods:
obj.methodName = function_name
obj.methodName(params)
69
3.2: Creating New Objects > 3.2.4: Defining Methods for an Object Type
Creating New Objects (Contd.)
function displayCar() { function car(make, model, year, owner) {
document.writeln(“A this.make = make
beautiful” + this.year this.model = model
+ “ ” + this.make + “ ” this.year = year
+ this.model this.owner = owner
} this.displayCar = displayCar
}
car1.displayCar()
car2.displayCar()
70
Object Properties: An Example
myobj=new
for … in
car("Mazda","Miata",1990)
for(variable in object)
for (var i in myobj) {
{ statements }
prop = i + ":" +
myobj[i]+"<BR>"
document.write(prop)
}
71
Creating Objects: Using „with‟ Keyword
• with object:
with (objectName)
{ statement }
with Math
{
x = PI * x
y = x * sin(PI)
}
72
3.4: Deleting Objects
Deleting Objects
• You can remove an object by using the delete operator.
mobs=new Car()
delete myobj // removes the object and returns true
73
Demo
• Complete_ex.html
• Instance_obj.html
• Temp_obj.html
74
JavaScript
Document Object Model
Lesson Objectives
• After completing this module you will be able to:
Understand the JavaScript Object Model.
Understand the Window object, it‟s properties and methods.
Understand the Frame object, it‟s properties and methods.
76
Module Coverage
• Topics covered in this module are:
JavaScript Document Object Model
Object Properties and Event Handlers
Working with the Window Object
Working with the Frame Object
77
6.1: JavaScript Document Object Model
JavaScript Document Object Model
78
6.1: JavaScript Document Object Model
JavaScript Document Object Model
79
6.1: JavaScript Document Object Model> 6.1.1: Object Properties
Object Properties
• Define a particular, current setting of an object.
• Property names are case-sensitive.
• Each property determines it‟s own read-write status.
• Any property you set survives as long as the document
remains loaded in the window.
• For example:
document.forms[0].phone.value = “555-1212”
document.forms[0].phone.delimiter = “-”
80
6.1: JavaScript Document Object Model> 6.1.2: Object Methods
Object Methods
• Command the script gives to that object.
• Some methods return values, but that is not a
prerequisite.
• Predefined by the object model
Assign additional methods to an existing object.
81
6.2: Event Handlers
Event Handlers
• Specify how an object reacts to an event.
Event can be triggered by a user action or a browser action.
In the earliest JavaScript-enabled browser, event handlers
were defined inside HTML tags as extra attributes.
• Event handlers as methods:
document.formName.button1.onclick=f1()
• Event handlers as properties:
<INPUT TYPE=”button” NAME=”button1” onClick=”f1()”>
82
6.2: Event Handlers
Event Handlers (Contd..)
83
6.3: Window Object
Working with Window Object
• Window object:
Unique position at the top of the JavaScript object hierarchy.
Exalted location gives window object a number of properties and
behaviors unlike other objects.
Can be omitted from object references.
Since everything takes place in a window.
84
6.3: Window Object > 6.3.1: Properties
Window Object Properties
• defaultStatus and status
window.defaultStatus=“Javascript Examples”
• parent
• frames
parent.frames.length parent.frames[0]
• onerror
window.onerror=null
• opener
85
6.3: Window Object > 6.3.2: Methods
Window Object Methods
• alert(message)
window.alert(“Display Message”)
• confirm(message)
window.confirm(“Exit Application ?”)
• prompt(message,[defaultReply])
var input=
window.prompt(“Enter value of X”)
86
6.3: Window Object > 6.3.2: Methods
Window Object Methods
• open(“URL”, “windowName” [, “windowFeatures”])
newwin=window.open(“new/URL”,”NewWindow”,
“toolbar,status,resizable”)
• close()
• moveBy(deltaX,deltaY), moveTo(x,y)
• resizeBy(deltaX,deltaY),
resizeTo(outerwidth,outerheight)
• scrollBy(deltaX,deltaY), scrollTo(x,y)
87
6.4: Frame Object
Frame Object
• Properties, methods and event handlers are same as the
window object.
• Behaves exactly like a window object, except that it is
created as part of a frameset by another document.
• Event Handlers:
OnBlur onDragDrop onMove onUnload
OnFocus onLoad onResize
88
Demo
• Window_object.html
• setTimeOut_method.html
• Window_ex.html
• setInterval_method.html
89