www.cisdocs.com

Download Report

Transcript www.cisdocs.com

JavaScript, Fifth Edition
Chapter 4
Manipulating the Browser Object Model
Objectives
In this chapter, you will:
• Study the browser object model
• Work with the Window object
• Study the History, Location, and Navigator
objects
JavaScript, Fifth Edition
2
OBJECT MODELS
JavaScript, Fifth Edition
3
Javascript Object Model
• JavaScript implementation is made up of three
distinct parts
– The Javascript Core (based on ECMAScript spec)
– The Document Object Model (DOM)
– The Browser Object Model (BOM)
JavaScript, Fifth Edition
4
Browser Object Model (BOM)
• The larger representation of everything provided by
the browser including the current document,
location, history, frames, and any other functionality
the browser may expose to JavaScript
– not standardized - can change based on different
browsers
– most important task is managing browser
windows and enabling communication between the
windows
JavaScript, Fifth Edition
5
Browser Object Model (cont.)
• Browser object model (BOM)
is client-side object model
– Hierarchy of objects
– Each provides programmatic
access
• To a different aspect of the
Web browser window or the
Web page
• Window object
– Represents a Web browser
window
– Called the global object
• Because all other BOM
objects contained within it
JavaScript, Fifth Edition
6
Understanding the Browser Object
Model (cont’d.)
Figure 4-2 Window object and Document object
JavaScript, Fifth Edition
7
The Document Object
• Every HTML document loaded into a browser
window becomes a Document object
– Therefore it is an object in the Browser Object
Model (BOM).
• Document object
– Represents the Web page displayed in a browser
– Contains all Web page elements
JavaScript, Fifth Edition
8
Document object model (DOM)
• The Document Object Model (DOM) is standardized
and is specific to current HTML document
– Interface allows programs and scripts to access and
modify the content, style, and structure of a document
• is platform-neutral (works on any computer)
• is language-neutral (can exchange information between any
client and a server)
JavaScript, Fifth Edition
9
Document object model (DOM)
• The Document Object Model
(DOM)
– Organized structure of objects
– Each document object model
organizes objects into a
hierarchy known as a
document tree
• Tree structure becomes more
elaborate as DOMs
encompass more objects
JavaScript, Fifth Edition
10
DOM and HTML
DOM sees an HTML (or XML) document as a tree or as a group of trees.
The document's root element is the <html> element (the primary source)
Can see the node structure with a browser, by inspection
Referencing Objects
• Browser object model objects may represent arrays
– Examples: forms[] or images[]
– Arrays contain objects
• Created from corresponding Web page elements
• JavaScript can reference any Web page element
– Use periods to append element’s name to the name
of any elements in which it is nested
JavaScript, Fifth Edition
12
Referencing Objects (cont’d.)
• Object name identifies each
object
• Use dot syntax (i.e., separate
each level using a dot) to
indicate location of an object
within the hierarchy
window.document
document.forms[0]
Referencing Objects (cont’d.)
• Example using name:
<body>
<img src=“dog.gif” height=‘100’ width=‘100’ name=“mydog” onclick=‘dog()’/>
</body>
<script>
function dog()
{
var pic = document.mydog.src;
}
</script>
JavaScript, Fifth Edition
14
Referencing Objects (cont’d.)
• Elements represented by arrays
– Can reference the object through the array
• Instead of using the element name
• Example using array:
<body>
<img src=“dog.gif” height=‘100’ width=‘100’ name=“mydog” onclick=‘dog()’/>
</body>
<script>
function dog()
{
var pic = document.images[0].src;
}
</script>
JavaScript, Fifth Edition
15
Referencing Objects (cont’d.)
• Referring to the current object
– Can use the this keyword
• Instead of including the Document object and images[]
array
– The this keyword refers to the current object
• Example:
<body>
<img src=“dog.gif” height=‘100’ width=‘100’ name=“mydog” onclick=‘dog(this)’/>
</body>
<script>
function dog(dogObj)
{
var pic = dogObj.src;
}
</script>
JavaScript, Fifth Edition
16
Object Collections
• Can have more than one type of object in a
document
– Essentially creates an array
– Also supports the length property
Ways to Reference Objects
To reference…
Use…
An object as part of the
collection in a document
collection[idref]
EX. document.forms[0]
A document object based
on its ID
document.getElementById(id)
EX.
document.getElementById(“box”)
An array of elements
based on the tag name
object.getElementsByTagName(tag)
EX.
document.getElementsByTagName(“img”)
An array of elements
based on the value of the
name attribute
document.getElementsByName(name)
EX.
document.getElementsByName(“box”)
Working with
Object Properties
• An object is just a special kind of data, with properties
and methods
• Most objects are associated with one or more object
properties
• Properties are the values associated with an object
SYNTAX:
objectName.propertyName
• To set the value of an object property:
objectName.propertyName = expression
var message = “hello”;
alert (message.length);
Working with
Object Properties
• Naming Conventions for object properties:
– Begin with lowercase
– Use camel case for multiple words
Working with
Object Properties
• HTML DOM allows JavaScript to change the style of
HTML elements
document.getElementById(“id”).style.property=new style
document.getElementById("p2").style.color="blue";
Object Methods
• Methods are the actions that can be performed on
objects
• Call a method using the syntax :
objectName.methodName();
var message="Hello world!";
var x=message.toUpperCase();
• Methods may need additional data :
objectName.methodName(parameters)
history.back(-2);
WINDOW OBJECT
JavaScript, Fifth Edition
23
Manipulating the Browser with the
Window Object
• Window object
– Includes properties containing information about the
Web browser window
– Contains methods to manipulate the Web browser
window itself
JavaScript, Fifth Edition
24
Manipulating the Browser with the
Window Object (cont’d.)
Table 4-1 Window object properties
JavaScript, Fifth Edition
25
Manipulating the Browser with the
Window Object (cont’d.)
Table 4-2 Window object methods (continues)
JavaScript, Fifth Edition
26
Manipulating the Browser with the
Window Object (cont’d.)
Table 4-2 Window object methods
JavaScript, Fifth Edition
27
Manipulating the Browser with the
Window Object (cont’d.)
• self property
– Refers to the current Window object
– Identical to using the window property to refer to the
Window object
– Examples:
window.alert("Your order has been received.");
self.alert("Your order has been received.");
• Best practice
– Use window or self references
• When referring to a Window object property or method
JavaScript, Fifth Edition
28
Opening and Closing Windows
• Reasons to open a new Web browser window
– To launch a new Web page in a separate window
– To use an additional window to display information
• When new Web browser window opened:
– New Window object created
• Represents the new window
• Can assign the new window to a variable, or give it a
anme, to communicate to the new window
JavaScript, Fifth Edition
29
Opening a Window
• open() method of the Window object
– Opens new windows in the strict DTD
• Syntax
window.open(url, name, options, replace);
Table 4-3 Arguments of the Window object’s open() method
JavaScript, Fifth Edition
30
Opening a Window (cont’d.)
• Include all (or none) window.open() method
arguments
• Example:
window.open("http://www.wikipedia.org");
Figure 4-10 Web browser window
opened with the URL argument of
the open() method
JavaScript, Fifth Edition
Figure 4-11 Blank Web browser
window opened with the
window.open() statement
31
Opening a Window (cont’d.)
• Customize new Web browser window appearance
– Use the window.open() method options
argument
JavaScript, Fifth Edition
Table 4-4 Common options of the Window object’s
open() method
32
Opening a Window (cont’d.)
Figure 4-12 Woodland Park Zoo
Photo Gallery Web page
JavaScript, Fifth Edition
Figure 4-13 Woodland Park Zoo
Photo Gallery Slideshow Web
page displaying a fox
33
Opening a Window (cont’d.)
• window.open() method name argument
– Same as value assigned to the deprecated target
attribute
• Specifies window name where the URL should open
– If name argument already in use
• JavaScript changes focus to the existing Web browser
window instead of creating a new window
window.open(‘wiki.html’,’wikiWindow’,’height=200’)
<a href=‘http://www.wikipedia.org/’ target="wikiWindow">
Wikipedia home page</a>
JavaScript, Fifth Edition
34
Opening a Window (cont’d.)
• Window object’s name property used to specify a
target window with a link
– Cannot be used in JavaScript code
• Assign the new Window object created with the
window.open() method to a variable to control it
newWin=window.open(‘wiki.html’,’wikiWindow’,’height=200’)
• focus() method
– Makes a window the active window
newWin.focus();
JavaScript, Fifth Edition
35window.open(,wikiWin
dow,
Closing a Window
• close() method
– Closes a Web browser window
• window.close() or self.close()
– Closes the current window
JavaScript, Fifth Edition
36
EVENTS
JavaScript, Fifth Edition
37
Event handlers
• Events are usually triggered by user action, or in
response to the completion of a task
• During normal execution a large number of events
occur
– Event object is very active
• When an event fires, the computer places data
about the event into the Event Object
– Where the mouse pointer was on the screen at the
time of the event
– Which mouse buttons were pressed
Drag and Drop Event
Event handlers
• Events are normally used in combination with functions,
and the function will not be executed before the event
occurs (such as when a user clicks a button).
• Event handlers may be attached to various objects
including DOM elements, document, window object, etc.
• Events can be intercepted by
– HTML
• Tightly coupled – user initiated
– Event Listeners
• Only one listener for same event - binding
– As anonymous functions
• Function with no name
Working with Event Handlers
• All objects can be affected by events initiated by the
user or browser
• Can assign an event directly to an HTML element
<button onclick="displayDate()">Try it</button>
• Can assign event using the HTML DOM
<body onload=“init()”>
• These are called “callback” functions, because they
are wired to the event in the HTML code
– Downside: Javascript is mixed in with HTML
Working with Event Handlers
• Function references don’t blend HTML and script
• Assign the function to the event property of an
object
– No parentheses are used as you do not want the
function to run at this point – just want to reference it
Working with Event Handlers
• Advantages:
– Provides greater flexibility in designing scripts
– Removes scripting from the HTML code, placing it
within the external script file, or separate area
• Disadvantages:
– Difficulty passing parameter values to the function
assigned to the event
– Can assign only one function at a time to an object
and event
Working with Event Handlers
• Function literals solve these disadvantages
• Assign a function literal as the function reference to the
event, and then within the function literal, call the function
Examples:
document.getElementById(“myDoc”).onload=function(evt)
{
init();
}
document.getElementByTagName(“body”).onload=function(evt)
{
init();
}
JavaScript, Fifth Edition
44
Introducing the Event Model
• The event model describes how events interact
with objects
– IE event model
• Supported by IE and Opera
– W3C event model
• Supported by other major browsers
• The event model has a flow – up or down the
document tree
– capture phase and/or a bubbling phase
– event flow describes how event objects move through
the structure
Introducing the Event Model
• Event capturing
– events are initiated at the top of the object hierarchy
and drop down the object tree to the lowest object
– Window object notices event first
• Event bubbling
– an event is initiated at the bottom of the object tree,
and rises to the top of the hierarchy
– Each object it propagates through recognizes the
event
– Window object notices event last
Introducing the Event Model
Event bubbling in the IE event model
Introducing the Event Model
Event capturing
• An event is split into
three phases
– A capture phase as
the event moves
down the object
hierarchy
– A target phase in
which the event
reaches the object
from which the event
originated/where it
originates
– A bubbling phase in
which the event
moves back up the
object hierarchy
Introducing the Event Model
• W3C browsers uses event capturing and event
bubbling
– very powerful
– Run functions at any phase in the event
• IE and Opera use event bubbling
I. E. Event Model
• To attach a function to an object, run:
object.attachEvent(onevent, function);
– where object is the object receiving the event,
– onevent is the text string of the event handler
– function is the function that runs in response to the
event.
Multiple functions can be attached to the same event in
the same object.
NOTE: in I.E. 9 and above, the W3C event Model is
used
W3C Event Model
• Does not have an attachEvent
• Use an event listener
– detects when a particular event has reached an
object in the document
object.addEventListener(event, function, capture);
–
–
–
–
where object is the object receiving the event
event is the text string describing the event
function is the function to run in response to the event
capture equals true if the event is moving down the
document tree and false if the event is bubbling up
the tree.
I.E. and W3C Event Model
• Both event models allow you to remove event
handlers from objects
– The IE event model uses the detachEvent method
object.detachEvent (onevent, function)
– The W3C event model uses the removeEventListener
method
object.removeEventListener (event, function,
capture)
Event Object
• Source of an Event
– If the user has pressed a key on the keyboard, you
may want to know which key was pressed
• This type of information is stored in the event object
Capturing Events in browsers
– Write custom code to determine which browser is
being used, and execute code for that particular
browser
– Use OBJECT DETECTION to let the browser
discover the event
• Write code once that works for all browsers
• The event objects of the different browsers have
different properties and methods
NOTE: I.E. 9 (and lower) browsers, use
attachEvent. After I.E. 9, Microsoft changed to use
addEventListener,
<html>
<head>
<title>Event Propagation</title>
<style type="text/css">
#t-daddy { border: 1px solid red }
#c1 { background-color: pink; }
</style>
<script type="text/javascript">
function stopEvent(ev) {
c2 = document.getElementById("c2");
c2.innerHTML = "hello";
// this ought to keep t-daddy from getting the click.
ev.stopPropagation();
alert("event propagation halted.");
}
function load() {
elem = document.getElementById("tbl1");
elem.addEventListener("click", stopEvent, false);
}
</script>
</head>
<body onload="load();">
<table id="t-daddy" onclick="alert('hi');">
<tr id="tbl1">
<td id="c1">one</td>
</tr>
<tr>
<td id="c2">two</td>
</tr>
</table>
</body>
</html>
This example demonstrates how events
fire and are handled in the DOM in a very
simple way. When the BODY of this
HTML document loads, an event listener
is registered with the top row of the
TABLE. The event listener handles the
event by executing the function
stopEvent, which changes the value in
the bottom cell of the table.
However, stopEvent also calls an event
object method, event.stopPropagation,
which keeps the event from bubbling any
further up into the DOM. Note that the
table itself has an onclick event handler
that ought to display a message when the
table is clicked. But the stopEvent method
has stopped propagation, and so after the
data in the table is updated, the event
phase is effectively ended, and an alert
box is displayed to confirm this.
Understanding Click Events
• click and dblclick events
– click event often used for anchor element
– Web browser handles execution of the onclick
event handler automatically
– Can override anchor element’s automatic
onclick event handler
• Add an onclick event handler executing custom
code to the <a> element
– dblclick event works like the click event
JavaScript, Fifth Edition
57
Understanding Click Events (cont’d.)
...
<script type="text/javascript">
/* <![CDATA[ */
function warnUser() {
return window.confirm("This link is only for Red
Sox fans.
Are you sure you want to continue?");
}
/* ]]> */
</script>
</head>
<body>
<p><a href="redsox.html"
onclick="return warnUser();">
Red Sox Fan Club</a></p>
</body>
</html>
JavaScript, Fifth Edition
58
Understanding Mouse Events
• mouseover and mouseout events
– Create rollover effects
– Rollover effect
• Occurs when mouse moves over an element
– mouseover event
• Occurs when mouse passes over an element
– mouseout event
• Occurs when mouse moves off an element
JavaScript, Fifth Edition
59
Understanding Mouse Events
• Event handling can refer to a CSS style
– Use the this reference and the style property in an event
handler within the element itself
– Use the style property to modify an element’s CSS properties
with JavaScript
• Example:
– onmouseover event underlines the link when the mouse passes
over it
– onmouseout event removes the link when the mouse passes off it
<a href="redsox.html"
onmouseover="this.style.textDecoration='underline';"
onmouseout="this.style.textDecoration='none';">
Red Sox Fan Club</a>
JavaScript, Fifth Edition
60
Understanding Mouse Events
• Common use
• Displaying alternate image or explanatory text when the
mouse passes over an element
Figure 4-5 Real estate page with
the mouse over the Townhouse link
JavaScript, Fifth Edition
61
Understanding Mouse Events
• defaultStatus property
– Specifies status bar default text appearing whenever the
mouse not positioned over a link
• Syntax
window.defaultStatus = "status bar text here";
• Common use of rollovers
– Replace (or swap) Web page image
• Example:
– Change displayed image
JavaScript, Fifth Edition
62
Understanding Mouse Events
<p><img src="v500tec.gif" height="90px" width="700px"
alt="Banner images"
onmouseover="this.src='showroom.gif'"
onmouseout="this.src='v500tec.gif'" /></p>
Figure 4-7 Web page before the mouse passes over the image
Figure 4-8 Web page with the mouse placed over the image
JavaScript, Fifth Edition
63
Understanding Mouse Events
• mousedown and mouseup events
– mousedown event occurs when pointing to an
element while holding the mouse button down
– mouseup event occurs when releasing the mouse
button
<p><img src="v500tec.gif" height="90px" width="700px"
alt="Banner images" onmousedown="this.src='showroom.gif'"
onmouseup="this.src='v500tec.gif'" /></p>
JavaScript, Fifth Edition
64
TIMERS
JavaScript, Fifth Edition
65
Working with Timeouts and Intervals
• Window object’s timeout and interval methods
– Creates code that executes automatically
• setTimeout() method
– Executes code after a specific amount of time
– Executes only once
– Syntax
var variable = setTimeout("code", milliseconds);
• clearTimeout() method
– Cancel setTimeout() before its code executes
• Example on next slide
JavaScript, Fifth Edition
66
Working with Timeouts and Intervals
(cont’d.)
...
<script type="text/javascript">
/* <![CDATA[ */
var buttonNotPressed = setTimeout(
"window.alert('You must press the OK button to continue!')",
10000);
function buttonPressed() {
clearTimeout(buttonNotPressed);
window.alert("The setTimeout() method was cancelled!");
}
/* ]]> */
</script>
</head>
<body>
<form action="">
<input type="button" value=" OK “ onclick="buttonPressed();" />
</form>
</body>
</html>
JavaScript, Fifth Edition
67
Working with Timeouts and Intervals
(cont’d.)
• setInterval() method
– Repeatedly executes the same code after being
called only once
• clearInterval() method
– Used to clear setInterval() method call
JavaScript, Fifth Edition
68
Working with Timeouts and Intervals
(cont’d.)
<script type="text/javascript">
/* <![CDATA[ */
var curBanner="cycle1";
function changeBanner() {
if (curBanner == "cycle2") {
document.images[0].src = "v500tec.gif";
curBanner = "cycle1";
}
else {
document.images[0].src = "showroom.gif";
curBanner = "cycle2";
}
}
/* ]]> */
</script>
</head>
<body onload="var begin=setInterval('changeBanner()',
2000);">
<p><img src="v500tec.gif" height="90px" width="700px"
alt="Banner images" /></p>
</body>
</html>
JavaScript, Fifth Edition
69
HISTORY OBJECT
JavaScript, Fifth Edition
70
The History Object
• History object
– Maintains internal list (history list)
• All documents opened during current Web browser
session
• Security features
– Will not display URLs contained in the history list
– Internet Explorer restriction
• Only possible if currently displayed Web page exists in
same domain as Web page containing JavaScript code
JavaScript, Fifth Edition
71
The History Object (cont’d.)
Table 4-5 Methods of the History object
JavaScript, Fifth Edition
72
The History Object (cont’d.)
• go() method
– Allows navigation to a specific previously visited Web
page
• History object length property
– Provides specific number of documents opened
during the current browser session
– Syntax
window.alert("You have visited " +
history.length + " Web pages.");
JavaScript, Fifth Edition
73
LOCATION OBJECT
JavaScript, Fifth Edition
74
The Location Object
• Location object
– Allows changes to a new Web page from within
JavaScript code
• Location object properties allow modification of URL
individual portions
– Web browser automatically attempts to open that new
URL
JavaScript, Fifth Edition
75
The Location Object (cont’d.)
Table 4-6 Properties of the Location object
Table 4-7 Methods of the Location object
JavaScript, Fifth Edition
76
The Location Object (cont’d.)
• Location object’s assign() method
– Same action as changing the href property
– Loads a new Web page
• Location object’s reload() method
– Equivalent to the Firefox Reload button, Internet
Explorer Refresh button
– Causes current page to open again
• Location object’s replace() method
– Replaces currently loaded URL with a different one
JavaScript, Fifth Edition
77
NAVIGATOR OBJECT
JavaScript, Fifth Edition
78
The Navigator Object
• Navigator object
– Obtains information about current Web browser
– Example: determine type of Web browser running
Table 4-8 Properties of the Navigator object
JavaScript, Fifth Edition
79
The Navigator Object (cont’d.)
with statement
Eliminates need to retype object name
When properties of the same object being referenced in a series
with (navigator) {
document.write("<p>Browser code name: "
+ appCodeName + "<br />");
document.write("Web browser name: "
+ appName + "<br />");
document.write("Web browser version: "
+ appVersion + "<br />");
document.write("Operating platform: "
+ platform + "<br />");
document.write("User agent: " + userAgent + "</p>");
}
JavaScript, Fifth Edition
80
SCREEN OBJECT
JavaScript, Fifth Edition
81
The Screen Object
• Screen object
– Obtains information about display screen’s size,
resolution, color depth
• Common use of Screen object properties
– Centering a Web browser window in the middle of the
display area
JavaScript, Fifth Edition
82
The Screen Object (cont’d.)
Table 4-9 Properties of the Screen object
JavaScript, Fifth Edition
83
The Screen Object (cont’d.)
• colorDepth and pixelDepth properties
– Useful in determining display color resolution
• Common Screen object properties uses
– Center a Web browser window
– Example:
var
var
var
var
var
winWidth=300;
winHeight=200;
leftPosition = (screen.width-winWidth)/2;
topPosition = (screen.height-winHeight)/2;
optionString = "width=" + winWidth + ",height="
+ winHeight + ",left=" + leftPosition + ",top="
+ topPosition;
OpenWin = window.open("", "CtrlWindow", optionString);
JavaScript, Fifth Edition
84