lecture 7 introduction to java script presented by dr. shazzad hosain asst. prof. eecs, nsu

51
Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Upload: morgan-nelson

Post on 25-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Lecture 7Introduction to Java Script

Presented ByDr. Shazzad Hosain

Asst. Prof. EECS, NSU

Page 2: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

2Introduction 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

Page 3: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

3

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 script-

enabled browser– but: slower than compiled code, not as powerful/full-

featured

Page 4: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

4

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

Page 5: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

5

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

Page 6: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

6

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

Page 7: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

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.

Page 8: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

8

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++.

Page 9: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

9

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 ;

Page 10: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

10

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.

Page 11: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

11

JavaScript in HTML

• The HTML <script> tag is used to insert a JavaScript into an HTML page.

• E.g.

<script>

...

</script>

Page 12: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

12

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>. 

Page 13: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

13

JavaScript in HTML (Example)

<html>

<body>

<script type="text/javascript">

document.write("Hello World!")

</script>

</body>

</html>

Page 14: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

14

JavaScript in HTML (Example)

Page 15: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

15

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.

Page 16: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

16

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.

Page 17: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

17

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.

Page 18: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

18

Scripts in the head of a section

As an example consider:

<html><head> <script type="text/javascript"> some statements </script></head>

Page 19: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

19

Scripts in the body of a sectionScripts 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>

Page 20: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

20

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>

Page 21: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

21

External JavaScriptsWe 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

Page 22: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

22

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.

Page 23: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

23

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.

Page 24: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

24

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

Page 25: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

25

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".

Page 26: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

26

JavaScript Data Types & Variables• JavaScript has only three primitive data types

String : "foo" 'howdy do' "I said 'hi'." ""Number: 12 3.14159 1.5E6Boolean : true false *Find info on Null, Undefined

<html><!–- CSC382 -->

<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 assigned different types of values

Page 27: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

27

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

Page 28: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

28

If condition

• Use if to test for a condition once.

• The syntax is:

if (boolean condition) {

Javascript code to be executed

}

Page 29: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

29

If condition (cntd)

<script type="text/javascript">

var d = new Date()

var time = d.getHours()

if (time < 10)

{ document.write("Good morning!") }

</script>

Page 30: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

30

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.

Page 31: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

31

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>

Page 32: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

32

Looping statementOften, 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.

Page 33: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

33

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}

Page 34: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

34

While loop example

Consider the code:

var num=0;

while (num < 12) {

document.write(num +”<br>”);

num = num + 1;

}

Page 35: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

35

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

Page 36: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

36

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.

Page 37: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

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.

Page 38: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

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);

Page 39: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

39

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

Functions (cntd)

Page 40: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

40

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;}

Functions (cntd)

Page 41: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

41

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.

Page 42: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

42

ObjectsObjects 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”;).

Page 43: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

43

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; }

Page 44: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

44

Creating ObjectsAlternatively, 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

};

Page 45: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

45

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.

Page 46: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

46

Array ObjectsThe 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")

Page 47: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

47

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"

Page 48: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

48

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]

Page 49: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

49

Object Hierarchy

Page 50: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

50

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

Page 51: Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU