SlideShare una empresa de Scribd logo
1 de 53
JavaScript, Third Edition

Chapter 9
Introduction to the Document
Object Model (DOM)
Objectives
• Learn about dynamic Web pages

• Study the Document Object Model (DOM)
• Work with the Image object
• Create animation with the Image object
• Learn how to cache images
JavaScript, Third Edition

2
Introduction
• Businesses want:
– Web sites to include Formatting and images that can
be updated without the user having to reload a Web
page from the server
– Innovative ways to use animation and interactive Web
pages to attract and retain visitors
– To make their Web sites effective and easy to navigate

JavaScript, Third Edition

3
Introduction (Cont.)
• These kinds of effects:
– Cannot be created with standard Extensible Hypertext
Markup Language (XHTML)
– Needs the use of Dynamic HTML (DHTML)

• One of the most important aspects of DHTML is the
Document Object Model (DOM)

JavaScript, Third Edition

4
Creating Dynamic Web Pages
•

Dynamic:
–

Web pages that respond to user requests through
buttons or other kinds of controls

–

Various kinds of effects, such as animation, that
appear automatically in a Web browser

JavaScript, Third Edition

5
Creating Dynamic Web Pages
(Cont.)
• A dynamic Web page can allow a user to:
– Change the document background color
– Submit a form and process a query
– Participate in an online game or quiz

JavaScript, Third Edition

6
Creating Dynamic Web Pages
(Cont.)
• To make Web pages truly dynamic, you need more
than just XHTML
– Need Dynamic HTML or (DHTML)

JavaScript, Third Edition

7
Creating Dynamic Web Pages
(Cont.)
• Dynamic HTML (DHTML):
– Refers to a combination of technologies that make
Web pages dynamic

• The term DHTML is:
– Combination of JavaScript, XHTML, CSS, and the
Document Object Model

JavaScript, Third Edition

8
JavaScript, Third Edition

9
See this game at:
plaza.harmonix.ne.jp/~jimmeans

JavaScript, Third Edition

10
The Document Object Model
• Is at the core of DHTML

• Represents the Web page displayed in a window
• Each element on a Web page is represented in the
DOM by its own object

• This makes it possible for a JavaScript program to:
– Access individual elements on a Web page
– Change elements individually, without having to
reload the page from the server
JavaScript, Third Edition

11
The Document Object Model

JavaScript, Third Edition

12
The Document Object Model
Document

JavaScript, Third Edition

13
Document Object Properties
• Examples: see StatesCapitals.html
function documentStatistics(){
alert(document.title + “n” + document.URL + “n” +
document.lastModified);
}

document.title = “WebAdventure, Inc.”;

JavaScript, Third Edition

14
Document Object Properties

JavaScript, Third Edition

15
Document Object Methods
• Can be used for dynamically generating and
manipulating Web pages
• Cannot be used to change content in a Web
page after it has been rendered

JavaScript, Third Edition

16
Document Object Model
• Document Object Methods
– close() Closes a new document that was created
with the open() method
– open() Opens a new document in a window or
frame
– write() Adds new text to a document
– writeln() Adds new text to a document, followed
by a line break.
JavaScript, Third Edition

17
Document Object Methods

JavaScript, Third Edition

18
Document Object Methods (Cont.)
• Open() method:
– Could be used to create a new document in a window or frame
– Use the write() and writeln() methods to add content to the new
document

– can include an argument specifying the MIME type of the
document to be displayed.
• default (no argument) is text/html.

JavaScript, Third Edition

19
Document Object Methods (Cont.)
• The close() method:
– Notifies the Web browser that
• You are finished writing to the window or frame
• The document should be displayed

JavaScript, Third Edition

20
Document Object Methods (Cont.)
• write(), writeln()
– if use these without first using the open() method,
they overwrite the contents of the current
document.
– if used after an open() they write into the new
browser window.

JavaScript, Third Edition

21
Document Object Methods
• Example: see WebStats.html

