Vous êtes sur la page 1sur 75

Web Programming

JavaScript

The growth of the WWW has resulted


in a demand for dynamic and
interactive web sites.
There are many different kinds of
scripting languages JavaScript,
This lecture aims at offering in-depth
knowledge of JavaScript, discussing
the complexity of scripting and
studying various common examples.
2

Web Programming

Client Side Scripting


Scripts on the web can be executed either at the clientside or at the server side.
Client side scripts are those scripts which are sent to the
client from the server and executed on the clients
machine (by the web browser)

i.e the client side script code is sent from the server to the
client.

While in the case of server-side scripts, the script code is


executed on the server and the result (if any) is sent to
the client. [ covered in subsequent chapters ]
There are several client-side scripting languages:

JavaScript, and VBScript are the dominant ones


Web Programming

JavaScript
Is a client-side scripting language (lightweight
programming language)
An interpreted language

A JavaScript is simply lines of executable code

Supported by all major browsers


Different from the Java programming language !
Is case sensitive!

Web Programming

JavaScript Capabilities
Improve the user interface of a website
Make your site easier to navigate
Easily create pop-up alert, windows
Replace images on a page without reload the page
Form validation (Validate user input)
Put dynamic text in an HTML page
React to events (interactive)
Read and write HTML elements in an HTML page

Web Programming

JavaScript confusion
JavaScript

Java

Interpreted by the client-side


computer

Compiled on the server before


executed on the client machine

Dynamic binding, object references


are checked at runtime

Static binding, object references


must exist at compile time

No need to declare data types

Data types must be declared

Code is embedded in HTML

Code is not integrated in HTML

Limited by the browser functionality

Java applications are standalone

Can access browser objects

Java has no access to browser


objects

Web Programming

JavaScript (contd)
How to add JavaScript to an HTML page
anywhere in the HTML document

<body>

<script type=text/javascript>
document.write(hello);
</script>

</body>

Web Programming

A Simple Script
<html>
<head> <title>First JavaScript Page</title> </head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
<!-document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
-->
</script>
</body>
</html>

Web Programming

JavaScript (contd)

use the <script> tag


in the <head> element
<head>

<script type=text/javascript>
javascript code (functions)
</script>
or
<script type=text/javascript src=js_file.js></script>
</head>

Web Programming

JavaScript Source File


<script language=JavaScript
src=your_source_file.js></script>

10

SRC specifies the location of an external script


TYPE specifies the scripting language of the script
LANGUAGE specifies the scripting language of the
script
TYPE and LANGUAGE have a similar function, we use
LANGUAGE to specify the language used in the script
Web Programming

Hide JavaScript from incompatible


browsers
<script language=JavaScript>
<! begin hiding JavaScript
// single-line comment, /* */ multiple-line comment
End hiding JavaScript -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>

11

Not all browsers support JavaScript.


E.g. NN1, IE2, character-based lynx.
Web Programming

JavaScript

the output of JavaScript code is displayed as if directly entered


in HTML

<html>
<!-- Dave Reed

js01.html

2/01/04 -->

<head>
<title>JavaScript Page</title>
</head>
<body>
<script type="text/javascript">
// silly code to demonstrate output
document.write("Hello world!");
document.write("<p>How are <br />" +
"<i>you</i>?</p>");
</script>
<p>Here is some static text as well.
</p>
</body>
</html>

12

view page in browser

document.write displays text in page

text to be displayed can include HTML


tags
the tags are interpreted by the browser
when the text is displayed

as in C++/Java, statements end with ;

JavaScript comments similar to C++/Java


//

starts a single line comment

/**/ enclose multi-line comments


Web Programming

Using the alert() Method


<head>
<script language=JavaScript>
alert(An alert triggered by JavaScript);
</script>
</head>

You can use it to display textual information to


the user (simple and concise).
The user can simply click OK to close it.

13

Web Programming

Using the confirm() Method


<head>
<script language=JavaScript>
confirm(Are you happy with the class?);
</script>
</head>

14

This box is used to give the user a choice either


OK or Cancel.
It is very similar to the alert() method.

Web Programming

Using the prompt() Method


<head>
<script language=JavaScript>
prompt(What is your student id number?);
prompt(What is your name?,No name);
</script>
</head>

15

This is the only one that allows the user to type


