Get great deals from the
Internet via E-mail CLICK
HERE
Member Newsletter
BUILD
YOUR SITE
Advanced:
A JavaScript Picture Book Tribute To My Family
JavaScript
is a great technology that is gaining in popularity with
more solid support from the movers and shakers of the Internet
industry, particularly the W3C, which is the standards body
charged with focusing the ongoing development energies of
the Web. Internet Explorer and Navigator now support a larger
common conceptual base for JavaScript. With
either browser, you can perform a JavaScript technique that
allows image swapping (as discussed in a previous issue
of this newsletter, click
here to view the previous topic). In that example, we
showed how to use events created by the visitor to cause
dynamic effects to occur.
Often
the next question is "So, how do I generate events
myself that can be used to trigger these effects instead
of relying on a visitor to generate them?" The answer
is setTimeout().
In this
newsletter we will examine the setTimeout event through
an example of a picture book, in which a collection of pictures
are displayed in sequence, changing at a pre-set interval.
The
JavaScript function setTimeout is an event generator. It
is designed to evaluate an expression or call a function
after so many milliseconds have elapsed. The setTimeout
function can be used to cause the browser to wait for a
specified period of time and then to DO whatever it is you
want it to do. In this example we'll show you how to use
this event generator to flip through pictures in a picture
book application. You can easily incorporate a similar application
on your Web pages either by cutting and pasting this code
and then altering the references to timing intervals, picture
names, and locations, or by developing it from scratch if
you have the desire to understand more deeply how this process
works. Here are the steps necessary to create this example:
1. Begin
by pre-caching your images. To do this, simply create a
container for each object in the following fashion.
<SCRIPT language="JavaScript"><!--
image1 = new Image();
image1.src = "photo1.gif";
image2 = new Image();
image2.src = "photo2.gif";
image3 = new Image();
image3.src = "photo3.gif";
image4 = new Image();
image4.src = "photo4.gif";
//--></SCRIPT>
This code needs to go into the body section of your document
(anywhere in the body is fine because it will not be displayed;
it is only creating containers which force the contents
of those containers to be cached, or stored locally on the
visitor's computer). This way it will get loaded with the
rest of the body content speeding up the image switching.
More importantly, the onLoad event will not occur until
these files are present in the cache. (See the notes below
for more information on why this is so important.)
2. Create
an <IMG> tag specifically where you want the picture
book to appear in your Web page. You must also name the
image object because we must use the Document Object Model
to access the contents of the image container in order to
change the picture, and the easiest method to do so is by
accessing the object through its "name". The image
tag below is named "picture_book", for example.
<IMG NAME="picture_book" width=200 height=200>
(Note: If you wrap the above tag inside of <SCRIPT>
tags and include a <NOSCRIPT> section, then you provide
a graceful deprecation of your page to non-script enabled
browsers. Though these dinosaurs are slowly disappearing,
some still use them.) Here is an example of the <IMG>
element inserted using the <SCRIPT> method. This can
be done INSTEAD of the above method.
<SCRIPT>
document.write('<IMG NAME="picture_book" width=200
height=200>');
</SCRIPT>
<NOSCRIPT>
Because your browser doesn't support JavaScript, it will
not allow my picture book to function. Sorry, it's really
neat. You might want to download one of the latest browsers
for free.
</NOSCRIPT>
3. Add a <SCRIPT> section that will perform the image
replacement, and set the timer event. If you used the <SCRIPT>
method above, you can put these items into that <SCRIPT>
section if you want.
<SCRIPT>
image_number=1; // which image to display
function start_book(){
document.picture_book.src="photo"+image_number+".gif";
if (++image_number>4) image_number=1; setTimeout("start_book()",4000);
// 4000 milliseconds is 4 seconds
}
</SCRIPT>
Notes on Step 3:
a. Because we have four images in this example, we need
a counter mechanism that can keep track of which image we
are supposed to show next. This example uses a variable
called "image_number", which is set OUTSIDE of
the start_book function, why? Because we only want to SET
it once, each subsequent access will be to perform math
with it.
b.
Immediately following the line that sets the <IMG>
source (src), the counter mechanism is set in motion. That
single line does two things: first, it increments the value
in image_number by one (that's what ++ means; the reason
that ++ occurs BEFORE image_number is because it forces
the increment to occur BEFORE the greater than comparison);
second, immediately after incrementing it, that new value
is checked to see if it is greater than 4. If it is, the
value is set to 1. Otherwise, it's left alone. (This is
because there are files named photo1.gif, photo2.gif, photo3.gif,
and photo4.gif, but if the counter gets to 5 we'll have
an error because there is no file named photo5.gif, so we
reset the counter to 1.)
4.
Add an onLoad event to your <BODY> tag. The onLoad
event is simply onLoad="start_book()". Notice
that "L" in "Load" is capitalized: Because
JavaScript is a case-sensitive language, you must duplicate
letter case exactly or it will not work. Here is an example
of a <BODY> tag with the event added. Keep in mind
that your tag may have other elements in it too, such as
elements that set a background color or image or that set
the link colors.
<BODY onLoad="start_book()">
The
picture book example
My Dynamic Family
What
are the specifics of the setTimeout event?
The
setTimeout event is pretty simple. You need to know a few
details about it in order to implement it successfully.
The syntax is as follows:
The
expression can be a JavaScript statement that causes something
to be evaluated immediately (such as "X++") or
a call to a function as we use in the examples on this page.
Milliseconds is the timing interval between when this statement
is initialized and when the event named as the expression
or function_name will occur. Milliseconds can seem like
overkill for a Web application, but if you can get an event
to occur in milliseconds, more power to you. Consider that
1000 milliseconds is 1 second; we've used seconds in our
examples by multiplying the speed by 1000.
It is
important to point out that by itself, setTimeout is pretty
harmless, but using it in tandem with a JavaScript loop
can cause some problems (read the next section for more
information). The event will occur only one time each time
it is called.
A
word of warning!
The
setTimeout generator can get you in serious trouble if you
are not careful with how it is used.
Because the combination of setTimeout is no secret and is
simple to implement, many students of JavaScript stumble
unwittingly into a trap of timing by implementing it without
knowing what can happen.
Here
is the problem. As soon as you initialize the event timer
by placing the setTimeout() call into a piece of running
script, the timer begins ticking (even if the page is NOT
done loading.) If you are using the timer to swap pictures
on your Web page and the event occurs BEFORE the page has
completely loaded (and thus, been cached), then you will
initiate a new request to the Web server for the next picture.
How is that a problem? Because if you are regenerating the
event infinitely your page will never finish loading. Instead,
each new picture swap will result in another request to
the Web server for as long as a visitor is viewing your
Web page. This
will make the server administrators very unhappy with you
and you will likely find yourself at the receiving end of
their frustration.
To prevent
the problem, do
not start the timer until AFTER the entire Web page has
downloaded. Here is how you accomplish this feat:
1. Put your setTimeout() call in a function as we have done
in the example picture book, and
then...
2. Add onLoad="function_name()"
(replacing function_name with whatever you name the function
where the setTimeout call is) into your <BODY> tag
as we have done in the example
as well. The "onLoad" event does not occur until
the browser says, "Okay, I'm done loading everything
on this page," at which point your function is called
and, voilà, the fun begins.
Where
do we go from here?
What
a great question. (I'm glad I asked it.) You could easily
expand on the picture book example by including animated
pictures in place of the static pictures, but keep in mind
they take longer to download. Perhaps you could also link
the properties of the table to controls which the visitor
can use to interact with the picture book. For example,
the control below will alter the picture flipping speed
in the picture book example on this page. Try changing the
value to the number of seconds you want.