JavaScript, Third Edition

22
The Document Object Model

Image

JavaScript, Third Edition

23
The Image Object
• Represents an image created using the <img> element

• Use to dynamically change an image displayed on a
Web page
• Image objects for each <img> element:
– Assigned to elements of images[] array in the order
they appear on the Web page

JavaScript, Third Edition

24
The Image Object (Cont.)
• An Image object contains various properties
and events that you can use to manipulate your
objects

JavaScript, Third Edition

25
The Image Object (Cont.)

JavaScript, Third Edition

26
The Image Object (Cont.)

JavaScript, Third Edition

27
The Image Object (Cont.)
• The src property:
– One of the most important parts of image object
– Allows JavaScript to dynamically change an image
– Changing assigned value also changes the src attribute
associated with an <img> element
• Dynamically changes an image displayed on a Web
page
• See
– ChangeImage.html
– Programmers.html
JavaScript, Third Edition

28
Animation with the Image Object
• simple animation on a Web page:
– Created by a sequence of images changed automatically

• To create an animated sequence:
– use setInterval() or setTimeout() methods to cycle
through the frames in an animation series
– Each iteration of a setInterval() or setTimeout() method
changes the frame displayed by an <img> element
– Change the frame by changing the src attribute of an
image
– Examples:
• Advertisement.html
JavaScript, Third Edition

29
Dynamic HTML
• Animation with the Image Object
– True animation
• Requires a different graphic, or frame, for each
movement that a character or object makes
• Frames can be automatically cycled using JavaScript
– Ensure each frame is consistent in size and position

• See runner0.html (code on next slide)

JavaScript, Third Edition

30
JavaScript, Third Edition

31
JavaScript, Third Edition

32
JavaScript, Third Edition

33
JavaScript, Third Edition

34
Animation
• Examples:
– Dribble.html

JavaScript, Third Edition

35
Animation
• Animation Problem: JavaScript does not
keep copies of each image in memory.
• each time a different image is loaded, JS must
physically open or reopen the image from
source.
• Solution: image caching. Save image files in
memory on local computer.

JavaScript, Third Edition

36
Image Caching
• Technique for eliminating multiple downloads of the
same file
• Temporarily stores image files in memory on a local
computer
• Allows JavaScript to store and retrieve an image from
memory rather than download the image each time it is
needed
JavaScript, Third Edition

37
Image Caching (Cont.)
•

Images are cached using the Image() constructor of
the Image object
–

•

Creates new Image object

Three steps for caching an image in JavaScript:
1. Create a new object using the Image() constructor
2. Assign a graphic file to the src property of the new
Image object
3. Assign the src property of the new Image object to
the src property of an <img> element
JavaScript, Third Edition

38
Dynamic HTML
• Image Caching Example.

1. image object created

<head>
<script language=“JavaScript”>
<!-- hide from incompatible browsers
function putImage(){
newImage = new Image();
newImage.src = “graphic.jpg”;
document.myImage.src = newImage.src;
}
// stop hiding -->
</script>
</head>
3.
<body onLoad = “putImage();”>
<img name = „myImage‟ src=“”>
</body>

2. image object given a source.
The image is now cached in
memory.

Document image is assigned
the cached image.

4. If use the line
document.myImage.src = “graphic.jpg”
then graphic loads every time the
line is executed. No caching
JavaScript, Third Edition
39
The RunnerCache0.html program

JavaScript, Third Edition

40
JavaScript, Third Edition

41
Animation
• See the following web pages:
– RunnerCache0.html
– RockingHorseCache.html
– FatCatDancing.html

JavaScript, Third Edition

42
Animation
• Image Caching Problem
– Erratic animation can occur due to all images not
being stored in Image objects before animation
begins
– a page may finish loading before all the images
have finished downloading.

JavaScript, Third Edition

43
Animation
• Image Caching
– To ensure all images are cached prior to
commencing animation:
• Use onLoad event handler of the Image object

JavaScript, Third Edition

