Professional Documents
Culture Documents
Lecture 8
Lecture 8
1
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
2
JavaScript is not Java
• JavaScript is a very simple scripting
language.
• Syntax is similar to a subset of Java.
• Interpreted language.
• Uses objects, but doesn't really support
the creation of new object types
3
Language Elements
• Variables
• Literals
• Operators
• Control Structures
• Objects
4
More JavaScript Basics
<script language=“JavaScript”>
document.write(“Hello, World!”);
</script>
6
Embedding HTML in JavaScript Output
• Yes:
document.write (“<b>”);
document.write (“Hello, World!”);
document.write (“</b>”);
• No:
<b>
document.write (“Hello, World!”);
</b>
8
More JavaScript Basics…
• Although multiple “write()” commands
may be used, HTML will still ignore the
different lines and put the words
together.
• If we want to force a new line to start, we
have to use <br>.
• If we want a new paragraph, we have to
use <p>.
9
Example
document.write(“Hello,”);
document.write(“How are you?”);
• This above text will appear all on one line.
If we want the text to be on different lines,
we have to do the following:
document.write(“Hello,”);
document.write(“<br>How are you?”);
10
What is a Variable?
• A variable is a “named storage spot”
where we can store information. It is a
little like a box where we can
temporarily put information that we want
to use later on.
• Variables are very useful when
programming – they allow us to retrieve
information from the user and use it at a
later point in time.
11
Prompting For & Storing User Input
<script language=“JavaScript”>
var name;
name=prompt(“Please enter your name”);
document.write(“Hello, ”);
document.write(name);
</script>
16
More Prompting
• When we use the “prompt()” function,
we can also enter default information
into the field. This is done by using a
second parameter.
prompt(“Question”, “default
text”);
• The “default text” will appear in the
editable field where the user is
supposed to put their data.
17
Multiple Variables
• We can use multiple variables when
using JavaScript. This means that we
are able to handle multiple different
inputs from the user.
• Once we have access to the different
variables, we can use them how we
wish.
• It is important to point out that a variable
can be use as many times as needed.
18
Multiple Variable Declaration
• We can declare multiple variables two
different ways:
– One per line:
• var first_name;
• var last_name;
– Both on the same line:
• var first_name, last_name;
19
Retrieving Multiple Pieces of Data
20
Variable Naming
27
Number Types
• There are two different types of
numbers: floats and ints.
• A float is a number with a decimal point
(a floating point number).
• An int is a number without a decimal
point (an integer).
• If we want to convert a string to a
number, we have to decide which
numeric type we want to convert it to.
28
Floats
• In order to convert strings to floats, we use a
function called parseFloat()
• We parse the number from the string
variable. This removes the number from the
string, storing it as a numeric value.
• The parse function will even remove extra
characters that may happen to follow the
floating point number in the prompt field. It will
not remove characters that appear before the
first character.
29
parseFloat()
var x, y, answer;
x = prompt(“Enter a number”);
x = parseFloat(x);
y = prompt(“Enter a second number”);
y = parseFloat(y);
answer = x + y;
document.write(x, “ + ”, y, “ = “, answer);
30
Explanation
• We can use the values stored in x and y to
create a new value to store in answer.
• We can use all three variable again to write
information to the screen.
• When using the write command, we have the
option of including multiple items to be
written, as long as they are separated by a
comma.
• We have to include the appropriate spacing
for the output to look correct.
31
What about ints?
• We can get an integer from a string by
using the parseInt function.
• This function will retrieve an int from the
entered text.
• As with the parseFloat function, trailing
letters will be removed, while leading
letters will cause an error.
• parseInt will also remove anything to
the right of the decimal point.
32
parseInt vs. parseFloat
33
What about other math
operations?
34
What about “Strings”?
37
Errors (cont’d)
• 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
know which lines of code have caused
the problem.
38
Errors (cont’d)
• If you are unsure of how some piece of
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,
you can answer your own questions
quickly about JavaScript. It is a good
way to learn how to program. 39
Error Types
• There are three different types of errors:
– syntax errors
– logic errors
– user errors
• We must be able to determine the
difference between these errors in order
to be able to correct them.
40
Syntax Errors
• A syntax error is an error created by
incorrectly typing in JavaScript
statements.
• An example would be:
– write.document(“Hello, World!);
• The missing quote will cause this
statement to fail.
• Such statements may simply not work in
our browsers.
41
Logic Errors
• Logic errors occur when we make a mistake
in the logic of our statements.
• For example:
number = 50 + 100 / 2
number = (50 + 100) / 2
• If we really mean the second one and we type
in the first one, we will have a logic error.
• We have to be careful that the logic of the
program is correct.
42
User Errors
program
programming statements
46
JavaScript Variables
• Un-typed!
• Can be declared with var keyword:
var foo;
47
Variables (cont.)
• Using var to declare a variable results
in a local variable (inside a function).
48
Literals
• The typical bunch:
– Numbers 17 123.45
– Strings "Hello Dave"
– Boolean: true false
– Arrays: [1,"Hi Dave",17.234]
49
Operators
• Arithmetic, comparison, assignment,
bitwise, boolean (pretty much just like
C).
+ - * / % ++ -- == != > <
&& || ! & | << >>
50
Control Structures
• Again – pretty much just like C:
if if-else ?: switch
with (object)
51
Objects
• An object is a definable thing, such as
a car. Objects are allowed to have other
objects – a car can have a trunk, the
trunk may have a spare tire.
• Since JavaScript is an object-oriented
language, we use dot syntax to specify
the relationship between objects.
• car.trunk.sparetire
52
Objects
• Objects have attributes and methods.
• Many pre-defined objects and object
types.
• Using objects follows the syntax of
C++/Java:
objectname.attributename
objectname.methodname()
53
Instance
• An instance is a particular incarnation
of an object.
• For example, I could represent students
in the class using class.student, where
an instance of the student object would
be a particular person.
• An instance of an object has all of the
same attributes as that object.
54
Objects
• In real life, and object is a tangible
“thing” – a car, a bike or a computer.
• As we can see, we like to name objects
so that we can talk about them.
• The object name doesn’t define the
object, but it acts as more of a reference
to the object itself.
55
Objects (cont’d)
• When programming, we use “objects”
as a reference name for information that
we want to store.
• We use programming objects to store
information about real-life objects.
• We store object data by storing
information about the individual
attributes or properties of the object in
question.
56
Object Information
• For example, if we have a green
bowling ball that weighs 3kgs, we know
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
associating an attribute with a piece of
data describing that attribute.
57
Creating an Object
• In JavaScript, we can create an Object
using a function. In this case, we can
create a bowling ball object:
var bball = new Object();
• This code creates a new object called
bball.
• The “new Object()” function is called a
constructor function because it is used
to construct a new object.
58
Storing Object Information
60
Object Info (cont’d)
• bball.color=“green”;
• car.color=“red”;
• If we were to say:
– document.write(color);, we wouldn’t
know which color to print out.
• Instead, we can refer to the information
based on the object:
– document.write(bball.color);
– document.write(car.color);
61
Object Attributes
• We can add as many attributes to an
object as we like.
• It is advisable to keep the number of
attributes to the minimum needed.
• We should also declare all of the
attributes in the same location, making it
easier to keep track of them.
62
Primitive Types
• Considering that an object is an new
type of variable, we can now refer to
ordinary variables as primitive types.
• A primitive type is a one of the regular
variables that we can store.
• There are three primary primitive
types – numbers, strings and Booleans.
63
Compound Objects
• A compound object is an object where
some of the attributes are other objects.
• For example, one attribute of a person
object might be their name.
• name itself can also be an object, as it
can be comprised of a first, middle and
last name.
• In this case, the object name is an
attribute of the object person.
64
Compound Objects (cont’d)
parent child
first
Name middle
Person last
Age
65
Using Compound Objects
• We can use compound objects in the
same way that we used variables.
• The advantage of compound objects
falls with the ability to logically manage
the object.
• We are able to store all of our related
information in a logical object.
66
More Objects
• The document object is a compound
object.
• The document object is part of the
larger window object. Each of these
objects has attributes that we can
access.
67
The Window Object
• window.closed (Boolean)
• window.location (String)
• window.history.length (Number)
68
The document Object
• The document object is special in the
window, so there is no need to specify
the parent “window” object.
• This allows us to use
“document.bgColor” instead of
“window.document.bgColor”.
• There are many other document
attributes that we can access.
69
document attributes
• document.bgColor (String)
• document.fgColor (String)
• document.URL (String)
• document.lastModified (String)
• document.linkColor (String)
• document.vlinkColor (String)
70
Object Methods
• A method is a function an object can use to
perform various tasks.
• We have already seen an object method –
the write method associated with the
document object.
• The write method is used to tell the
document object to add some information to
the page.
• This is why we say document.write(“foo”);
71
Object Methods (cont’d)
• Methods are a powerful method of
modifying objects.
• Creating methods for objects that we
have created is out of the scope of this
course, but we will take advantage of
those methods available to us from the
window, document and other objects.
72
window.confirm()
• The confirm() method of the window
object will ask the user a question and
get a result – either true or false,
depending on which button they push.
• We can store the results of the question
in a variable. We can use the variable
later in the program to perform some
action.
73
Example
var question;
question = window.confirm(“This is a question
where you have to answer OK or Cancel. OK is
true, Cancel is false. Do you understand?”);
if (question){
document.write(“You understood.”);
}
else{
document.write(“You didn’t understand.”);
}
74
window.location
• window.location is responsible for
telling the window to load a new
webpage.
• If we say
window.location=http://www.csuhayward.e
du, we will be transported to the
Hayward homepage.
75
window.history
• We can also use the window history to
go back to previous webpages.
• For example, if we want to bring the
user back to the page they just arrived
from, we can use window.history.go(-
1); to bring them back one page. We
can go back as many pages as we like.
76
Properties
• Object can have properties. These
properties are responsible for identifying
and storing information about the object.
• For example, in the example of
class.student, each instance of
student would have a property called
name.
• We can access the property using the
dot syntax for class.student.name
77
Values
• We can set the values of object
properties for instances of an object.
• In our student example, we can set the
name of the student in the following
way:
– class.student.name = “Frank”;
• Likewise, we can apply this to our
document object:
– window.document.bgColor=“red”;
78
Accessing Values...
• If we include an image in our webpage and
give it a name, we can access it as a
property.
• <img src=“image.jpg”
name=“testPic” alt=“picture”>
can be accessed by:
• document.testPic.src=“image.jpg”
79
Accessing Values…
<a href=“#”
onmouseover=“document.bgColor=‘green’;”>
This is some text</a>
83
onmouseout event
• Attribute length
• Methods include:
concat join pop push reverse sort
90
Array example code
var a = [8,7,6,5];
for (i=0;i<a.length;i++)
a[i] += 2;
b = a.reverse();
91
Many other pre-defined object types
92
Predefined Objects
• JavaScript also includes some objects
that are automatically created for you
(always available).
– document
– navigator
– screen
– window
93
The document object
• Many attributes of the current
document are available via the
document object:
Title Referrer
URL Images
Forms Links
Colors
94
document methods
• document.write() like a print
statement – the output goes into the
HTML document.
string concatenation!
95
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>
96
JavaScript and
HTML Comments
<SCRIPT>
<!--
document.write("Hi Dave");
document.bgColor="BLUE";
-->
</SCRIPT>
97
JavaScript Functions
• The keyword function used to define
a function (subroutine):
function add(x,y) {
return(x+y);
}
98
JavaScript Events
• JavaScript supports an event handling
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.
99
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 small
window.innerWidth=300; window.innerHeight=50;
document.bgColor='cyan';
</SCRIPT>
100
Buttons
• You can associate buttons with JavaScript
events (buttons in HTML forms)
<FORM>
<INPUT TYPE=BUTTON
VALUE="Don't Press Me"
onClick="alert('now you are in trouble!')“ >
</FORM>
101
Some Events (a small sample)
onUnLoad
Window events
onLoad
onClick
onMouseUp Button events
onMouseDown
onDblClick
onMouseOver Link events
102
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.
103
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>
104
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.
105
Checking Fields
function checkform() {
if (document.myform.age.value == "") {
alert("You need to specify an age");
return(false);
} else {
return(true);
}
}
107
Important Note about Form Validation
108
Decision-Making Code
109
Outline
• Boolean variables
• How to compare values
• The “if” structure
• The “if …else” structure
110
Boolean Variables
• A Boolean variable is a variable that is
able to hold one of two values:
– true
– false
• Boolean variables are used to answer
simple questions that we can pose in a
program.
– If the answer is “true”, we do something.
– If the answer is “false”, we do something
else.
111
Creating Booleans
• var x;
• x = false;
• This means that “x” will store the value
of “false”.
• Note:
– it is not a string
– it is not a number
112
Comparing Values
• If we compare two values together, we
can determine what their relationship is.
• Once we determine their relationship,
we can store that information using a
Boolean.
• 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.
113
Comparing Values
• We can compare in different ways:
Operator Operation
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equals
!= not equals
114
Examples
117
Logical Operations
Operator Operation Performed
&& AND: true if both values are true
|| OR: true if either value is true
! NOT: negates the value
119
“OR” Logic Table
Expression Resulting Value
true||true true
true||false true
false||true true
false||false false
120
Putting it together
if (Boolean expression) {
statement;
…
statement;
}
123
An “if” Example
var number;
number=prompt(“Enter a number”);
if (number < 10) {
document.write(“Your number is < 10”);
}
if (number > 10) {
document.write(“Your number is > 10”);
}
124
The “if” Example
125
An “if … else” Structure
if (Boolean statement) {
statement;
…
}
else {
statement;
…
}
127
An “if … else” Example
var number;
number=prompt(“Please input a number”);
if (number < 10){
document.write(“Your number is < 10”);
}
else {
document.write(“Your number is >= 10”);
}
128
More on “if”
135
End of Lecture
136