in his own response to the specific question.
You can give a default value to avoid displaying
undefined.
Web Programming

Interactive pages using prompt


<html>
<!-- Dave Reed

js05.html

user interaction can take place


using prompt

2/01/04 -->

<head>
<title>Interactive page</title>
</head>
<body>
<script type="text/javascript">
userName = prompt("What is your name?", "");
userAge = prompt("Your age?", "");
userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) {
document.write(" Do your parents know " +
"you are online?");
}
</script>
<p>The rest of the page...
</body>
</html>

view page in browser


16

1st argument: the prompt


message that appears in the
dialog box
2nd argument: a default value
that will appear in the box (in
case the user enters nothing)
the function returns the value
entered by the user in the
dialog box (a string)
if value is a number, must use
parseFloat to convert

forms will provide a better interface


for interaction (later)
Web Programming

JavaScript (contd)

JavaScript ignores spaces, tabs, and newlines that


appear between tokens in programs
Semicolon (;) at the end of a statement is optional if each
statement is on a separate line

If more than one statement per line, separate them using (;)

Comments
// single line comment
/* multi line
comment */
17

Web Programming

JavaScript (contd)

Literals (constants)
12 // The number twelve
1.2 // The number one point two
"hello world" // A string of text
'Hi' // Another string
true // A Boolean value
false // The other Boolean value
null // Absence of an object

18

Web Programming

JavaScript (contd)

Identifiers

The first character must be a letter, an underscore (_), or a


dollar sign ($). Subsequent characters can be a letter, a digit, an
underscore, or a dollar sign.
Examples
i
distance_value
v13 _dummy
$str
_some_variable

19

Web Programming

JavaScript (contd)
Reserved words
break do if switch typeof case else in this var catch
false instanceof tHRow void continue finally new
true while default for null try with delete function
return

20

Web Programming

JavaScript (contd)

Datatypes and Variables

21

numbers : integer, floating point, hexadecimal, octal


strings
boolean
bojects
arrays

Web Programming

Data Types

JavaScript allows the same variable to contain different types


of data values.
Primitive data types

Composite data types (or Complex data types)

Number: integer & floating-point numbers


Boolean: logical values true or false
String: a sequence of alphanumeric characters
Object: a named collection of data
Array: a sequence of values

Special data types

22

Null: an initial value is assigned


Undefined: the variable has been created by not yet assigned a value

Web Programming

Numeric Data Types

It is an important part of any programming language for


doing arithmetic calculations.
JavaScript supports:

Integers: A positive or negative number with no decimal


places.

Floating-point numbers: usually written in exponential


notation.

23

Ranged from 253 to 253

3.1415, 2.0e11

Web Programming

Integer and Floating-point number


example
<script language=JavaScript>
var integerVar = 100;
var floatingPointVar = 3.0e10;
// floating-point number 30000000000
document.write(integerVar);
document.write(floatingPointVar);
</script>

24

The integer 100 and the number 30,000,000,000


will be appeared in the browser window.
Web Programming

Boolean value example


<head>
<script language=JavaScript>
var result;
result = (true*10 + false*7);
alert(true*10 + false*7 = , result);
</script>
</head>

The expression is converted to

25

(1*10 + 0*7) = 10

They are automatically converted.


Web Programming

Variables

JavaScript allows you to declare and use variables to


store values.
How to assign a name to a variable?

26

Include uppercase and lowercase letters


Digits from 0 through 9
The underscore _ and the dollar sign $
No space and punctuation characters
First character must be alphabetic letter or underscore
99Total?, 012345number?,
Case-sensitive
No reserved words or keywords

Web Programming

Which one is legal?


My_variable
$my_variable
1my_example
_my_variable
@my_variable
My_variable_example
++my_variable
%my_variable
#my_variable
~my_variable
myVariableExample
27

Legal

Illegal

Web Programming

Strings

A string variable can store a sequence of alphanumeric


characters, spaces and special characters.
String can also be enclosed in single quotation marks ()
or in double quotation marks ().
What is the data type of 100?

String but not number type

Pay attention to the special characters.

28

Web Programming

Strings example
<head>
<script language=JavaScript>
document.write(This is a string.);
document.write(This string contains quote.);
var myString = My testing string;
alert(myString);
</script>
</head>

29

Unlike Java and C, JavaScript does not have a single