44
<HTML>
RunnerCache1.html
<HEAD>
<TITLE>Runner</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
var runner = new Array(6);
Create an array.
var curRunner = 0;
Each element will
var startRunning;
be an Image object.
var imagesLoaded = 0;
For each element in the array:
for(var i = 0; i < 6; ++i) {
runner[i] = new Image();
1. Create an Image object
runner[i].src = "runner" + i + ".jpg";
runner[i].onload = runMarathon;
2. Assign the appropriate
}
graphics file for the source

3. Have the Image object call
the function runMarathon when
that object has finished loading.
JavaScript, Third Edition

45
function runMarathon() {
++imagesLoaded;
if (imagesLoaded == 6)
startRunning=setInterval("marathon()",100);
}
function marathon() {
if (curRunner == 5)
curRunner = 0;
else
++curRunner;
document.animation.src = runner[curRunner].src;
}

JavaScript, Third Edition

When all images have
loaded, start the interval
timer.

This line will NOT have
to get the image from
the server because the
runner array contains
image Objects, not just
strings.

46
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</SCRIPT>
</HEAD>
<BODY>
<P><IMG SRC="runner1.jpg" NAME="animation"></P>
name of the image.
</BODY>
Body does nothing.
</HTML>

See RockingHorseImageLoad.html also!

JavaScript, Third Edition

47
Animation
• Image Caching with preLoad Example.
– RunnerCache1.html

JavaScript, Third Edition

48
Chapter Summary
• Dynamic HTML (DHTML):
– Combination of technologies that make Web pages
dynamic
– DHTML is a combination of JavaScript, XHTML,
CSS, and the Document Object Model

• Document Object Model, or DOM:
– At the core of DHTML

– Represents the Web page displayed in a window
JavaScript, Third Edition

49
Chapter Summary (cont.)
• The open() method:
– Creates a new document in a window or frame

• The close() method:
– Notifies Web browser that you are finished writing to
the window or frame and that the document should be
displayed

• An Image object:
– Represents an image created using the <img> element

JavaScript, Third Edition

50
Chapter Summary (cont.)
• Src property:
– One of the most important properties of the Image
object

– Allows JavaScript to change an image dynamically

JavaScript, Third Edition

51
Chapter Summary (cont.)
• Image caching:
– Technique for eliminating multiple downloads of the
same file
– Temporarily stores image files in memory
– Allows JavaScript to store and retrieve an image from
memory rather than downloading the image each time
it is needed

JavaScript, Third Edition

52
Chapter Summary (cont.)
• Onload event handler of the Image:
– Use it to be certain that all images are downloaded into
a cache before commencing an animation sequence

JavaScript, Third Edition

53

Más contenido relacionado

Similar a Chapter09 slideshow2

ARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: RolloversARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: RolloversGilbert Guerrero
 
ARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: RolloversARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: RolloversGilbert Guerrero
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceSebastian Springer
 
Chapter 9 Getting Started with JavaScript
Chapter 9 Getting Started with JavaScriptChapter 9 Getting Started with JavaScript
Chapter 9 Getting Started with JavaScriptDr. Ahmed Al Zaidy
 
Web browser architecture
Web browser architectureWeb browser architecture
Web browser architectureNguyen Quang
 
Creating a web gallery lightbox2 final
Creating a web gallery lightbox2 finalCreating a web gallery lightbox2 final
Creating a web gallery lightbox2 finalDaniel Downs
 
2.6 flickr, image list, and network objects
2.6   flickr, image list, and network objects2.6   flickr, image list, and network objects
2.6 flickr, image list, and network objectsallenbailey
 
Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)
Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)
Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)Nuzhat Memon
 
SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...
SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...
SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...Brian O'Gorman
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
MTA animations graphics_accessing data
MTA animations graphics_accessing dataMTA animations graphics_accessing data
MTA animations graphics_accessing dataDhairya Joshi
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the BrowserFITC
 

Similar a Chapter09 slideshow2 (20)

