UNIT
III Intro to Javascript
Faculty:
Dr. Narinder Kaur
Seera
Client Side Scripting
2
CS380
Why use client-side
3
programming?
PHP already allows us to create dynamic
web pages. Why also use client-side
scripting?
client-side scripting (JavaScript) benefits:
usability: can modify a page without
having to post back to the server (faster UI)
efficiency: can make small, quick changes
to page without waiting for server
event-driven: can respond to user actions
like clicks and key presses
Why use client-side
4
programming?
server-side programming (PHP) benefits:
security: has access to server's private
data; client can't see source code
compatibility: not subject to browser
compatibility issues
power: can write files, open connections to
servers, connect to databases, ...
What is Javascript?
5
a lightweight programming language
("scripting language")
used to make web pages interactive
insert dynamic text into HTML (ex: user
name)
react to events (ex: page load user click)
get information about a user's computer
(ex: browser type)
perform calculations on user's computer
(ex: form validation)
Javascript vs Java
6
Javascript is -
interpreted, not compiled
more relaxed syntax and rules
fewer and "looser" data types
variables don't need to be declared
errors often silent (few exceptions)
key construct is the function rather than
the class
"first-class" functions are used in many
situations
contained within a web page and
JavaScript is not Java
JavaScript has some features that resemble
features in Java:
JavaScript has Objects and primitive data types
JavaScript has qualified names; for example,
document.write("Hello World");
JavaScript has Events and event handlers
Exception handling in JavaScript is almost the
same as in Java
JavaScript has some features unlike
anything in Java:
Variable names are untyped: the type of a
variable depends on the value it is currently
holding
Objects and arrays are defined in quite a
JavaScript vs. PHP
8
similarities:
both are interpreted, not compiled
both are relaxed about syntax, rules,
and types
both are case-sensitive
both have built-in regular expressions
for powerful text processing
JavaScript vs. PHP
9
Differences:
JS is more object-oriented: noun.verb(),
less procedural: verb(noun)
JS focuses on user interfaces and
interacting with a document; PHP is
geared toward HTML output and
file/form processing
JS code runs on the client's browser; PHP
code runs on the web server
About JavaScript
JavaScript is not Java, or even related to Java
The original name for JavaScript was “LiveScript”
The name was changed when Java became popular
Statements in JavaScript resemble statements in
Java, because both languages borrowed heavily
from the C language
JavaScript should be fairly easy for Java programmers
to learn
However, JavaScript is a complete, full-featured,
complex language
JavaScript is seldom used to write complete
“programs”
Instead, small bits of JavaScript are used to add
functionality to HTML pages
JavaScript is often used in conjunction with HTML
Using JavaScript in a
browser
JavaScript code is included within <script>
tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
Notes:
The type attribute is to allow you to use other
scripting languages (but JavaScript is the default)
This simple code does the same thing as just putting
<h1>Hello World!</h1> in the same place in the
HTML document
The semicolon at the end of the JavaScript statement
is optional
You need semicolons if you put two or more statements
on the same line
Where to put JavaScript
JavaScript can be put in the <head> or in the
<body> of an HTML document
JavaScript functions should be defined in the <head>
This ensures that the function is loaded before
it is needed
JavaScript in the <body> will be executed as the page
loads
JavaScript can be put in a separate .js file
– <script src="myJavaScriptFile.js"></script>
Put this HTML wherever you would put the actual
JavaScript code
An external .js file lets you use the same JavaScript on
multiple HTML pages
The external .js file cannot itself contain a <script> tag
Linking to a JavaScript file:
13
script
<script src="filename" type="text/javascript"></script>
HTML
script tag should be placed in HTML
page's head
script code is stored in a separate .js file
JS code can be placed directly in the
HTML file's body or head (like CSS)
but this is bad style (should separate
content, presentation, and behavior
Primitive data types
JavaScript has three “primitive” types: number,
string, and boolean
Everything else is an object
Numbers are always stored as floating-point
values
Hexadecimal numbers begin with 0x
Some platforms treat 0123 as octal, others treat it as
decimal
Strings may be enclosed in single quotes or
double quotes
Strings can contains \n (newline), \" (double quote),
etc.
Booleans are either true or false
Variables
Variables are declared with a var
statement:
– var pi = 3.1416, x, y, name = "Dr. Dave" ;
Variables names must begin with a letter or
underscore
Variable names are case-sensitive
Variables are untyped (they can hold values
of any type)
The word var is optional (but it’s good style to
use it)
Variables declared within a function are
local to that function (accessible only
Variables
16
var name = expression; JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4; JS
variables are declared with the var
keyword (case sensitive)
types are not specified, but JS does have
types ("loosely typed")
Number, Boolean, String, Array, Object,
Function, Null, Undefined
can find out a variable's type by calling
typeof
Number type
17
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS
integers and real numbers are the same
type (no int vs. double)
same operators: + - * / % ++ -- = += -=
*= /= %=
similar precedence to Java
many operators auto-convert types: "2"
* 3 is 6
Comments (same as Java)
18
// single-line comment
/* multi-line comment */
JS
identical to Java's comment syntax
recall: 4 comment syntaxes
HTML: <!-- comment -->
CSS/JS/PHP: /* comment */
Java/JS/PHP: // comment
PHP: # comment
Comments
Comments are as in C or Java:
Between // and the end of the line
Between /* and */
Java’s javadoc comments, /** ... */, are
treated just the same as /* ... */
comments; they have no special
meaning in JavaScript
Operators, I
Because most JavaScript syntax is borrowed from
C (and is therefore just like Java), we won’t spend
much time on it
Arithmetic operators:
+ - * / % ++ --
Comparison operators:
< <= == != >= >
Logical operators:
&& || ! (&& and || are short-circuit
operators)
Bitwise operators:
& | ^ ~ << >> >>>
Assignment operators:
+= -= *= /= %= <<= >>= >>>=
Operators, II
String operator:
+
The conditional operator:
condition ? value_if_true :
value_if_false
Special equality tests:
– == and != try to convert their operands
to the same type before performing the
test
– === and !== consider their operands
unequal if they are of different types
Additional operators (to be discussed):
new typeof void delete
Logical operators
22
> < >= <= && || ! == != === !==
most logical operators automatically
convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
=== and !== are strict equality tests;
checks both type and value
"5.0" === 5 is false
Boolean type
23
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
any value can be used as a Boolean
"falsey" values: 0, 0.0, NaN, "", null, and
undefined
"truthy" values: anything else
converting a value into a Boolean
explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);
Statements, I
Most JavaScript statements are also
borrowed from C
Assignment: greeting = "Hello, " + name;
Compound statement:
{ statement; ...; statement }
If statements:
if (condition) statement;
if (condition) statement; else
statement;
Familiar loop statements:
while (condition) statement;
do statement while (condition);
Statements, II
The switch statement:
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
Other familiar statements:
– break;
– continue;
The empty statement, as in ;; or { }
if/else statement (same as
26
Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
identical structure to Java's if/else
statement
JavaScript allows almost anything as a
condition
for loop (same as Java)
27
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS
while loops (same as Java)
28
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
break and continue keywords also
behave as in C or Java
The for…in statement
You can loop through all the properties of an object with
for (variable in object) statement;
Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
Possible output: teacher: Dr. Dave
number: CIT597
The properties are accessed in an undefined order
If you add or delete properties of the object within the loop,
it is undefined whether the loop will visit those properties
Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
Notice that course["teacher"] is equivalent to
course.teacher
You must use brackets if the property name is in a
variable
The with statement
• with (object) statement ; uses the
object as the default prefix for
variables in the statement
For example, the following are
equivalent:
– with (document.myForm) {
result.value = compute(myInput.value) ;
}
– document.myForm.result.value =
compute(document.myForm.myInput.value);
One of my books hints at mysterious
problems resulting from the use of
Object literals
You don’t declare the types of variables
in JavaScript
– Objects are variables too. But objects
can contain many values.
– The values are written as name:value
pairs (name and value separated by a
colon).
– { name1 : value1 , ... , nameN :
valueN }
Example: A car is an object.
A car has properties like weight and
Object Definition
32
You define (and create) a JavaScript object
with an object literal:
const person = { firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue" };
The name:values pairs in JavaScript
objects are called properties:
You can access object properties in two
ways:
objectName.propertyName or
Three ways to create an
object
You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
You can use new to create a “blank” object,
and add fields to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave");
Javascript Objects
34
Arrays
Strings
Date Object
Math Object
Document Object
Browser Object Model’s Object (BOM’s
objects)
Window
History
Screen
Arrays
35
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS
Array literals
You don’t declare the types of variables in
JavaScript
JavaScript has array literals, written with
brackets and commas
Example: color = ["red", "yellow", "green", "blue"];
Arrays are zero-based: color[0] is "red"
If you put two commas in a row, the array has
an “empty” element in that location
Example: color = ["red", , , "green", "blue"];
• color has 5 elements
However, a single comma at the end is ignored
Example: color = ["red", , , "green", "blue”,]; still has 5
elements
Four ways to create an
array
You can use an array literal:
var colors = ["red", "green", "blue"];
You can use new Array() to create an empty
array:
– var colors = new Array();
You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue";
colors[1]="green";
You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
You can use new Array(…) with two or more
arguments to create an array containing those
values:
The length of an array
If myArray is an array, its length is given by
myArray.length
Array length can be changed by assignment
beyond the current length
Example: var myArray = new Array(5); myArray[10]
= 3;
Arrays are sparse, that is, space is only
allocated for elements that have been assigned
a value
Example: myArray[50000] = 3; is perfectly OK
But indices must be between 0 and 232-1
As in C and Java, there are no two-dimensional
arrays; but you can have an array of arrays:
myArray[5][3]
Arrays and objects
Arrays are objects
• car = {Company: “Hyundai", Name:
“Creta" }
– car[“Company”] is the same as
car.Company
– car.Name is the same as car[“Name“]
Array functions
If myArray is an array,
myArray.sort() sorts the array alphabetically
myArray.sort(function(a, b) { return a - b; })
sorts numerically
myArray.reverse() reverses the array
elements
myArray.push(…) adds any number of new
elements to the end of the array, and
increases the array’s length
myArray.pop() removes and returns the last
element of the array, and decrements the
array’s length
myArray.toString() returns a string
Math object
41
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
JS
methods: abs, ceil, cos, floor, log,
max, min, pow, random, round, sin,
sqrt, tan
properties: E, PI
Special values: null and
42
undefined
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
undefined : has not been declared, does
not exist
null : exists, but was specifically
assigned an empty or null value
Why does JavaScript have both of these?
String Object
43
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
charAt returns a one-letter String (there is
no char type)
length property (not a method as in Java)
Strings can be specified with "" or ''
concatenation with + :
1 + 1 is 2, but "1" + 1 is "11"
String Methods
44
charAt() Returns the character at a specified index
(position)
concat() Returns two or more joined strings
indexOf() Returns the index (position) of the first
occurrence of a value in a string
replace() Searches a string for a value, or a regular
expression, and returns a string where the values are
replaced
slice() Extracts a part of a string and returns a new
string
substring() Extracts characters from a string, between
two specified indices (positions)
toLowerCase() Returns a string converted to
lowercase letters
Splitting strings: split and
45
join
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown“,"fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS
split breaks apart a string into an array
using a delimiter
can also be used with regular expressions
(seen later)
join merges an array into a single string,
placing a delimiter between them
Javascript Dates
46
The JavaScript date object can be used
to get year, month and day. You can
display a timer on the webpage by the
help of JavaScript date object.
Methods of Date Object are:
getDate() It returns the integer value
between 1 and 31 that represents the
day for the specified date on the basis of
local time.
getDay() It returns the integer value
between 0 and 6 that represents the day
Date Methods (contd..)
47
getHours() It returns the integer value between 0
and 23 that represents the hours on the basis of
local time.
getMilliseconds() It returns the integer value
between 0 and 999 that represents the
milliseconds on the basis of local time.
getMinutes() It returns the integer value between
0 and 59 that represents the minutes on the
basis of local time.
getMonth() It returns the integer value between
0 and 11 that represents the month on the basis
of local time.
setDate() It sets the day value for the specified
Date Example
48
Create a date object and then you can use
methods as follows:
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
DOM (Document Object
49
Model)
DOM organizes the elements of the
document in a tree structure (DOM tree)
and in the DOM tree, all elements of the
document are defined as objects (tree
nodes) which have properties and
methods.
The document object represents the
whole html document.
When html document is loaded in the
browser, it becomes a document object.
It is the root element that represents
50
Properties of Document
51
Object
Methods of document
52
object
We can access and change the contents of
document by its methods.
write("string") - writes the given string on the
doucment.
writeln("string") - writes the given string on the
doucment with newline character at the end.
getElementById() - returns the element having
the given id value.
getElementsByName() - returns all the elements
having the given name value.
getElementsByTagName() - returns all the
elements having the given tag name.
innerHTML property
53
The innerHTML property can be used to
write the dynamic html on the html
document.
It is used mostly in the web pages to
generate the dynamic html such as
registration form, comment form, links
etc.
Eg: <p id=‘para1’> </p>
:
:
Changing element style:
54
element.style
Example :
Property or
<body> style object
<H1 id=“myid”> Heading1
</H1> color
: padding
<script>
backgroundCo
h=document.getElementById("m lor
yid"); borderTopWidt
h.style.color="red"; h
h.style.fontSize=40; fontSize
h.style.backgroundColor="green" fontFamily
Document Object Model
55
(DOM)
most JS code
manipulates elements
on an HTML page
we can examine
elements' state
e.g. see whether a box
is checked
we can change state
e.g. insert some new
text into a div
we can change styles
BOM
56
BOM main task is to manage browser windows
and enable communication between the windows
(i.e BOM deals with entire browser). Each HTML
page which is loaded into a browser window
becomes a Document object and a document
object is an object in the BOM.
BOM is a superset of DOM. BOM has many
objects, methods, and properties that are not
part of the DOM structure.
It consists of:
Window,screen, location, history, navigator,
popup alert, timing, cookies
BOM
57
The Browser Object Model (BOM) is
used to interact with the browser.
The default object of browser is window
means you can call all the functions of
window by specifying window or directly.
For example:
window.alert(“Hello World");
Is same as:
alert(“Hello World");
BOM
58
You can use a lot of properties (other
objects) defined underneath the window
object like document, history, screen,
navigator, location etc.
Window Object
59
Methods of Window object are:
1. alert() - displays the alert box
containing message with ok button.
2. confirm() - displays the confirm dialog
box containing message with ok and
cancel button.
3. prompt() - displays a dialog box to get
input from the user.
4. open() - opens the new window.
5. close() - closes the current window.
History Object
60
The JavaScript history object represents an array of
URLs visited by the user. By using this object, you can
load previous, forward or any particular page.
Property of History object: Length - returns the
length of the history URLs.
Methods of History are:
1. forward() - loads the next page.
2. back() - loads the previous page.
3. go() - loads the given page number.
Examples: history.back();
//for previous page
history.forward(); //for next page
history.go(2); //
for next 2nd page
DOM vs. BOM
61
Document Object Model in JavaScript is the API
to access the elements inside the document. It
maps the entire Document into an hierarchy of
parent and child tree. Each node can hold number
of children element or can inherit to other parent
element in some or the other way.
Browser Object Model is a larger representation
of everything provided by the browser including the
current document, location, history, frames, and
any other functionality the browser may expose to
JavaScript. The Browser Object Model is not
standardized and can change based on different
DOM vs. BOM
62
JavaScript functions
63
function name()
{ //function definition
statements ;
...
Return value; //returning a value
}
Val= name(); // function calling
JS
function myFunction(str)
{ //function definition
alert("Hello!“+str);
alert("How are you?");
}
myFunction(name); // function calling with arguments
Functions
Functions should be defined in the
<head> of an HTML page, to ensure
that they are loaded first
The syntax for defining a function is:
function name(arg1, …, argN)
{ statements }
The function may contain return value;
statements
Any variables declared within the
function are local to it
The syntax for calling a function is just
name(arg1, …, argN)
Event-driven programming
65
Event-driven programming
66
A JavaScript can be executed when an
event occurs, like when a user clicks on
an HTML element.
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
Event-driven programming
67
Few commonly used events
are: onMouseOver
onBlur onMouseMove
onFocus onSubmit
onSelect onLoad
onUnload
onClick
onScroll
onDblClick
onDrag
onChange onResize
onKeyPress
onKeyDown
onKeyPress
Event-driven programming
68
you are used to programs start with a
main method (or implicit main like in
PHP)
JavaScript programs instead wait for user
actions called events and respond to
them
event-driven programming: writing
programs driven by user events
Let's write a page with a clickable button
that pops up a "Hello, World" window...
Buttons
69
<button>Click me!</button> HTML
button's text appears inside tag; can
also contain images
To make a responsive button or other UI
control:
1. choose the control (e.g. button) and event
(e.g. mouse 1. click) of interest
2. write a JavaScript function to run when
the event occurs
3. attach the function to the event on the
Event handlers
70
<element attributes onclick="function();">...
HTML
<button onclick="myFunction();">Click me!</button>
HTML
JavaScript functions can be set as event
handlers
when you interact with the element, the
function will execute
onclick is just one of many event HTML
attributes we'll use
but popping up an alert window is
disruptive and annoying
A JavaScript statement:
71
alert
alert(“Access Denied.");
JS
a JS command that pops up a dialog box
with a message
Popup boxes
72
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
73
THANK
YOU