Lecture 06 - Introduction to Java Script

advertisement
Lecture 7
Introduction to Java Script
Presented By
Dr. Shazzad Hosain
Asst. Prof. EECS, NSU
2
Introduction to Java Script I
Client-Side Programming
Lecture Content
What is JavaScript?
What a JavaScript can do?
JavaScript in HTML
Scripts in the head and body of a section
External JavaScript
Variable manipulation In JavaScript
Conditional and Iterative statements
User defined functions in JavaScript
Objects and array of Objects
Scripting Language
• a scripting language is a simple,
interpreted programming language
– scripts are embedded as plain text, interpreted by
application
– simpler execution model: don't need compiler or
development environment
– saves bandwidth: source code is downloaded, not compiled
executable
– platform-independence: code interpreted by any scriptenabled browser
– but: slower than compiled code, not as powerful/fullfeatured
3
Scripting Language
• JavaScript:
– the first Web scripting language, developed by Netscape in
1995
– syntactic similarities to Java/C++, but simpler, more
flexible in some respects, limited in others
– loose typing, dynamic variables, simple objects
• JScript:
– Microsoft version of JavaScript, introduced in 1996
– same core language, but some browser-specific differences
– fortunately, IE, Netscape, and Firefox can (mostly) handle
both JavaScript & JScript
– JavaScript 1.5 & JScript 5.0 cores conform to ECMAScript
standard
• VBScript:
– client-side scripting version of Microsoft Visual Basic
4
Common Scripting Tasks
• adding dynamic features to Web pages
– validation of form data (the most commonly used
application)
– image rollovers
– time-sensitive or random page elements
– handling cookies
• defining programs with Web interfaces
– utilize buttons, text boxes, clickable images,
prompts, etc
5
Common Scripting Tasks
• limitations of client-side scripting
– since script code is embedded in the page, it is
viewable to all
– for security reasons, scripts are limited in what they
can do
• e.g., can't access the client's hard drive
– since designed to run on any machine platform,
scripts do not contain platform specific commands
– script languages are not full-featured; slow
execution
• e.g., JavaScript objects are crude, not good for large
project development
6
7
What is JavaScript
• JavaScript is a scripting language - a scripting language
is a lightweight programming language;
• JavaScript was designed to add interactivity to HTML
pages;
• A JavaScript is lines of executable computer code which
is usually embedded directly in HTML pages;
• JavaScript is an interpreted language (means that
scripts execute without preliminary compilation);
• JavaScript is supported by all major browsers, like
Netscape and Internet Explorer.
Are Java and JavaScript the same?
Are Java and JavaScript the same?
• NO! Java and JavaScript two different languages;
• Java (developed by Sun Microsystems) is a
powerful and very complex programming language
- in the same category as C and C++.
8
What can a JavaScript do?
• JavaScript gives HTML designers a programming
tool:
– HTML authors are normally not programmers, but
JavaScript is a scripting language with a very simple
syntax!
– Almost anyone can put small "snippets" of code into HTML
pages;
• JavaScript can put dynamic text into an HTML page
- A JavaScript statement like this:
document.write("<h1>" + name + "</h1>")
can write a variable text into an HTML page ;
9
What can a JavaScript do? (cont’d)
• 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;
• JavaScript can be used to validate data - A
JavaScript can be used to validate form data before
it is submitted to a server, this will save the server
from extra processing.
10
JavaScript in HTML
• The HTML <script> tag is used to insert a
JavaScript into an HTML page.
• E.g.
<script>
...
</script>
11
JavaScript in HTML (Example)
• Start a script using the <script> tag;
• Use type attribute to define the language
<script type="text/javascript">
•JavaScript starts, the command for writing some
output to a page is
document.write("Hello World!");
• the <script> tag has to be closed </script>.
12
JavaScript in HTML (Example)
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
13
JavaScript in HTML (Example)
14
Ending Statements with a ( ; )
• With traditional programming languages,
like C++ and Java, each code statement
has to end with a semicolon (;) .
• Many programmers continue this habit
when writing JavaScript, but in general,
semicolons are optional! However,
semicolons are required if you want to put
more than one statement on a single line.
15
Where to put the JavaScript
Scripts in a page will be executed immediately while the page
loads into the browser. This is not always what we want.
Sometimes we want to execute a script when a page loads, other
times when a user triggers an event.
16
Scripts in the head of a section
Scripts to be executed when they are called, or when an event
is triggered, go in the head section.
When you place a script in the head section, you will ensure
that the script is loaded before anyone uses it.
17
Scripts in the head of a section
As an example consider:
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
18
Scripts in the body of a section
Scripts to be executed when the page loads go in the body to generate
content. E.g.:
<html>
<head>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>
19
Scripts in head and body
An unlimited number of scripts can be put in both the body and head
sections. E.g.:
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>
20
External JavaScripts
We can run the same script on several pages, without writing the script
on each and every page.
To do this we write a script in an external file, and save it with a .js
file extension, as myfile.js:
document.write("This script is external")
NOTE: External scripts -> no
<script> tag
21
External JavaScripts (cntd)
Now you can call this script, using the "src" attribute, from any of your
pages:
<html>
<head>
</head>
<body>
<script src=“myfile.js"></script>
</body>
</html>
Note: place the script at the right position.
22
Variables
• A variable is a "container" for information you
want to store.
• A variable's value can change during the script.
• You can refer to a variable by name to see its
value or to change its value.
• Rules for Variable names:
– Variable names are case sensitive
– They must begin with a letter or the underscore character.
23
Declare a Variable
• You can create a variable with the var
statement:
var strname = some value
• You can also create a variable without the var
statement:
strname = some value
24
Assign Values to Variables
• You assign a value to a variable like this:
var strCustomerName = “Smith“
or like this:
strCustomerName = “Smith“
• The variable name is on the left side of the
expression and the value you want to assign
to the variable is on the right. Now the
variable "strCustomerName" has the value
“Smith".
25
JavaScript Data Types & Variables
• JavaScript has only three primitive data types
String : "foo"
Number: 12
Boolean : true
<html>
<!–- CSC382
'howdy do'
"I said 'hi'."
3.14159
1.5E6
false
""
*Find info on Null, Undefined
-->
<head>
<title>Data Types and Variables</title>
</head>
<body>
<script type="text/javascript">
var x, y;
x= 1024;
y=x; x = “Hello World";
document.write("<p>x = " + y + "</p>");
document.write("<p>x = " + x + "</p>");
</script>
</body>
</html>
variable names are sequences of
letters, digits, and underscores that
start with a letter or an underscore
variables names are case-sensitive
you don't have to declare variables,
will be created the first time used,
but it’s better if you use var
statements
var message, pi=3.14159;
variables are loosely typed, can be
26
assigned different types of values
Conditional Statements
• Often in a program we want to perform
different actions for different decisions.
JavaScript has three conditional statements:
- if statement - use this statement if you want to
execute a set of code when a condition is true;
- if...else statement - use this statement if you want
to select one of two sets of lines to execute;
- switch statement - use this statement if you want
to select one of many sets of lines to execute
27
If condition
• Use if to test for a condition once.
• The syntax is:
if (boolean condition) {
Javascript code to be executed
}
28
If condition (cntd)
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time < 10)
{ document.write("Good morning!") }
</script>
29
If … else condition
• To execute some code if a condition is true and
another code if a condition is false, use the if...else
statement. The syntax is
if (condition)
{Javascript code}
else
{Javascript code for the else case}
• Javascript allows nested if blocks.
30
If … else condition (cntd)
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time < 10)
{ document.write("Good morning!") }
else { document.write("Good day!") }
</script>
31
Looping statement
Often, we want the same block of code to run a number of times.
JavaScript supports three looping statements:
- while - loops through a block of code while a
condition is true;
- do...while - loops through a block of code
once, and then repeats the loop while a
condition is true;
- for - run statements a specified number of
times.
32
Loops in JavaScript
while:
while (condition)
{code to be executed}
do-while:
do
{code to be executed}
while (condition)
for:
for (initialisation; condition; increment)
{code to be executed}
33
While loop example
Consider the code:
var num=0;
while (num < 12) {
document.write(num +”<br>”);
num = num + 1;
}
34
JavaScript Operators & Control Statements
<html>
<!–- CSC382 -->
<head>
<title>Folding Puzzle</title>
</head>
<body>
<script type="text/javascript">
distanceToSun = 93.3e6*5280*12;
thickness = .002;
foldCount = 0;
while (thickness < distanceToSun) {
thickness *= 2;
foldCount++;
}
document.write("Number of folds = "
+ foldCount);
</script>
</body>
</html>
standard C++/Java operators
& control statements are
provided in JavaScript
• +, -, *, /, %, ++, --, …
• ==, !=, <, >, <=, >=
• &&, ||, !,===,!==
• if-then, if-then-else, switch
• while, for, do-while, …
PUZZLE: Suppose you took a piece
of paper and folded it in half, then
in half again, and so on.
How many folds before the
thickness of the paper reaches
from the earth to the sun?
*Find more info on this subject
35
Functions
• Javascript has a large number of built-in
functions to perform a number of operations
like abs(x) to find the absolute value of x,
sqr(x) for the square of a number and so
on).
• On the other hand, the user is able to define
his own functions to perform any custom
operations.
36
37
Functions (cntd)
We can define a function by using the function statement.
The general form is :
function functionname(arg1,arg2,…,argn) {
//Javascript code goes
}
The return statement is used to return the value we want to the program.
38
Functions (cntd)
Consider the code:
function squarenumber(x){
//finds the square of a number
return x*x;
}
To use it, type var a = squarenumber(12);
39
Functions (cntd)
An alternative would be to use the Function() constructor:
var v = new Function(arg1,arg2,…,argn);
For example:
var z= new Function(“x”,”y”,”return x*y;”);
multiplies two numbers.
Argument 1
Argument 2
Function Body
40
Functions (cntd)
Finally, we can use function literals.
This is done via the statement
var f=function(arg1,…,argn) {statements};
e.g. the square of a number:
var f=function(x) {return x*x;}
Lifetime of variables
• Local variables i.e. variables declared within a
function can only be accessed within that
function. Exiting the function, the variable is
destroyed.
• Local variables with the same name can be
declared in different functions, as
each is
recognized only by the function in which it is
declared.
• A variable declared outside a function can be
accessed by all the functions on your page. The
lifetime of these variables starts when they are
declared, and ends when the page is closed.
41
Objects
Objects are composite data types, used to hold a number of properties.
E.g. a car has color, brand etc.
To set or retrieve properties of an object, we use either the dot notation
E.g.
car.color=“red”;
range = car.range;
Or associative arrays:
e.g.
car[“color”]=“red”;).
42
Creating Objects
• To create an object, use the new constructor
(this assumes that a function that defines the
object exists).
• As an example, consider the code
var a = new Square(12).
• We also need a constructor function to
initialize the object.
• Example:
function Square(x){ this.side=x; }
43
Creating Objects
Alternatively, we can create an object simply by assigning values to its properties (this
serves as its definition as well, if it has not been been defined previously). For
example:
var john={
name:”John Smith”,
age:35,
phone:12345678
};
44
Insert & Delete of Object Property
We can create a new property for the object simply by assigning a
value to it. As an example, consider:
john.salary = 12500;.
If you want to delete a property, use delete. (e.g. delete
john.phone;).
You need to be very careful in delete process as this will delete
the property for good.
45
Array Objects
The Array object is used to store a set of values in a
single variable name. Each value is an element of
the array has an associated index number.
You create an instance of the Array object with the
"new" keyword.
The following example creates two arrays, both of
three elements:
var family_names = new Array(3)
var family_names=new Array(“John","Jani","Stale")
46
Array Objects (cntd)
You can refer to a particular element in the array by using the
name of the array and the index number. The index number
starts at 0.
If you create an array with a single numeric parameter, you can
assign data to each of the elements in the array like this:
family_names[0]=“John“
family_names[1]="Jani“
family_names[2]="Stale"
47
Array Objects (cntd)
And the data can be retrieved by using the index number of the
particular array element you want, like this:
father=family_names[0]
mother=family_names[1]
48
Object Hierarchy
49
Further Reading
Javascript: The definitive guide, by D. Flanagan.
Mastering Javascript and Jscript by J. Jaworski.
Javascript for the World Wide Web by T. Negrino & D. Smith.
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/
www.w3schools.com/js/js_howto.asp
50
Download