Ddpz2613 topic9 java
Ddpz2613 topic9 javaDdpz2613 topic9 java
Ddpz2613 topic9 java
 
ARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: RolloversARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: Rollovers
 
ARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: RolloversARTDM 170, Week 3: Rollovers
ARTDM 170, Week 3: Rollovers
 
Extjs
ExtjsExtjs
Extjs
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web Performance
 
Chapter 9 Getting Started with JavaScript
Chapter 9 Getting Started with JavaScriptChapter 9 Getting Started with JavaScript
Chapter 9 Getting Started with JavaScript
 
Web browser architecture
Web browser architectureWeb browser architecture
Web browser architecture
 
Creating a web gallery lightbox2 final
Creating a web gallery lightbox2 finalCreating a web gallery lightbox2 final
Creating a web gallery lightbox2 final
 
IP Unit 2.pptx
IP Unit 2.pptxIP Unit 2.pptx
IP Unit 2.pptx
 
2.6 flickr, image list, and network objects
2.6   flickr, image list, and network objects2.6   flickr, image list, and network objects
2.6 flickr, image list, and network objects
 
Performance (browser)
Performance (browser)Performance (browser)
Performance (browser)
 
Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)
Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)
Std 12 Computer Chapter 2 Cascading Style Sheet and Javascript (Part-2)
 
Presentation Tier optimizations
Presentation Tier optimizationsPresentation Tier optimizations
Presentation Tier optimizations
 
SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...
SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...
SHOW202: How to customize Lotus Quickr Templates Using HTML, Javascript and C...
 
Web works hol
Web works holWeb works hol
Web works hol
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
MTA animations graphics_accessing data
MTA animations graphics_accessing dataMTA animations graphics_accessing data
MTA animations graphics_accessing data
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Javascript libraries
Javascript librariesJavascript libraries
Javascript libraries
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the Browser
 

