1 javascript client-side dynamic documents. 2 javascript capabilities add content to a web page...

136
1 JavaScript Client-side dynamic documents

Upload: brenda-gibbs

Post on 29-Dec-2015

258 views

Category:

Documents


0 download

TRANSCRIPT

1

JavaScript

Client-side dynamic documents

2

JavaScript Capabilities

• Add content to a web page dynamically.

• Alter a web page in response to user actions.

• React to user events.

• Interact with frames.

• Manipulate HTTP cookies

3

JavaScript is not Java

• JavaScript is a very simple scripting JavaScript is a very simple scripting language.language.

• Syntax is similar to a subset of Java.Syntax is similar to a subset of Java.

• Interpreted language.Interpreted language.

• Uses objects, but doesn't really support Uses objects, but doesn't really support the creation of new object typesthe creation of new object types

4

Language Elements

• VariablesVariables

• LiteralsLiterals

• OperatorsOperators

• Control StructuresControl Structures

• ObjectsObjects

5

More JavaScript Basics

<script language=“JavaScript”> <script language=“JavaScript”> document.write(“Hello, World!”);document.write(“Hello, World!”);</script></script>

• We can put as many commands inside We can put as many commands inside of the <script> container as we like.of the <script> container as we like.

• The “write” method will write whatever The “write” method will write whatever data we want to the document, allowing data we want to the document, allowing it to appear on the screen.it to appear on the screen.

6

JavaScript in HTML Documents

• We can put JavaScript is either the We can put JavaScript is either the HEAD of BODY of a document.HEAD of BODY of a document.

• Even with a “write” command in the Even with a “write” command in the HEAD of the document, the text will still HEAD of the document, the text will still appear in the BODY of the document.appear in the BODY of the document.

7

Embedding HTML in JavaScript Output

• We can put as much (or as little) HTML We can put as much (or as little) HTML as we like in with our JavaScript.as we like in with our JavaScript.

• The HTML that we put in with our The HTML that we put in with our JavaScript will be used to mark up the JavaScript will be used to mark up the document.document.

• We must “print” the HTML elements – We must “print” the HTML elements – we cannot just “put” them around the we cannot just “put” them around the JavaScript commands.JavaScript commands.

8

Embedding (cont’d)

• YesYes::document.write (“<b>”);

document.write (“Hello, World!”);

document.write (“</b>”);

• NoNo::<b>

document.write (“Hello, World!”);

</b>

9

More JavaScript Basics…

• Although multiple “write()” commands Although multiple “write()” commands may be used, HTML will still ignore the may be used, HTML will still ignore the different lines and put the words different lines and put the words together.together.

• If we want to force a new line to start, we If we want to force a new line to start, we have to use <br>.have to use <br>.

• If we want a new paragraph, we have to If we want a new paragraph, we have to use <p>.use <p>.

10

Example

document.write(“Hello,”);document.write(“Hello,”);

document.write(“How are you?”);document.write(“How are you?”);

• This above text will appear all on one line. This above text will appear all on one line. If we want the text to be on different lines, If we want the text to be on different lines, we have to do the following:we have to do the following:

document.write(“Hello,”);document.write(“Hello,”);

document.write(“<br>How are you?”);document.write(“<br>How are you?”);

11

What is a Variable?

• A A variablevariable is a “named storage spot” is a “named storage spot” where we can store information. It is a where we can store information. It is a little like a box where we can little like a box where we can temporarily put information that we want temporarily put information that we want to use later on.to use later on.

• Variables are very useful when Variables are very useful when programming – they allow us to retrieve programming – they allow us to retrieve information from the user and use it at a information from the user and use it at a later point in time.later point in time.

12

Prompting For & Storing User Input

• In order to prompt the user for In order to prompt the user for information, we can use the “prompt()” information, we can use the “prompt()” function.function.

• We can store the result of the prompt() We can store the result of the prompt() function in a variable.function in a variable.

• The information entered by the user will The information entered by the user will be stored in the variable name for use be stored in the variable name for use at a later point in time. at a later point in time.

13

Prompting and Storing (cont’d)• The order in how we do this is The order in how we do this is

important. important. • First, we have to create the variable. First, we have to create the variable.

We can do this using the following We can do this using the following command:command:var name;

• Where “var” tells us that it is a variable Where “var” tells us that it is a variable and “name” is the name of the variable. and “name” is the name of the variable. There is now a spot in the computer that There is now a spot in the computer that is going to hold information, and that is going to hold information, and that spot is called “name”spot is called “name”

14

Prompting and Storing (cont’d)

• Once we have declared the variable, we Once we have declared the variable, we can prompt the user for information and can prompt the user for information and store it in the variable:store it in the variable:name=prompt(“Enter your name.”);

• This will take information from the user This will take information from the user and will store it in the variable “name”. and will store it in the variable “name”. We will be able to access the variable at We will be able to access the variable at a later point in time to use the a later point in time to use the information retrieved from the user.information retrieved from the user.

15

Using Variable to Retrieve Info

• If we want to use information stored in a If we want to use information stored in a variable, all we have to do is use the variable variable, all we have to do is use the variable where we want the data.where we want the data.document.write(name);

• Note that we do not use quotes around Note that we do not use quotes around namename when using the variable. If we used quotes, when using the variable. If we used quotes, the computer would think that we wanted to the computer would think that we wanted to print the word “name” on the screen. By just print the word “name” on the screen. By just using using namename, it uses the value stored in that , it uses the value stored in that variable.variable.

16

An Example

<script language=“JavaScript”><script language=“JavaScript”>

var name;var name;

name=prompt(“Please enter your name”);name=prompt(“Please enter your name”);

document.write(“Hello, ”);document.write(“Hello, ”);

document.write(name);document.write(name);

</script></script>

17

More Prompting

• When we use the “prompt()” function, When we use the “prompt()” function, we can also enter default information we can also enter default information into the field. This is done by using a into the field. This is done by using a second parameter.second parameter.

prompt(“Question”, “default prompt(“Question”, “default text”);text”);

• The “default text” will appear in the The “default text” will appear in the editable field where the user is editable field where the user is supposed to put their data.supposed to put their data.

18

Multiple Variables

• We can use multiple variables when We can use multiple variables when using JavaScript. This means that we using JavaScript. This means that we are able to handle multiple different are able to handle multiple different inputs from the user.inputs from the user.

• Once we have access to the different Once we have access to the different variables, we can use them how we variables, we can use them how we wish. wish.

• It is important to point out that a variable It is important to point out that a variable can be use as many times as needed.can be use as many times as needed.

19

Multiple Variable Declaration

• We can declare multiple variables two We can declare multiple variables two different ways:different ways:– One per line:

• var first_name;var first_name;• var last_name;var last_name;

– Both on the same line:• var first_name, last_name;var first_name, last_name;

20

Retrieving Multiple Pieces of Data

var first_name, last_name;var first_name, last_name;

first_name=prompt(“First name?”);first_name=prompt(“First name?”);

last_name=prompt(“Last name?”);last_name=prompt(“Last name?”);

document.write(first_name);document.write(first_name);

document.write(“ “);document.write(“ “);

document.write(last_name);document.write(last_name);

21

Variable Naming

• We can assign many different names We can assign many different names for variables, helping us to keep track of for variables, helping us to keep track of what is actually stored in the variable.what is actually stored in the variable.

• It is important to choose appropriate It is important to choose appropriate names, as that will help us to keep track names, as that will help us to keep track of the data.of the data.

• There are a few naming rules that we There are a few naming rules that we have to follow.have to follow.

22

Variable Naming Rules

• Names can be composed of:Names can be composed of:– letters – numbers – the underscore.

• Names cannot:Names cannot:– have spaces or special characters– start with a number

• Names are also case sensitive!Names are also case sensitive!

23

Examples

• var first_name;var first_name;

• var first name;var first name;

• var FirstName;var FirstName;

• var firstname;var firstname;

• var name1;var name1;

• var 1name;var 1name;

• var first&name;var first&name;

24

Storing Strings

• We have stored words in the variables We have stored words in the variables such as our first name and our last such as our first name and our last name.name.

• These pieces of information were These pieces of information were collections of characters. We refer to collections of characters. We refer to these collections of characters as these collections of characters as stringsstrings. .

• A A stringstring is any collection of characters is any collection of characters that we find on the keyboard.that we find on the keyboard.

25

Storing Numbers

• We can also store numbers in our We can also store numbers in our variables. variables.

• In order to store numbers, we have to In order to store numbers, we have to tell the computer (using JavaScript) that tell the computer (using JavaScript) that the data stored in the variable is a the data stored in the variable is a number and not a string. number and not a string.

• If we do not tell the computer that we If we do not tell the computer that we have a number, it will treat the digits like have a number, it will treat the digits like a string.a string.

26

Value Representation• In order to help us understand the In order to help us understand the

difference between a string value and a difference between a string value and a numeric value, we usually show our numeric value, we usually show our strings surrounded by quotes (“).strings surrounded by quotes (“).

• Quotes are often used to represent Quotes are often used to represent strings.strings.

• number = “45”; number = “45”; a “string” of two a “string” of two digitsdigits

• number = 45; number = 45; the integer 45 the integer 45

27

Reading Input

• When we prompt for information from When we prompt for information from the user, it is always stored as a string.the user, it is always stored as a string.

• Some math operations might work with Some math operations might work with the variables, but not all.the variables, but not all.

• When in doubt, the computer will treat When in doubt, the computer will treat any input as a string. any input as a string.

• We can convert string variables to We can convert string variables to numeric variables.numeric variables.

28

Number Types

• There are two different types of There are two different types of numbers: numbers: floatsfloats and and intsints..

• A A floatfloat is a number with a decimal point is a number with a decimal point (a (a floating point numberfloating point number).).

• An An intint is a number without a decimal is a number without a decimal point point (an integer(an integer))..

• If we want to convert a string to a If we want to convert a string to a number, we have to decide which number, we have to decide which numeric type we want to convert it to. numeric type we want to convert it to.

29

Floats

• In order to convert strings to floats, we use a In order to convert strings to floats, we use a function called function called parseFloat()parseFloat()

• We We parseparse the number from the string the number from the string variable. This removes the number from the variable. This removes the number from the string, storing it as a numeric value.string, storing it as a numeric value.

• The parse function will even remove extra The parse function will even remove extra characters that may happen to follow the characters that may happen to follow the floating point number in the prompt field. It will floating point number in the prompt field. It will not remove characters that appear before the not remove characters that appear before the first character.first character.

30

parseFloat()

var x, y, answer;var x, y, answer;

x = prompt(“Enter a number”);x = prompt(“Enter a number”);

x = parseFloat(x);x = parseFloat(x);

y = prompt(“Enter a second number”);y = prompt(“Enter a second number”);

y = parseFloat(y);y = parseFloat(y);

answer = x + y;answer = x + y;

document.write(x, “ + ”, y, “ = “, answer);document.write(x, “ + ”, y, “ = “, answer);

31

Explanation

• We can use the values stored in We can use the values stored in xx and and yy to to create a new value to store in create a new value to store in answeranswer. .

• We can use all three variable again to write We can use all three variable again to write information to the screen. information to the screen.

• When using the When using the writewrite command, we have the command, we have the option of including multiple items to be option of including multiple items to be written, as long as they are separated by a written, as long as they are separated by a comma.comma.

