Upload
roger-leonard
View
225
Download
2
Embed Size (px)
Citation preview
The Document Object The Document Object ModelModel
GoalsGoalsUnderstand how a JavaScript can
communicate with the web page in which it “lives.”
Understand how to use dot notation.Understand how to read form
elements.Understand how to work with new
windows.
Review – ObjectsReview – ObjectsObjects are unique programming
entities in scripts or web pages. Objects have properties which describe them; methods (actions that objects can do) and events to which they can react.
A property is an object’s characteristic. Typically, properties come in property-value pairs (i.e. - background-color is a property; blue is a value).
A method is something that an object can do.
An event is an action to which an object can react (i.e. – when a web page loads).
Introducing DOMIntroducing DOMDescribes the way JavaScript
(and other client-side languages) can communicate with the web page in which it “lives.”
DOM allows us to dynamically update Web pages.
Because of DOM, we can now use JavaScript to interact with CSS and other web elements, like form objects.
Introducing DOMIntroducing DOMDOM relies on interaction with
objects in a web page. The document object is
considered the “core” object in DOM.
The top-level DOM object is the window object.
We can dynamically assign values to object properties:
Reading PropertiesReading Properties
Not only can we change properties dynamically, we can read properties, as well:
Common Document Common Document PropertiesPropertiesdocument.bgColor – The
background color of the page.document.fgColor – The text
color used on a page.document.domain – The address
of the web server that houses the page.
document.lastModified – The date and the last time someone edited the page.
Common Document Common Document PropertiesPropertiesdocument.URL – The address of
the web page.document.location – (Deprecated)
Same as document.URL document.referrer – The address
of the page that linked to the current page.
document.title – The text contained in the <title>…</title> tag of the current page.
Common Document Common Document MethodsMethodsdocument.open() – Begin a new
document, replacing existing content (destructive)
document.close() – Ends a document begun with the document.open() method
document.write() – Append text to the current document
document.writeln() – Append text to the current document and include a newline character (line break)
JavaScript Events & DOMJavaScript Events & DOMThrough recording and reacting
to events, we make our web page more interactive.
We can add this interactivity by detecting events in a document’s environment and writing programming statements to react to those events. Typically, we code this using functions:
Getting Input Using DOMGetting Input Using DOMInput is not just text anymore! It
can come from form components (text fields, password fields, hidden fields, radio buttons, etc.).
We can use dot notation to represent DOM hierarchy. DOM hierarchy provides each form element with its unique “address.”
Dot NotationDot Notation
The unique “address” of an objectFrom L to R, start with the most
general, moving to the object itself
window.document.myForm.fName.valuewindow.document.myForm.fName.value
Browser Window
The Current Page
Form Name
Field Name
ValueProperty
Input using Text FieldsInput using Text FieldsName the formName all fieldsUse dot notation to reference specific
fieldsStraight-forward, similar to how we
reference variablesOther objects that use the same
syntax:◦ textarea◦ password field◦ hidden
Input using Check BoxesInput using Check BoxesName the formName all fieldsUse dot notation to reference specific
fieldsUsed the “checked” instead of the
“value” propertyReturns a Boolean value:
◦ true◦ false
Use if structure to evaluate
DOM and ArraysDOM and ArraysFor some form objects, we need to
use a new type of data structure – an array.
What is an array?◦An array is a data structure that can
hold multiple values (unlike a variable, which can only hold 1 value at a time).
◦An array is useful when we work with groups of form objects, like radio buttons
Arrays and MemoryArrays and MemoryIn a computer’s memory, an
array represents multiple contiguous locations that all contain the values of the same data type.
We represent each “slot” in an array with a number:◦Numbers start at zero. ◦An element’s position (represented
by a number) is called an index (or subscript)
Why use Arrays?Why use Arrays?Use an array when you need to
group values by some common characteristic (e.g. – Students in a classroom).
When designing an application that performs the same processing for multiple sets of data, use an array and a looping structure.
Conceptual Example of Conceptual Example of ArraysArrays
00 JohnJohn
11 MaryMary
22 ElizabethElizabeth
33 OmarOmar
44 CharlesCharles
55 RaviRavi
66 KatherineKatherine
77 HannahHannah
88 AlexanderAlexander
99 WilliamWilliam
Array Positions (Elements) –Each number represents the subscript (index) of its corresponding position
Array Values –The value stored in contiguous memory cells
Array Name = Class
Array ElementsArray ElementsElements populate an array.Each element is a discrete value.We identify elements using a
unique index (the element’s “address”).
Array index numbering starts with zero and increments by one for each new element.
Declaring an ArrayDeclaring an ArrayTo declare an array in JavaScript,
we use the array constructor and assign the array to a variable. We give the constructor the size of the array as an argument:var n341Class = new Array(34);
At times, we may not know the size of the array when declaring. In such situations, we can declare an empty array:var n341Class = new Array();
Adding Values to an ArrayAdding Values to an ArrayTo add values to an array, assign
the new values while also identifying the index where you want JavaScript to store the new value:n341Class[0] = “Jennifer”;n341Class[0] = “Jennifer”;n341Class[1] = “Joseph”;n341Class[1] = “Joseph”;n341Class[2] = “Marcus”;n341Class[2] = “Marcus”;n341Class[3] = “Alex”;n341Class[3] = “Alex”;
Using a For Loop to Add Using a For Loop to Add ValuesValuesIn some instances, we can use a
for loop to add values:for(var i=0; i<10; i++){
var newStudent = new String(“”);
newStudent = “Student”;newStudent = i.toString();n341Class[i] = newStudent;
}
Parallel (Corresponding) Parallel (Corresponding) ArraysArraysParallel arrays gives you the ability to
store multiple pieces of information about a single entity in an application.
The indexes of each array should correspond to one another for individual entities:◦ Student ID◦ Student Name◦ Student Exam Score
Conceptual Example of Conceptual Example of Parallel ArraysParallel Arrays
00 047254047254
11 038546038546
22 024136024136
33 057866057866
44 015543015543
55 025769025769
66 025119025119
77 035176035176
88 036585036585
99 028116028116
Arr
ay N
am
e =
str
SID
00 JohnJohn
11 MaryMary
22 ElizabethElizabeth
33 OmarOmar
44 CharlesCharles
55 RaviRavi
66 KatherineKatherine
77 HannahHannah
88 AlexanderAlexander
99 WilliamWilliam
00 9393
11 8686
22 7474
33 9292
44 5656
55 8282
66 8989
77 8282
88 7575
99 7777
Arr
ay N
am
e =
str
N341C
lass
Arr
ay N
am
e =
fl
tExam
1S
core
s
Creating Parallel ArraysCreating Parallel ArraysTo create parallel arrays, just
create them as you would any other array:var SID = new Array();var n341Class = new Array(); var examScr = new Array();
The arrays are separate arrays in memory, but your program should treat them as one …
Assigning Values to Parallel Assigning Values to Parallel ArraysArrays
To assign values for a single entity to parallel arrays, use the same index number for each assignment:SID[5] = “025769”;n341Class[5] = “Ravi”;examScr[5] = 82;
The Array.length PropertyThe Array.length PropertyJust like any JavaScript objects,
arrays have properties.One of the most useful properties
is the length property, which will give you a count of how many indexes the array has.
The Array.length PropertyThe Array.length PropertyExample of the Array.length property:var golfScores = new Array();var golfScrSize = 0;
golfScores[0] = 72;golfScores[1] = 85;golfScores[2] = 125;
//golfScrSize will get the//value of 3golfScrSize = golfScores.length;
Using Array.lengthUsing Array.lengthThe following code averages the
values stored in an arrayfor(var i=0; i<golfScores.length; i++){
sumScores += golfScores[i]}avgScore = sumScores/golfScores.length;
Array ExamplesArray Examples
Single Array
Parallel Arrays
Input using Radio ButtonsInput using Radio ButtonsName the form.Name the group (each button of
the same group has the same name)
Assign each button a “value” property.
Use an if structure nested in a for loop to evaluate each button.
Input using Selection Input using Selection ObjectsObjectsSimilar to radios (use an array to
evaluate)No need for a loop because there is
only one object rather than several options.
Name the formName the select objectAssign each option a “value”
property
Outputting to WindowsOutputting to WindowsUse a functionCreate a new window using the open()
method of the window object.The open() method takes the following
parameters:◦ URL◦ Name of the window object◦ Window properties:
Size Menus? Toolbars?
Outputting to Windows - ExamplesOutputting to Windows - Examples
Example 1
Example 2
Questions?Questions?
ResourcesResourcesFlanagan, David. JavaScript: The
Definitive Guide, 4th Edition. O’Reilly, 2002.