Último

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Último (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Chapter09 slideshow2

  • 1. JavaScript, Third Edition Chapter 9 Introduction to the Document Object Model (DOM)
  • 2. Objectives • Learn about dynamic Web pages • Study the Document Object Model (DOM) • Work with the Image object • Create animation with the Image object • Learn how to cache images JavaScript, Third Edition 2
  • 3. Introduction • Businesses want: – Web sites to include Formatting and images that can be updated without the user having to reload a Web page from the server – Innovative ways to use animation and interactive Web pages to attract and retain visitors – To make their Web sites effective and easy to navigate JavaScript, Third Edition 3
  • 4. Introduction (Cont.) • These kinds of effects: – Cannot be created with standard Extensible Hypertext Markup Language (XHTML) – Needs the use of Dynamic HTML (DHTML) • One of the most important aspects of DHTML is the Document Object Model (DOM) JavaScript, Third Edition 4
  • 5. Creating Dynamic Web Pages • Dynamic: – Web pages that respond to user requests through buttons or other kinds of controls – Various kinds of effects, such as animation, that appear automatically in a Web browser JavaScript, Third Edition 5
  • 6. Creating Dynamic Web Pages (Cont.) • A dynamic Web page can allow a user to: – Change the document background color – Submit a form and process a query – Participate in an online game or quiz JavaScript, Third Edition 6
  • 7. Creating Dynamic Web Pages (Cont.) • To make Web pages truly dynamic, you need more than just XHTML – Need Dynamic HTML or (DHTML) JavaScript, Third Edition 7
  • 8. Creating Dynamic Web Pages (Cont.) • Dynamic HTML (DHTML): – Refers to a combination of technologies that make Web pages dynamic • The term DHTML is: – Combination of JavaScript, XHTML, CSS, and the Document Object Model JavaScript, Third Edition 8
  • 10. See this game at: plaza.harmonix.ne.jp/~jimmeans JavaScript, Third Edition 10
  • 11. The Document Object Model • Is at the core of DHTML • Represents the Web page displayed in a window • Each element on a Web page is represented in the DOM by its own object • This makes it possible for a JavaScript program to: – Access individual elements on a Web page – Change elements individually, without having to reload the page from the server JavaScript, Third Edition 11
  • 12. The Document Object Model JavaScript, Third Edition 12
  • 13. The Document Object Model Document JavaScript, Third Edition 13
  • 14. Document Object Properties • Examples: see StatesCapitals.html function documentStatistics(){ alert(document.title + “n” + document.URL + “n” + document.lastModified); } document.title = “WebAdventure, Inc.”; JavaScript, Third Edition 14
  • 16. Document Object Methods • Can be used for dynamically generating and manipulating Web pages • Cannot be used to change content in a Web page after it has been rendered JavaScript, Third Edition 16
  • 17. Document Object Model • Document Object Methods – close() Closes a new document that was created with the open() method – open() Opens a new document in a window or frame – write() Adds new text to a document – writeln() Adds new text to a document, followed by a line break. JavaScript, Third Edition 17
  • 19. Document Object Methods (Cont.) • Open() method: – Could be used to create a new document in a window or frame – Use the write() and writeln() methods to add content to the new document – can include an argument specifying the MIME type of the document to be displayed. • default (no argument) is text/html. JavaScript, Third Edition 19
  • 20. Document Object Methods (Cont.) • The close() method: – Notifies the Web browser that • You are finished writing to the window or frame • The document should be displayed JavaScript, Third Edition 20
  • 21. Document Object Methods (Cont.) • write(), writeln() – if use these without first using the open() method, they overwrite the contents of the current document. – if used after an open() they write into the new browser window. JavaScript, Third Edition 21
  • 22. Document Object Methods • Example: see WebStats.html JavaScript, Third Edition 22
  • 23. The Document Object Model Image JavaScript, Third Edition 23
  • 24. The Image Object • Represents an image created using the <img> element • Use to dynamically change an image displayed on a Web page • Image objects for each <img> element: – Assigned to elements of images[] array in the order they appear on the Web page JavaScript, Third Edition 24
  • 25. The Image Object (Cont.) • An Image object contains various properties and events that you can use to manipulate your objects JavaScript, Third Edition 25
  • 26. The Image Object (Cont.) JavaScript, Third Edition 26
  • 27. The Image Object (Cont.) JavaScript, Third Edition 27
  • 28. The Image Object (Cont.) • The src property: – One of the most important parts of image object – Allows JavaScript to dynamically change an image – Changing assigned value also changes the src attribute associated with an <img> element • Dynamically changes an image displayed on a Web page • See – ChangeImage.html – Programmers.html JavaScript, Third Edition 28
  • 29. Animation with the Image Object • simple animation on a Web page: – Created by a sequence of images changed automatically • To create an animated sequence: – use setInterval() or setTimeout() methods to cycle through the frames in an animation series – Each iteration of a setInterval() or setTimeout() method changes the frame displayed by an <img> element – Change the frame by changing the src attribute of an image – Examples: • Advertisement.html JavaScript, Third Edition 29
  • 30. Dynamic HTML • Animation with the Image Object – True animation • Requires a different graphic, or frame, for each movement that a character or object makes • Frames can be automatically cycled using JavaScript – Ensure each frame is consistent in size and position • See runner0.html (code on next slide) JavaScript, Third Edition 30
  • 36. Animation • Animation Problem: JavaScript does not keep copies of each image in memory. • each time a different image is loaded, JS must physically open or reopen the image from source. • Solution: image caching. Save image files in memory on local computer. JavaScript, Third Edition 36
  • 37. Image Caching • Technique for eliminating multiple downloads of the same file • Temporarily stores image files in memory on a local computer • Allows JavaScript to store and retrieve an image from memory rather than download the image each time it is needed JavaScript, Third Edition 37
  • 38. Image Caching (Cont.) • Images are cached using the Image() constructor of the Image object – • Creates new Image object Three steps for caching an image in JavaScript: 1. Create a new object using the Image() constructor 2. Assign a graphic file to the src property of the new Image object 3. Assign the src property of the new Image object to the src property of an <img> element JavaScript, Third Edition 38
  • 39. Dynamic HTML • Image Caching Example. 1. image object created <head> <script language=“JavaScript”> <!-- hide from incompatible browsers function putImage(){ newImage = new Image(); newImage.src = “graphic.jpg”; document.myImage.src = newImage.src; } // stop hiding --> </script> </head> 3. <body onLoad = “putImage();”> <img name = „myImage‟ src=“”> </body> 2. image object given a source. The image is now cached in memory. Document image is assigned the cached image. 4. If use the line document.myImage.src = “graphic.jpg” then graphic loads every time the line is executed. No caching JavaScript, Third Edition 39
  • 42. Animation • See the following web pages: – RunnerCache0.html – RockingHorseCache.html – FatCatDancing.html JavaScript, Third Edition 42
  • 43. Animation • Image Caching Problem – Erratic animation can occur due to all images not being stored in Image objects before animation begins – a page may finish loading before all the images have finished downloading. JavaScript, Third Edition 43
  • 44. Animation • Image Caching – To ensure all images are cached prior to commencing animation: • Use onLoad event handler of the Image object JavaScript, Third Edition 44
  • 45. <HTML> RunnerCache1.html <HEAD> <TITLE>Runner</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- HIDE FROM INCOMPATIBLE BROWSERS var runner = new Array(6); Create an array. var curRunner = 0; Each element will var startRunning; be an Image object. var imagesLoaded = 0; For each element in the array: for(var i = 0; i < 6; ++i) { runner[i] = new Image(); 1. Create an Image object runner[i].src = "runner" + i + ".jpg"; runner[i].onload = runMarathon; 2. Assign the appropriate } graphics file for the source 3. Have the Image object call the function runMarathon when that object has finished loading. JavaScript, Third Edition 45
  • 46. function runMarathon() { ++imagesLoaded; if (imagesLoaded == 6) startRunning=setInterval("marathon()",100); } function marathon() { if (curRunner == 5) curRunner = 0; else ++curRunner; document.animation.src = runner[curRunner].src; } JavaScript, Third Edition When all images have loaded, start the interval timer. This line will NOT have to get the image from the server because the runner array contains image Objects, not just strings. 46
  • 47. // STOP HIDING FROM INCOMPATIBLE BROWSERS --> </SCRIPT> </HEAD> <BODY> <P><IMG SRC="runner1.jpg" NAME="animation"></P> name of the image. </BODY> Body does nothing. </HTML> See RockingHorseImageLoad.html also! JavaScript, Third Edition 47
  • 48. Animation • Image Caching with preLoad Example. – RunnerCache1.html JavaScript, Third Edition 48
  • 49. Chapter Summary • Dynamic HTML (DHTML): – Combination of technologies that make Web pages dynamic – DHTML is a combination of JavaScript, XHTML, CSS, and the Document Object Model • Document Object Model, or DOM: – At the core of DHTML – Represents the Web page displayed in a window JavaScript, Third Edition 49
  • 50. Chapter Summary (cont.) • The open() method: – Creates a new document in a window or frame • The close() method: – Notifies Web browser that you are finished writing to the window or frame and that the document should be displayed • An Image object: – Represents an image created using the <img> element JavaScript, Third Edition 50
  • 51. Chapter Summary (cont.) • Src property: – One of the most important properties of the Image object – Allows JavaScript to change an image dynamically JavaScript, Third Edition 51
  • 52. Chapter Summary (cont.) • Image caching: – Technique for eliminating multiple downloads of the same file – Temporarily stores image files in memory – Allows JavaScript to store and retrieve an image from memory rather than downloading the image each time it is needed JavaScript, Third Edition 52
  • 53. Chapter Summary (cont.) • Onload event handler of the Image: – Use it to be certain that all images are downloaded into a cache before commencing an animation sequence JavaScript, Third Edition 53