JavaScript can load the images and then give them the appearance of animation by using a timer that will be set to put a new image on the page at short repeating intervals, similar to fl
Trang 112.6 Animation and Timers
On a small but thick pad of paper a boy has drawn a stick man on each page For each page
he draws his stick man in a sightly different position, maybe moving one leg up and an
arm down After filling the pad with as many little stick man pictures as he wants to draw,
he goes to his friend and starts rapidly flipping the pages Voila! He has made a little movie!
Although seemingly primitive, this is the idea behind JavaScript animation Instead of
flip-ping through a pad of drawings, the stick man drawings can be scanned into your
com-puter as a set of images as shown in Figure 12.26 JavaScript can load the images and then
give them the appearance of animation by using a timer that will be set to put a new image
on the page at short repeating intervals, similar to flipping the pages of the small pad of
paper With JavaScript, a number of DOM elements (<img />, <div>, etc.) can be moved in
the document according to a looping mechanism or an expression tied to a timer
Two JavaScript functions used as timers are setTimeout() and setInterval(), which
allow JavaScript code to be executed at set intervals (We have seen the use of both of
these functions throughout this text.)
setTimeout(someFunction,500);
// calls someFunction() 500 milliseconds from now setInterval(someFunction,500);
Figure 12.25 An open source Web site that provides excellent examples of slideshows.
Trang 212.6.1 Changing Image Position
In Example 12.12, two stick figures have been scanned into the computer and saved as
.png files The figures are loaded and alternately displayed on the screen at short intervals
giving the illusion that the stick figure is running
E X A M P L E 1 2 1 2
<html>
<head><title>animation</title>
<script type="text/javascript">
2 function animate(whichone){
4 document.images["stickman"].src=pics[whichone];
5 window.setTimeout("animate(" + (whichone + 1)+");",500);
}
6 window.onload=function(){
7 pics=new Array( "0.png","1.png","0.png","1.png");
}
</script>
</head>
<body bgcolor=lightgreen>
9 <img src="0.png" name="stickman" />
</body>
</html>
E X P L A N A T I O N
1 A global variable called pics is declared, which will be available to all the functions
in this JavaScript code
2 The function called animate() is called the first time on line 8 The initial value of
pos is 0 On line 5 the window’s setTimeout() function calls animate() repeatedly
every 5 sec Each time animate() is called the whichone value is incremented by 1.
3 The value of whichone is changed each time the function is called by using the
modulus operator The remainder will be a number between 0 and 4, not
includ-ing 4 This number is used as an index in the pics array to select an image.
4 The source file for the stick man image file changes each time the function is
called, so rapidly that the stick man appears to be running
5 This is where the timer is set to cause the animation of the stick man
6, 7, 8 When the page has loaded this anonymous function will create an array of images,
and then call the animate() function on line 2 with an initial value of 0.
9 The initial stick man image is displayed in the document
Trang 312.6.2 Changing Image Height and Width Properties
In Example 12.13 the width and height properties of the image object allow us to change
the size of an image dynamically By increasing the width of a black bar image at set time
intervals, the bar appears to be lengthening as it is displayed
Figure 12.26 Animated stick man appears to be running.
E X A M P L E 1 2 1 3
<html>
<head><title>Progress Bar</title>
<script type="text/javascript">
// Set the width of the image every 5 second
2 if(document.images["bar"].width < 300){
3 document.images["bar"].width += 5;
document.images["bar"].height = 10;
// Setting the height keeps the bar from getting taller // as the image is widened.
} else{
} }
6 window.onload = function(){
timer = setInterval("progress();",500);
// Image is stretched every 5 seconds
}
</script>
Trang 412.7 What You Should Know
A story book without pictures is like a Web page without images: Doable, but not much
fun This chapter demonstrated some of the ways you can animate a Web page using
JavaScript to manipulate images Now you should know:
1 How JavaScript stores the images from a Web page
2 How JavaScript stores the hyperlinks from a Web page
3 How to draw the document tree with images and links using the Legacy DOM
4 How to figure out how many links and images are on the page
</head>
<body bgColor="aquamarine">
7 <img src="blackbar.bmp" height="10" name="bar"/>
<p>Watching your Progress</p>
</body>
</html>
E X P L A N A T I O N
1 This user-defined function will cause the image to be stretched horizontally every
.5 seconds
2 As long as the length of the bar is less than 300 pixels, we enter this if block If
not, the interval timer is stopped
3 The width of the image is increased by 5 pixels every 5 seconds
4 The height of the bar is at a constant 10; otherwise the browser will attempt to
increase the height of the bar to be proportional to the increase in the length
5 The variable, timer, will be assigned the return value of the setInterval() function
6 The window’s onload method is assigned an anonymous function When the page
has finished loading, this function starts the timer, set Interval(), which in turn
calls the progress() function every 5 seconds
7 The image of a black bar will be displayed when the page is loaded (see Figure
12.27)
Figure 12.27 Making an image grow!
E X A M P L E 1 2 1 3
Trang 55 How the image name is used to reference a particular image
6 How to replace images with the src property.
7 How to create a simple rollover
8 What considerations contribute to how you set up a slideshow
9 What preloading accomplishes
10 About the Image constructor
11 How event handlers work with images
12 How links work with images
13 How to use the link object and imagemaps.
14 How to create a simple slideshow
15 How timers work with animation
16 How to resize an image
17 How to randomly display a set of images
Trang 61 Create an array of different sports images so that each time the page loads, a
random image is displayed Center the image on the page, and specify width and height Choose a background color
2 Create a document entitled “Our Universe.” The page will consist of three
frames The top frame will be a horizontal frame to contain the title, “Our Uni-verse,” The left frame will contain a form with radio buttons representing the names of planets and a textbox The background image in the second frame will
be a sky filled with stars When the user clicks a radio button, a picture of the selected planet will appear in the second frame A description of the planet will appear in a textbox under the form in the left frame
3 Create a JavaScript program that will produce a slideshow It will contain an
array of four images Preload the images A timer will be set so that a new image replaces another image every 10 seconds If the user clicks a button labeled
Start, the timer starts the image replacement If the user clicks a button labeled Stop, the timer stops it.
4 When the page is loaded, call a function that will preload two images, each
associated with a link When the mouse rolls over an image, replace the first image with the second image When the mouse moves away from the image, the first image appears
5 Create the illusion of a car driving across the screen using animation Move the
car to the right a certain number of pixels using a timer Create two buttons to start and stop the car
6 Use a program such as Windows Paint to draw three traffic lights Preload the
three images Every 30 seconds change the light When the light turns green, say
“Go” in a little box under the light, for yellow “Slow down,” and for red, “Stop.”
7 Find a picture of the major planets in our solar system Create an imagemap so
that when the user clicks one of the planets, a popup window is opened describing that planet
E x e r c i s e s
Trang 713
Handling Events
13.1 Introduction to Event Handlers
JavaScript reacts to events We have been talking about events since Chapter 1,
“Intro-duction to JavaScript,” because events are inherently part of almost all Web pages and
they make the pages interactive and dynamic JavaScript events are asynchronous,
meaning that they can happen at any time They are actions that are initiated by a user
visiting a Web page; for example, if the user submits a form or moves the mouse over a
link or an image, he or she might trigger an event When an event occurs, your browser
has some default actions it takes; for example, if you click on a link, it opens up the
loca-tion in the href JavaScript can also respond to a user’s acloca-tion and execute code in
response The event itself may be blur, click, change, keystroke, and so on We have seen
many examples using event handlers in previous examples This chapter explains how
each of the event handlers responds when events occur on different objects
JavaScript has three event models for programming events: the inline model, the
scripting model, and the DOM 2 model In this chapter we discuss the inline model and
the scripting model In Chapter 15, “The W3C DOM and JavaScript,” we describe the
way events are handled by the W3C DOM Level 2 model and its pros and cons
13.2 The Inline Model for Handling Events
This is the oldest and easiest way to handle events With the inline model, the event
han-dlers are attributes of an HTML tag and are used to handle the event for which they are
named For example the onClick handler will handle the click event, the onSubmit handler
will handle the submit event, and so on Although a very popular way of dealing with
events, the disadvantage of using the inline model is that JavaScript is intrusive; that is, it
is not separated from the HTML markup The inline model will be used here to show you
what the many event handlers do, and how they affect the objects in a document Later in
this chapter, we discuss the JavaScript scripting method for handling events