• We have to include the appropriate spacing We have to include the appropriate spacing for the output to look correct.for the output to look correct.

32

What about ints?

• We can get an integer from a string by We can get an integer from a string by using the using the parseIntparseInt function. function.

• This function will retrieve an This function will retrieve an intint from the from the entered text. entered text.

• As with the parseFloat function, trailing As with the parseFloat function, trailing letters will be removed, while leading letters will be removed, while leading letters will cause an error.letters will cause an error.

• parseIntparseInt will also remove anything to will also remove anything to the right of the decimal point.the right of the decimal point.

33

parseInt vs. parseFloat

• If you enter 4.3f as the value into the If you enter 4.3f as the value into the prompt, then “4.3f” will be stored in the prompt, then “4.3f” will be stored in the variable. variable.

• If we use parseFloat, we will end up If we use parseFloat, we will end up with the variable value of 4.3with the variable value of 4.3

• If we use parseInt, we will end up with If we use parseInt, we will end up with the variable value of 4the variable value of 4

34

What about other math operations?

• subtraction “-” works finesubtraction “-” works fine

• division “/” works finedivision “/” works fine

• multiplication “*” works finemultiplication “*” works fine

• We can use these functions to do basic We can use these functions to do basic math on our web pages.math on our web pages.

35

What about “Strings”?

• We can perform math operations on We can perform math operations on variables that are numbers, but do variables that are numbers, but do these math operations work on strings?these math operations work on strings?

• Do any of the math operations work with Do any of the math operations work with strings?strings?

• If math operations don’t work on strings, If math operations don’t work on strings, what results do we get to tell us that we what results do we get to tell us that we have an error?have an error?

36

String Operations

• ““+” will concatenate two strings +” will concatenate two strings together, so if x=“bob” and y=“bill”, together, so if x=“bob” and y=“bill”, x+y=“bobbill”x+y=“bobbill”

• ““-”, “*”, and “/” will all fail. The result on -”, “*”, and “/” will all fail. The result on the screen for these equations will be the screen for these equations will be “NaN”.“NaN”.

• ““NaN” stands for “Not a Number”, as the NaN” stands for “Not a Number”, as the result from these “equations” is not a result from these “equations” is not a valid number. valid number.

37

Errors

• JavaScript will give us errors if we try to JavaScript will give us errors if we try to do something that it doesn’t like.do something that it doesn’t like.

• The errors may involve something The errors may involve something printed to the screen, or it may involve printed to the screen, or it may involve nothing printed to the screen.nothing printed to the screen.

• We will need to be able to figure out We will need to be able to figure out where the errors are and fix them.where the errors are and fix them.

38

Errors (cont’d)

• My personal suggestion: My personal suggestion: – write your JavaScript in fairly small, logical

sections– test each section to make sure that it works– once one section works, move to the next

section

• If an error is introduced, then you will If an error is introduced, then you will know which lines of code have caused know which lines of code have caused the problem.the problem.

39

Errors (cont’d)

• If you are unsure of how some piece of If you are unsure of how some piece of JavaScript works:JavaScript works:– you can look it up online to see how it works– you can write a small program and see how

it works

• By writing code to see how things work, By writing code to see how things work, you can answer your own questions you can answer your own questions quickly about JavaScript. It is a good quickly about JavaScript. It is a good way to learn how to program.way to learn how to program.

40

Error Types

• There are three different types of errors:There are three different types of errors:– syntax errors– logic errors– user errors

• We must be able to determine the We must be able to determine the difference between these errors in order difference between these errors in order to be able to correct them.to be able to correct them.

41

Syntax Errors

• A A syntax errorsyntax error is an error created by is an error created by incorrectly typing in JavaScript incorrectly typing in JavaScript statements.statements.

• An example would be:An example would be:– write.document(“Hello, World!);

• The missing quote will cause this The missing quote will cause this statement to fail. statement to fail.

• Such statements may simply not work Such statements may simply not work in our browsers.in our browsers.

42

Logic Errors

• Logic errors Logic errors occur when we make a mistake occur when we make a mistake in the logic of our statements.in the logic of our statements.

• For example:For example:number = 50 + 100 / 2

number = (50 + 100) / 2

• If we really mean the second one and we type If we really mean the second one and we type in the first one, we will have a logic error. in the first one, we will have a logic error.

• We have to be careful that the logic of the We have to be careful that the logic of the program is correct.program is correct.

43

User Errors

• User errorsUser errors are caused when the user are caused when the user enters in the wrong information. enters in the wrong information.

• If we expect the user to enter in a If we expect the user to enter in a number and a letter is entered instead, number and a letter is entered instead, then this can cause lots of problems. then this can cause lots of problems.

• There are ways that we can double-There are ways that we can double-check to see what the user has typed check to see what the user has typed in, helping to avoid this problem. We will in, helping to avoid this problem. We will learn of these methods later.learn of these methods later.

44

Writing Readable Code

• Once again, writing readable code is Once again, writing readable code is important. The easier it is to read, the important. The easier it is to read, the easier it will be to understand and to easier it will be to understand and to find errors.find errors.

• We are able to write our programs in a We are able to write our programs in a couple of different ways. We should couple of different ways. We should choose the method that makes the code choose the method that makes the code as easy to read as possible.as easy to read as possible.

45

Variables & Statements

• We must declare our variables before We must declare our variables before we use them in our program.we use them in our program.

• It doesn’t make a difference where we It doesn’t make a difference where we declare our variables, as long as they declare our variables, as long as they are declared before they are used. are declared before they are used.

• In order to make our code more In order to make our code more readable, we should declare all of our readable, we should declare all of our variables at the top of our program. It variables at the top of our program. It makes the code easier to read.makes the code easier to read.