character (char) data type.
Web Programming

What is an Object?

An object is a thing, anything, just as things in the


real world.

In the web browser, objects are the browser


window itself, forms, buttons, text boxes,
Methods are things that objects can do.

Cars can move, dogs can bark.


Window object can alert the user alert().

All objects have properties.

30

E.g. (cars, dogs, money, books, )

Cars have wheels, dogs have fur.


Browser has a name and version number.
Web Programming

Array

An Array contains a set of data represented by a single


variable name.
Arrays in JavaScript are represented by the Array Object,
we need to new Array() to construct this object.
The first element of the array is Array[0] until the last
one Array[i-1].
E.g. myArray = new Array(5)

31

We have myArray[0,1,2,3,4].

Web Programming

Array Example
<script language=JavaScript>
Car = new Array(3);
Car[0] = Ford;
Car[1] = Toyota;
Car[2] = Honda;
document.write(Car[0] + <br>);
document.write(Car[1] + <br>);
document.write(Car[2] + <br>);
</script>

You can also declare arrays with variable length.

32

arrayName = new Array();


Length = 0, allows automatic extension of the length.
Car[9] = Ford; Car[99] = Honda; Web Programming

Variable

Declaration

syntax:
var identifier [ = initial_value ]
ex. var x;
var first_name = Abebe;

33

Web Programming

<head>
<script language=JavaScript>
Variable declaration
var id;
id = prompt(What is your student id number?);
alert(id);
name = prompt(What is your name?,No name);
alert(name);
</script>
</head>

34

We should use var because it is more easy to keep


track of the variables.
Web Programming

Null & Undefined

An undefined value is returned when you attempt to


use a variable that has not been defined or you have
declared but you forgot to provide with a value.
Null refers to nothing
You can declare and define a variable as null if you want
absolutely nothing in it, but you just dont want it to be
undefined.

35

Web Programming

Null & Undefined example


<html>
<head>
<title> Null and Undefined example </title>
<script language=JavaScript>
var test1, test2 = null;
alert(No value assigned to the variable + test1);
alert(A null value was assigned + test2);
</script>
</head>
<body> </body>
</html>

36

Web Programming

JavaScript Special Characters


Character

37

\b
\f
\t
\n
\r
\\
\
\

Meaning
Backspace
Form feed
Horizontal tab
New line
Carriage return
Backslash
Single quote
Double quote
Web Programming

Expressions

It is a set of literals, variables, operators that merge and


evaluate to a single value.

Left_operand operator right_operand

By using different operators, you can create the following


expressions.

38

Arithmetic, logical
String and conditional expressions.

Web Programming

Operators

Arithmetic operators
Logical operators
Comparison operators
String operators
Bit-wise operators
Assignment operators
Conditional operators

39

Web Programming

Operators
Arithmetic Operators
Operator
+

Description
Addition

Subtraction

Multiplication

Division

Modulus (division remainder)

++

Increment

--

Decrement

40

Example
x=2
y=2
x+y
x=5
y=2
x-y
x=5
y=4
x*y
15/5
5/2
5%2
10%8
10%2
x=5
x++
x=5
x--

Web Programming

Result
4

20

3
2.5
1
2
0
x=6
x=4

Assignment operators
Used to assign values to variables

Operator

Description

Assigns the value of the right operand to the


left operand

Example

A=2

+=

Add the operands and assigns the result to the


left operand

A += 5

-=

Subtracts the operands and assigns the result


to the left operand

A -= 5

*=

Multiplies the operands and assigns the result


to the left operand

A *= 5

/=

Divides the left operands by the right operand


and assigns the result to the left operand

A /= 5

%=
41

Assigns the remainder to the left operand


Web Programming

A %= 2

Comparison operators
Used to compare two numerical values

Operator

Name

Description

Example

==

Equal

Perform type conversion before checking the


equality

5 == 5

===

Strictly equal

!=

Not equal

!==

Strictly not
equal

>

Greater than

<

Less than

>=

Greater than or
equal

true if left operand is greater than or equal


to the right operand

5 >= 2

<=

Less than or
equal

true if left operand is less than or equal to


the right operand

5 <= 2

42

No type conversion before testing


true when both operands are not equal
No type conversion before testing
nonequality

5 === 5
4 != 2
5 !== 5

true if left operand is greater than right


operand

2>5

true if left operand is less than right


operand

3<5

Web Programming

Logical operators

Used to perform Boolean operations on


Boolean operands

Operator
&&
||
!

43

Name

Description

Logical and Evaluate to true when


both operands are true
Logical or

Evaluate to true when


either operand is true

Logical not Evaluate to true when


the operand is false

Web Programming

Example
3>2 &&
5<2
3>1 ||
2>5
5 != 3

Strict Equality Operators

<script language=JavaScript>
var currentWord=75;
var currentValue=75;
var outcome1=(currentWord == currentValue);
var outcome2=(currentWord === currentValue);
alert(outcome1: + outcome1 + : outcome2: + outcome2);
</script>

44

Surprised that outcome1 is True!


JavaScript tries very hard to resolve numeric and
string differences.
Web Programming

String operator

JavaScript only supports one string operator for


joining two strings.

Operator

Name

Description

Return value

String
concatenation

Joins two strings

HelloWorld

<script language=JavaScript>
var myString = ;
myString = Hello + World;
alert(myString);
</script>
45

Web Programming

JavaScript (contd)

Conditional statements

if, if else
switch

conditional operator

46

var_name = (condition) ? true_value : false_value

Web Programming

if statement
if (condition) { statements; }

47

It is the main conditional statement in JavaScript.


The keyword if always appears in lowercase.
The condition yields a logical true or false value.
The condition is true, statements are executed.

Web Programming

if statement example

<script language=JavaScript>
var chr = ;

if (chr == A || chr == O) {
document.write(Vowel variable);
}
</script>
|| operator - increase the speed of the script

48

Web Programming

if else statement
if (condition) { statements; }
else { statements; }

49

You can include an else clause in an if statement


when you want to execute some statements if the
condition is false.

Web Programming

Ternary Shortcut (concise)


<script language=JavaScript>
If (3 > 2) {
alert(True);
} else {
alert(False);
}
(3 > 2) ? alert(True) : alert(False);
</script>
50

Substitute for a simple if/else


statement.
Web Programming

else if statement
if (condition) { statement; }
else if (condition) { statement; }
else { statement; }

51

Allows you to test for multiple expression for one


true value and executes a particular block of code.

Web Programming

switch statement
switch (expression) {
case label1:
statements; break;
default:
statements;
}

52

Allows you to merge several evaluation tests of the


same variable into a single block of statements.
Web Programming

switch statement example


<script language=JavaScript>
var chr;
chr = prompt(Pls enter a character in lowercase:,);
switch(chr){
case a :
alert(Vowel a); break;
case e :
alert(Vowel e); break;
default :
alert(Not a vowel);
}
</script>
53

Web Programming

Looping Statement

for Loops
for/in Loops
while Loops
do while Loops
break statement
continue statement

54

Web Programming

for statement
for (initial_expression; test_exp; change_exp)
{ statements; }

55

One of the most used and familiar loops is the


for loop.
It iterates through a sequence of statements for
a number of times controlled by a condition.
The change_exp determines how much has been
added or subtracted from the counter variable.
Web Programming

for statement example


<script language=JavaScript>
var counter;
for (counter = 1; counter <= 10; counter++)
{
document.write(counter*counter + );
}
</script>

56

Display the square of numbers


Output: 1 4 9 16 25 36 49 64 81 100
Web Programming

for/in statement
for (counter_variable in object)
{ statements; }

When the for/in statement is used, the counter


and termination are determined by the length of
the object.
The statement begins with 0 as the initial value
of the counter variable, terminates with all the
properties of the objects have been exhausted.

57

E.g. array

no more elements found


Web Programming

JavaScript For...In Statement


The for...in statement loops through the properties of an
object.
Syntax:

for(varaible in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed once
for each property

58

Web Programming

for/in statement example


<script language=JavaScript>
var book; (What is the difference if var book=;)
var booklist = new Array(Chinese, English, Jap);
for (var counter in booklist) {
book += booklist[counter] + ;
}
alert(book);
</script>

59

Web Programming

while statement
initial value declaration;
while (condition) {
statements;
increment/decrement statement;
}

60

The while loop begins with a termination condition and


keeps looping until the termination condition is met.
The counter variable is managed by the context of the
statements inside the curly braces.
Web Programming

While statement example

61

<html>
<head>
<title>While loop example</title>
<script language=JavaScript>
var counter = 100;
var numberlist = ;
while (counter > 0) {
numberlist += Number + counter + <br>;
counter -= 10;
}
document.write(numberlist);
</script> <body> </body>
</html>
Web Programming

do while statement
do {
statements;
counter increment/decrement;
} while (termination condition)

62

The do/while loop always executes statements in the


loop in the first iteration of the loop.
The termination condition is placed at the bottom
of the loop.

Web Programming

JavaScript (contd)
Functions

A function will be executed by an event or by a call to the


function
syntax:
function function_name( argument1, argument2, ){
statements
[return value]
}
calling:
[var_name = ] function_name(arg_list)
63

Web Programming

Example:
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
64

Web Programming

User-defined functions
function definitions are similar to C++/Java, except:

no return type for the function (since variables are loosely typed)
no types for parameters (since variables are loosely typed)
by-value parameter passing only (parameter gets copy of argument)

function isPrime(n)
// Assumes: n > 0
can limit variable scope
// Returns: true if n is prime, else false
{
if the first use of a variable is preceded
if (n < 2) {
return false;
with var, then that variable is local to
}
the function
else if (n == 2) {
return true;
}
for modularity, should make all
else {
variables in a function local
for (var i = 2; i <= Math.sqrt(n); i++)
{
if (n % i == 0) {
return false;
}
}
return true;
} 65
Web Programming
}

The return Statement

The return statement is used to specify the value that is returned from the function
<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
66

Web Programming

Javascript Objects

Everything" in JavaScript is an Object: a String, a Number, an Array, a


Function....
In addition, JavaScript allows you to define your own objects.
JavaScript has several built-in objects, like String, Date, Array, and more.
An object is just a special kind of data, with properties and methods.

67

Web Programming

Accessing Object Properties

Properties are the values associated with an object.


The syntax for accessing the property of an object is:
objectName.propertyName
This example uses the length property of the String
object to find the length of a string:

var message="Hello World!";


var x=message.length;

68

Web Programming

Accessing Objects Methods

Methods are the actions that can be performed on objects.


You can call a method with the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object, to
convert a text to uppercase:
var message="Hello world!";
var x=message.toUpperCase();

69

Web Programming

JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example:
var pi=3.14; // Written with decimals
var x=34;
// Written without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:

Example:
var y=123e5; // 12300000
var z=123e-5; // 0.00123
All JavaScript Numbers are 64-bit
JavaScript is not a typed language. Unlike many other programming languages, it does not
define different types of numbers, like integers, short, long, floating-point etc.
All numbers in JavaScript are stored as 64-bit (8-bytes) base 10, floating point numbers.

70

Web Programming

Octal and Hexadecimal


JavaScript interprets numeric constants as octal if they are preceded by a
zero, and as hexadecimal if they are preceded by a zero and x.
Example
var y=0377;
var z=0xFF;

71

Web Programming

The String object is used for storing and manipulating text.


JavaScript Strings

A string simply stores a series of characters like "John Doe".

A string can be any text inside quotes.You can use simple or double quotes:

Syntax
var txt = new String(string);
or more simply:
var txt = string;
Example
var carname="Volvo XC60";

You can access each character in a string with its position (index):

Example
var character=carname[7];

String indexes are zero-based, which means the first character is [0], the second is [1], and so on.

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
72

Web Programming

String Length
The length of a string (a string object) is found in the built in property
length:
Example
var txt="Hello World!";
document.write(txt.length);

Finding a String in a String

The indexOf() method returns the position (as a number) of the first found
occurrence of a specified text inside a string:

Example
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");

The method returns -1 if the specified text is not found.

73

Web Programming

<!DOCTYPE html>
<html>
<body>
<p id="p1">Click the button to locate where "locate" first occurs.</p>
<p id="p2">0</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str=document.getElementById("p1").innerHTML;
var n=str.indexOf("locate");
//20
document.getElementById("p2").innerHTML=n+1;
}
</script>
</body>
</html>

74

Web Programming

Matching Content
The match() method can be used to search for a matching content in a string
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>"); // world
document.write(str.match("World") + "<br>"); //Null
document.write(str.match("world!")); // world!
</script>
</body>
</html>

75

Web Programming

Vous aimerez peut-être aussi