46

Variables & Statements

program

variable declarations

programming statements

47

JavaScript Variables

• Un-typed!Un-typed!

• Can be declared with var keyword:Can be declared with var keyword:var foo;

• Can be created automatically by Can be created automatically by assigning a value:assigning a value:foo=1; blah="Hi Dave";

48

Variables (cont.)

• Using Using varvar to declare a variable results to declare a variable results in a in a locallocal variable (inside a function). variable (inside a function).

• If you don't use If you don't use varvar – the variable is a – the variable is a global variable.global variable.

49

Literals

• The typical bunch:The typical bunch:– Numbers 17 123.45– Strings "Hello Dave"– Boolean: true false– Arrays: [1,"Hi Dave",17.234]

Arrays can hold anything!

50

Operators

• Arithmetic, comparison, assignment, Arithmetic, comparison, assignment, bitwise, boolean (pretty much just like bitwise, boolean (pretty much just like C).C).

+ - * / % ++ -- == != > < + - * / % ++ -- == != > <

&& || ! & | << >>&& || ! & | << >>

51

Control Structures

• Again – pretty much just like C:Again – pretty much just like C:if if-else ?: switchif if-else ?: switch

for while do-whilefor while do-while

• And a few not in CAnd a few not in Cfor (var in object) for (var in object)

with (object)with (object)

52

Objects

• An An objectobject is a definable thing, such as is a definable thing, such as a car. Objects are allowed to have other a car. Objects are allowed to have other objects – a car can have a trunk, the objects – a car can have a trunk, the trunk may have a spare tire.trunk may have a spare tire.

• Since JavaScript is an Since JavaScript is an object-orientedobject-oriented language, we use language, we use dot syntaxdot syntax to specify to specify the relationship between objects.the relationship between objects.

• car.trunk.sparetirecar.trunk.sparetire

53

Objects

• Objects have attributes and methods.Objects have attributes and methods.

• Many pre-defined objects and object Many pre-defined objects and object types.types.

• Using objects follows the syntax of C+Using objects follows the syntax of C++/Java:+/Java:objectname.attributename

objectname.methodname()

54

Instance

• An An instanceinstance is a particular incarnation is a particular incarnation of an object.of an object.

• For example, I could represent students For example, I could represent students in the class using in the class using class.studentclass.student, where , where an instance of the student object would an instance of the student object would be a particular person.be a particular person.

• An instance of an object has all of the An instance of an object has all of the same attributes as that object.same attributes as that object.

55

Objects

• In real life, and object is a tangible In real life, and object is a tangible “thing” – a car, a bike or a computer.“thing” – a car, a bike or a computer.

• As we can see, we like to name objects As we can see, we like to name objects so that we can talk about them.so that we can talk about them.

• The object name doesn’t define the The object name doesn’t define the object, but it acts as more of a reference object, but it acts as more of a reference to the object itself. to the object itself.

56

Objects (cont’d)

• When programming, we use “objects” When programming, we use “objects” as a reference name for information that as a reference name for information that we want to store. we want to store.

• We use programming objects to store We use programming objects to store information about real-life objects.information about real-life objects.

• We store object data by storing We store object data by storing information about the individual information about the individual attributes or properties of the object in attributes or properties of the object in question.question.

57

Object Information• For example, if we have a green For example, if we have a green

bowling ball that weighs 3kgs, we know bowling ball that weighs 3kgs, we know that:that:– the bowling ball color is green– the bowling ball shape is round– the bowling ball weight is 3kgs

• In each of these cases, we are In each of these cases, we are associating an associating an attributeattribute with a piece of with a piece of data describing that attributedata describing that attribute..

58

Creating an Object

• In JavaScript, we can create an Object In JavaScript, we can create an Object using a function. In this case, we can using a function. In this case, we can create a bowling ball object:create a bowling ball object:var bball = new Object();

• This code creates a new object called This code creates a new object called bballbball..

• The “new Object()” function is called a The “new Object()” function is called a constructor functionconstructor function because it is used because it is used to construct a new object.to construct a new object.

59

Storing Object Information

• If we have an object called If we have an object called bballbball, we , we can store information about that object:can store information about that object:bball.color = “blue”;

bball.shape = “round”;

bball.weight = “3”;

bball.holes = “true”;

• We can store as much information as We can store as much information as we want about bowling balls. we want about bowling balls.

60

Object Information

• We associate the properties of the We associate the properties of the object with the object using a “.”object with the object using a “.”

• This allows us to associate the This allows us to associate the parameter to a particular object.parameter to a particular object.

• For example, we could easily store the For example, we could easily store the color of multiple different objects. Using color of multiple different objects. Using the object name will help us keep track the object name will help us keep track of the information.of the information.

61

Object Info (cont’d)

• bball.color=“green”;bball.color=“green”;• car.color=“red”;car.color=“red”;• If we were to say:If we were to say:

– document.write(color);, we wouldn’t know which color to print out.

• Instead, we can refer to the information Instead, we can refer to the information based on the object: based on the object: – document.write(bball.color);– document.write(car.color);

62

Object Attributes

• We can add as many attributes to an We can add as many attributes to an object as we like. object as we like.

• It is advisable to keep the number of It is advisable to keep the number of attributes to the minimum needed.attributes to the minimum needed.

• We should also declare all of the We should also declare all of the attributes in the same location, making it attributes in the same location, making it easier to keep track of them. easier to keep track of them.

63

Primitive Types

• Considering that an object is an new Considering that an object is an new type of variable, we can now refer to type of variable, we can now refer to ordinary variables as ordinary variables as primitive typesprimitive types. .

• A primitive type is a one of the regular A primitive type is a one of the regular variables that we can store.variables that we can store.

• There are three There are three primary primitive primary primitive typestypes – numbers, strings and Booleans. – numbers, strings and Booleans.

64

Compound Objects

• A A compound objectcompound object is an object where is an object where some of the attributes are other objects.some of the attributes are other objects.

• For example, one attribute of a For example, one attribute of a personperson object might be their name.object might be their name.

• namename itself can also be an object, as it itself can also be an object, as it can be comprised of a first, middle and can be comprised of a first, middle and last name.last name.

• In this case, the object In this case, the object namename is an is an attribute of the object attribute of the object personperson..

65

Compound Objects (cont’d)

Person

first

middle

last

Name

Age

parent child

66

Using Compound Objects

• We can use compound objects in the We can use compound objects in the same way that we used variables.same way that we used variables.

• The advantage of compound objects The advantage of compound objects falls with the ability to logically manage falls with the ability to logically manage the object.the object.

• We are able to store all of our related We are able to store all of our related information in a logical object.information in a logical object.

67

More Objects

• The The documentdocument object is a compound object is a compound object.object.

• The document object is part of the The document object is part of the larger larger windowwindow object. Each of these object. Each of these objects has attributes that we can objects has attributes that we can access.access.

68

The Window Object

• window.closed (Boolean)window.closed (Boolean)

• window.location (String)window.location (String)

• window.history.length (Number)window.history.length (Number)

69

The document Object

• The document object is special in the The document object is special in the window, so there is no need to specify window, so there is no need to specify the parent “window” object. the parent “window” object.

• This allows us to use This allows us to use “document.bgColor” instead of “document.bgColor” instead of “window.document.bgColor”.“window.document.bgColor”.

• There are many other document There are many other document attributes that we can access.attributes that we can access.

70

document attributes

• document.bgColor (String)document.bgColor (String)

• document.fgColor (String)document.fgColor (String)

• document.URL (String)document.URL (String)

• document.lastModified (String)document.lastModified (String)

• document.linkColor (String)document.linkColor (String)

• document.vlinkColor (String)document.vlinkColor (String)

71

Object Methods

• A A method method is a function an object can use to is a function an object can use to perform various tasks.perform various tasks.

• We have already seen an object method – We have already seen an object method – the the writewrite method associated with the method associated with the documentdocument object. object.

• The The writewrite method is used to tell the method is used to tell the document object to add some information to document object to add some information to the page.the page.

• This is why we say This is why we say document.write(“foo”);document.write(“foo”);

72

Object Methods (cont’d)

• Methods are a powerful method of Methods are a powerful method of modifying objects.modifying objects.

• Creating methods for objects that we Creating methods for objects that we have created is out of the scope of this have created is out of the scope of this course, but we will take advantage of course, but we will take advantage of those methods available to us from the those methods available to us from the window, document and other objects.window, document and other objects.

73

window.confirm()

• The The confirm()confirm() method of the window method of the window object will ask the user a question and object will ask the user a question and get a result – either get a result – either truetrue or or falsefalse, , depending on which button they push.depending on which button they push.

• We can store the results of the question We can store the results of the question in a variable. We can use the variable in a variable. We can use the variable later in the program to perform some later in the program to perform some action.action.

74

Examplevar question;var question;question = window.confirm(“This is a question question = window.confirm(“This is a question

where you have to answer OK or Cancel. OK is where you have to answer OK or Cancel. OK is true, Cancel is false. Do you understand?”);true, Cancel is false. Do you understand?”);

if (question){if (question){document.write(“You understood.”);document.write(“You understood.”);

}}else{else{ document.write(“You didn’t understand.”);document.write(“You didn’t understand.”);}}

75

window.location

• window.locationwindow.location is responsible for is responsible for telling the window to load a new telling the window to load a new webpage.webpage.

• If we say If we say window.location=http://www.csuhayward.ewindow.location=http://www.csuhayward.edu,du, we will be transported to the we will be transported to the Hayward homepage.Hayward homepage.

76

window.history

• We can also use the window history to We can also use the window history to go back to previous webpages.go back to previous webpages.

• For example, if we want to bring the For example, if we want to bring the user back to the page they just arrived user back to the page they just arrived from, we can usefrom, we can use window.history.go(- window.history.go(-1);1); to bring them back one page. We to bring them back one page. We can go back as many pages as we like.can go back as many pages as we like.

77

Properties

• Object can have properties. These Object can have properties. These properties are responsible for identifying properties are responsible for identifying and storing information about the object.and storing information about the object.

• For example, in the example of For example, in the example of class.studentclass.student, each instance of , each instance of studentstudent would have a property called would have a property called namename. .

• We can access the property using the We can access the property using the dot syntax for dot syntax for class.student.nameclass.student.name

78

Values• We can set the values of object We can set the values of object

properties for instances of an object.properties for instances of an object.

• In our student example, we can set the In our student example, we can set the name of the student in the following name of the student in the following way:way:– class.student.name = “Frank”;

• Likewise, we can apply this to our Likewise, we can apply this to our document object:document object:– window.document.bgColor=“red”;

79

Accessing Values...

• If we include an image in our webpage and If we include an image in our webpage and give it a name, we can access it as a give it a name, we can access it as a property.property.

• <img src=“image.jpg” <img src=“image.jpg” name=“testPic” alt=“picture”>name=“testPic” alt=“picture”>

can be accessed by:can be accessed by:• document.testPic.src=“image.jpg”document.testPic.src=“image.jpg”

80

Accessing Values…

• Likewise, if we set the background color Likewise, if we set the background color of our webpage to grey using:of our webpage to grey using:

<body bgColor=“grey”><body bgColor=“grey”>

• We can also access that same property We can also access that same property using:using:

document.bgColor=“grey”document.bgColor=“grey”

81

Events

• In real life, objects can encounter In real life, objects can encounter events.events.

• An event is some action that has An event is some action that has happened. happened.

• If we can identify an event that may If we can identify an event that may happen to a webpage, we can watch for happen to a webpage, we can watch for that event to happen.that event to happen.

• One example would be to watch where One example would be to watch where the mouse is placed on the screen.the mouse is placed on the screen.

82

Event Handlers

• When we see an event happen, we When we see an event happen, we have to have to handlehandle the event. the event.

• One such event is One such event is mouseovermouseover, when , when the mouse is placed over an object in the mouse is placed over an object in the webpage. the webpage.

• This event can trigger an action, such This event can trigger an action, such as changing the picture that the mouse as changing the picture that the mouse is over.is over.

83

Mouseover Event

• Our Our event handlerevent handler is responsible to doing is responsible to doing something when the event has happened.something when the event has happened.

<a href=“#” <a href=“#”

onmouseover=“document.bgColor=‘green’;”> onmouseover=“document.bgColor=‘green’;”>

This is some text</a>This is some text</a>

• This will change the background color to This will change the background color to green when we put the mouse over the link.green when we put the mouse over the link.

84

onmouseout event

• We can also make things happen when We can also make things happen when the mouse is removed from the object the mouse is removed from the object (like when the mouse is removed from (like when the mouse is removed from on top of the link or picture).on top of the link or picture).

• This is known as the “onmouseout” This is known as the “onmouseout” event, and works in the same way.event, and works in the same way.

• There are other mouse events that we There are other mouse events that we will talk about later…will talk about later…

85

Variables

• We have already seen some variables We have already seen some variables used in our simple programs.used in our simple programs.

• We can set the value of a variable to We can set the value of a variable to whatever we want, and we can use the whatever we want, and we can use the variable wherever we would use the variable wherever we would use the value.value.

• Variables can be reused as many times Variables can be reused as many times as we want in a program.as we want in a program.

86

Arrays

• An array is just an An array is just an orderedordered collection of collection of data.data.

• If we want to store 10 pieces of similar If we want to store 10 pieces of similar information, an array is easier than information, an array is easier than coming up with 10 unique variable coming up with 10 unique variable names.names.

• Arrays are Arrays are indexedindexed with a number. with a number.var pets = new Array();var pets = new Array();pets[0] = “Fluffy”pets[0] = “Fluffy”pets[1] = “Sparky”pets[1] = “Sparky”

87

Arrays (cont’d)• Arrays usually start at 0 and go from Arrays usually start at 0 and go from

there.there.

• Some programmers like to start their Some programmers like to start their arrays at 1 as they believe that this is arrays at 1 as they believe that this is “more natural” and easier to “more natural” and easier to understand.understand.

• As long as you are consistent, it doesn’t As long as you are consistent, it doesn’t really make a difference (although I do really make a difference (although I do prefer to start arrays at 0)prefer to start arrays at 0)

88

Methods• Methods are Methods are actionsactions that are that are

associated with objects. These actions associated with objects. These actions are often triggered by events or called in are often triggered by events or called in the middle of a program.the middle of a program.

• For example, the For example, the documentdocument object has object has a method called a method called writewrite which takes care which takes care of putting information to the browser.of putting information to the browser.

• We call the method using the dot We call the method using the dot notation – notation – document.write(“text”);document.write(“text”);

89

Functions

• A A functionfunction is a group of statements that is a group of statements that have been collected together to perform have been collected together to perform a specific task.a specific task.

• Functions are grouped in such a way Functions are grouped in such a way that they can be reused many times in a that they can be reused many times in a single program.single program.

• We can “call” a function in the same We can “call” a function in the same way that we would call a method, just by way that we would call a method, just by using the function name.using the function name.

90

Array Objects

• Arrays are supported as objects.Arrays are supported as objects.

• Attribute Attribute lengthlength

• Methods include:Methods include:concat join pop push reverse sort

91

Array example code

var a = [8,7,6,5];var a = [8,7,6,5];

for (i=0;i<a.length;i++)for (i=0;i<a.length;i++)

a[i] += 2;a[i] += 2;

b = a.reverse();b = a.reverse();

92

Many other pre-defined object types

• String: manipulation methods• Math: trig, log, random numbers• Date: date conversions• RegExp: regular expressions• Number: limits, conversion to string

93

Predefined Objects

• JavaScript also includes some objects that are automatically created for you (always available).– document– navigator– screen– window

94

The document object

• Many attributes of the current document are available via the document object:

Title Referrer

URL Images

Forms Links

Colors

95

document methods

• document.write() like a print statement – the output goes into the HTML document.

document.write("My title is" + document.title);

string concatenation!

96

JavaScript Example<HEAD><TITLE>JavaScript is fun!</TITLE></HEAD><BODY><H3>I am a web page and here is my name:</H3>

<SCRIPT>document.write(document.title);</SCRIPT><HR>

<HEAD><TITLE>JavaScript is fun!</TITLE></HEAD><BODY><H3>I am a web page and here is my name:</H3>

<SCRIPT>document.write(document.title);</SCRIPT><HR>

97

JavaScript andHTML Comments<SCRIPT><SCRIPT>

<!--<!--

document.write("Hi Dave");document.write("Hi Dave");

document.bgColor="BLUE";document.bgColor="BLUE";

-->-->

</SCRIPT></SCRIPT>

HTML

com

men

t

98

JavaScript Functions

• The keyword The keyword functionfunction used to define used to define a function (subroutine):a function (subroutine):

function add(x,y) {function add(x,y) {

return(x+y);

}}

99

JavaScript Events

• JavaScript supports an event handling JavaScript supports an event handling system.system.– You can tell the browser to execute

javascript commands when some event occurs.

– Sometimes the resulting value of the command determines the browser action.

100

Simple Event Example

<BODY BGCOLOR=WHITE onUnload="restore()"><H5>Hello - I am a very small page!</H5><SCRIPT>savewidth = window.innerWidth;saveheight = window.innerHeight;function restore() { window.innerWidth=savewidth; window.innerHeight=saveheight;}// Change the window size to be smallwindow.innerWidth=300; window.innerHeight=50;document.bgColor='cyan';</SCRIPT>

<BODY BGCOLOR=WHITE onUnload="restore()"><H5>Hello - I am a very small page!</H5><SCRIPT>savewidth = window.innerWidth;saveheight = window.innerHeight;function restore() { window.innerWidth=savewidth; window.innerHeight=saveheight;}// Change the window size to be smallwindow.innerWidth=300; window.innerHeight=50;document.bgColor='cyan';</SCRIPT>

101

Buttons

• You can associate buttons with JavaScript You can associate buttons with JavaScript events (buttons in HTML forms)events (buttons in HTML forms)

<FORM>

<INPUT TYPE=BUTTON

VALUE="Don't Press Me"

onClick="alert('now you are in trouble!')“ >

</FORM>

<FORM>

<INPUT TYPE=BUTTON

VALUE="Don't Press Me"

onClick="alert('now you are in trouble!')“ >

</FORM>

102

Some Events (a small sample)

onUnLoad

onLoad

onClick

onMouseUp

onMouseDown

onDblClick

onMouseOver

Window events

Button events

Link events

103

Document Object Model

• Naming hierarchy used to access individual elements of a HTML document.

• Netscape D.O.M. is a little different than IE D.O.M.

• Easy to use if you name all entities:– Forms, fields, images, etc.

104

DOM example<FORM ID=myform ACTION=…Please Enter Your Age:<INPUT TYPE=TEXT ID=age NAME=age><BR>And your weight:<INPUT TYPE=TEXT ID=weight NAME=weight><BR>

</FORM>

From javascript you can get at the age input field as: document.myform.age.value

105

Form Field Validation

• You can have JavaScript code that makes sure the user enters valid information.

• When the submit button is pressed the script checks the values of all necessary fields:– You can prevent the request from

happening.

106

Checking Fieldsfunction checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); }}

function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); }}

Needs to return true or false!

107

The Form

<FORM METHOD=GET ACTION=foo.cgi

NAME=myform

onSubmit="return(checkform())">

AGE: <INPUT TYPE=TEXT NAME=Age>

<INPUT TYPE=SUBMIT>

</FORM>

<FORM METHOD=GET ACTION=foo.cgi

NAME=myform

onSubmit="return(checkform())">

AGE: <INPUT TYPE=TEXT NAME=Age>

<INPUT TYPE=SUBMIT>

</FORM>

Needed to prevent the

browser from submitting!

108

Important Note about Form Validation

• It's a good idea to make sure the user fills out the form before submitting.

• Users can bypass your form – they can create requests manually (or their own forms).

109

Decision-Making Code

110

Outline

• Boolean variablesBoolean variables

• How to compare valuesHow to compare values

• The “if” structureThe “if” structure

• The “if …else” structureThe “if …else” structure

111

Boolean Variables

• A A BooleanBoolean variablevariable is a variable that is is a variable that is able to hold one of two values:able to hold one of two values:– true– false

• Boolean variables are used to answer Boolean variables are used to answer simple questions that we can pose in a simple questions that we can pose in a program. program. – If the answer is “true”, we do something. – If the answer is “false”, we do something

else.

112

Creating Booleans

• var x;var x;

• x = false;x = false;

• This means that “x” will store the value This means that “x” will store the value of “false”. of “false”.

• Note:Note:– it is not a string– it is not a number

113

Comparing Values

• If we compare two values together, we If we compare two values together, we can determine what their relationship is.can determine what their relationship is.

• Once we determine their relationship, we Once we determine their relationship, we can store that information using a can store that information using a Boolean.Boolean.

• Assume three variables: x, y and z:Assume three variables: x, y and z:z = (x < y)– If x < y, then z will be true. – If x > y, then z will be false.

114

Comparing Values

• We can compare in different ways:We can compare in different ways:OperatorOperator OperationOperation

<< less thanless than<=<= less than or equal toless than or equal to>> greater thangreater than>=>= greater than or equal to greater than or equal to ==== equalsequals!=!= not equalsnot equals

115

Examples

if x=2 and y=3, then if:if x=2 and y=3, then if:

z = (x<y);z = (x<y); z will be truez will be true

z = (x<=y);z = (x<=y); z will be truez will be true

z = (x>y);z = (x>y); z will be falsez will be false

z = (x>=y);z = (x>=y); z will be falsez will be false

z = (x==y);z = (x==y); z will be falsez will be false

z = (x!=y);z = (x!=y);z will be truez will be true

116

Comparing Strings

• We can use the “equals” operator (==) We can use the “equals” operator (==) to compare two strings.to compare two strings.

• We can check to see if two strings are We can check to see if two strings are the same:the same:– name1 = “Bob”;– name2 = “Fred”;

result = (name1 == name2);

result = (name1 != name2);

117

Logic Operators

• Now that we are able to work with Now that we are able to work with Boolean variables, we need to be able Boolean variables, we need to be able to deal with multiple Booleans. to deal with multiple Booleans.

• We may need to make multiple We may need to make multiple comparisons and then decide, based on comparisons and then decide, based on the results, what we should do. the results, what we should do.

• This requires using logical operations.This requires using logical operations.

118

Logical Operations

OperatorOperator Operation PerformedOperation Performed

&&&& AND: true if both values are trueAND: true if both values are true

|||| OR: true if either value is trueOR: true if either value is true

!! NOT: negates the valueNOT: negates the value

• These operations can be used on any two These operations can be used on any two Boolean values and will result in a Boolean Boolean values and will result in a Boolean value itself.value itself.

119

“AND” Logic Table

ExpressionExpression Resulting ValueResulting Value

true&&truetrue&&true truetrue

true&&falsetrue&&false falsefalse

false&&truefalse&&true falsefalse

false&&falsefalse&&false falsefalse

120

“OR” Logic Table

ExpressionExpression Resulting ValueResulting Value

true||truetrue||true truetrue

true||falsetrue||false truetrue

false||truefalse||true truetrue

false||falsefalse||false falsefalse

121

Putting it together

• The logic tables require two Booleans.The logic tables require two Booleans.

• Since any comparison that we make Since any comparison that we make results in a Boolean, we can use these results in a Boolean, we can use these comparisons in logic operations where comparisons in logic operations where needed.needed.

• These logic operations and Booleans These logic operations and Booleans will come in handy when we have to will come in handy when we have to make decisions.make decisions.

122

The “if” Statement

• One key decision statement is the “if” One key decision statement is the “if” statement.statement.

• The “if” statement allows us to The “if” statement allows us to determine the value of a Boolean and, determine the value of a Boolean and, based on that value, either execute or based on that value, either execute or skip some section of code.skip some section of code.

• This is the easiest way to control which This is the easiest way to control which code we are going to run.code we are going to run.

123

How “if” Works

if (Boolean expression) {if (Boolean expression) {

statement;statement;

……

statement;statement;

}}

124

An “if” Example

var number;var number;number=prompt(“Enter a number”);number=prompt(“Enter a number”);if (number < 10) {if (number < 10) {

document.write(“Your number is < 10”);document.write(“Your number is < 10”);}}if (number > 10) {if (number > 10) {

document.write(“Your number is > 10”);document.write(“Your number is > 10”);}}

125

The “if” Example

• For our example: For our example: – if the number is less than 10, we get one

response– if the number is greater than 10, we get

another response– if the number is equal to 10, what

happens?

126

An “if … else” Structure

• The “if … else” structure is similar to an The “if … else” structure is similar to an “if” structure, except that it has a second “if” structure, except that it has a second part associated with it. part associated with it.

• The “else” portion catches all of that The “else” portion catches all of that cases that are not associated with the cases that are not associated with the “if” Boolean.“if” Boolean.

• This allows us to cover two different This allows us to cover two different cases in the same structure.cases in the same structure.

127

The “if … else” Structure

if (Boolean statement) {if (Boolean statement) {statement;statement;……

}}else {else {

statement;statement;……

}}

128

An “if … else” Example

var number;var number;number=prompt(“Please input a number”);number=prompt(“Please input a number”);if (number < 10){if (number < 10){

document.write(“Your number is < 10”);document.write(“Your number is < 10”);}}else {else {

document.write(“Your number is >= 10”);document.write(“Your number is >= 10”);}}

129

More on “if”

• ““if” and “if …else” statements are the if” and “if …else” statements are the basic building blocks to decision-making basic building blocks to decision-making code.code.

• They are the basic method used to They are the basic method used to control which code will be executed and control which code will be executed and which will be skipped. which will be skipped.

• This allows the user to input information This allows the user to input information that will effect how the program will act.that will effect how the program will act.

130

Some Possible Problems

• One key problem when dealing with One key problem when dealing with variables is making sure that you are variables is making sure that you are comparing what you want to compare.comparing what you want to compare.

• From the perspective of users entering From the perspective of users entering input, you should be careful that the input, you should be careful that the user enters in the “correct” information. user enters in the “correct” information.

• If you are trying to compare numbers If you are trying to compare numbers and the user enters letters, it could and the user enters letters, it could cause trouble.cause trouble.

131

An Example

• If we try to compare a number entered If we try to compare a number entered by the user, but the user enters a string, by the user, but the user enters a string, then the comparison will still “happen”.then the comparison will still “happen”.

• You may try to use the “number” You may try to use the “number” entered by the user later, but because it entered by the user later, but because it is a string, it will cause errors.is a string, it will cause errors.

• Your results may not turn out to be what Your results may not turn out to be what you want.you want.

132

Checking Input

• We can check input from the user with a We can check input from the user with a function called “isNaN()”function called “isNaN()”

• This function allows us to determine if This function allows us to determine if the parameters is “NaN”.the parameters is “NaN”.

• Now that we can determine if a value is Now that we can determine if a value is a number, we will be able to ask the a number, we will be able to ask the user to re-enter information that we user to re-enter information that we think is correct.think is correct.

133

Checking Input Example

var number, test;var number, test;

number=prompt(“Enter a number”);number=prompt(“Enter a number”);

test = isNaN(number);test = isNaN(number);

if (test) {if (test) {

document.write(“The input was a string”);document.write(“The input was a string”);

}}

else {else {

document.write(“The input was a number”);document.write(“The input was a number”);

}}

134

What about bad input?

• If we receive bad input from the user, If we receive bad input from the user, we can warn them that the input is we can warn them that the input is incorrect with an “alert”. incorrect with an “alert”.

• An alert will create a pop-up dialog An alert will create a pop-up dialog along with some text. The box will stay along with some text. The box will stay on the screen until they click “OK”.on the screen until they click “OK”.

• This is one way to give the user some This is one way to give the user some information.information.

135

An “alert” Example

alert (“This is an alert on the screen!”);alert (“This is an alert on the screen!”);

136

End of Lecture