Академический Документы
Профессиональный Документы
Культура Документы
TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by
following the capitalization style used by the manufacturer.
Netscape Communications, the Netscape Communications logo, Netscape, and Netscape Navigator are trademarks of
Netscape Communications Corporation.
Microsoft® Internet Explorer ©1996 Microsoft Corporation. All rights reserved. Microsoft, the Microsoft Internet Explorer logo,
Windows, Windows NT, and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in
the United States and/or other countries.
The author and publisher have made their best efforts to prepare this book, and the content is based upon final release soft-
ware whenever possible. Portions of the manuscript may be based upon pre-release versions supplied by software manufac-
turer(s). The author and the publisher make no representation or warranties of any kind with regard to the completeness or
accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability,
fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or indirectly
from this book.
Photographs and illustrations used in this book have been downloaded from publicly accessible file archives and are used in
this book for news reportage purposes only to demonstrate the variety of graphics resources available via electronic access.
Text and images available over the Internet may be subject to copyright and other rights owned by third parties. Online avail-
ability of text and images does not imply that they may be reused without the permission of rights holders, although the
Copyright Act does permit certain unauthorized reuse as fair use under 17 U.S.C. Section 107.
Copyright ©1999 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. No part of this pub-
lication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy,
photograph, magnetic or other record, without the prior agreement and written permission of the publisher.
2492web1.qxd 3/4/99 10:18 AM Page 1
B O N U S C H A PT E R
O N E 1
Creating Web Page Widgets
■ What’s a Widget?
■ Scrolling Messages
I t seems like the most popular Web pages always have the best adornments—
scrolling marquees, animated icons, or dynamically updated advertisements. To
some extent, these novelties help to contribute to the popularity of these pages.
The Web, after all, is the showcase for everything that is new and cool.
In this chapter, we’ll cover using JavaScript to create a variety of interesting
widgets for your Web pages. These widgets can be used to simplify the develop-
ment of your pages and to add features that your users will find helpful and
interesting. I’ll present a variety of ways in which JavaScript can be used to facili-
tate the way you display advertisements, and I’ll show you how to develop and
display the number of “hits” your Web sites and Web pages are enjoying. You’ll
also learn how to create scrolling text and images and animated icons. Finally, I’ll
present examples of features that allow users to control how your Web pages are
displayed. When you finish this chapter, you’ll be able to enhance your Web
pages with all of these new features.
What’s a Widget?
Widgets are common components that can be used over and over. They have been
developed to fill a common need and can be easily tailored for use in a variety of
situations.
In this chapter, you’ll learn how to develop and use a variety of widgets with
your Web pages. Some of the widgets, such as animated icons and scrolling text
marquees, will need to be tailored for a particular application. Others, such as
usage counters for measuring hits, can be reused with little or no tailoring.
In this section, you’ll learn how JavaScript can be used to simplify the placement
and management of ads in your Web pages. You’ll learn how to display fixed ads,
for specific time intervals and how to randomly sequence your ads in a continuous
display. You’ll also learn how to tailor your ad display based on user preferences.
FIGURE 1:
This widget displays the ad
of the day (Listing 1).
The fixed ad display is easy to implement. You create an array of URLs corre-
sponding to each day of the week. You also create the ad images associated with
each URL and give them indexed names—for example, i0.gif, i1.gif, i2.gif, etc.
When your Web page is being loaded, you use the Date object to determine
what ad to display for the current month, date, day, hour, and so on. The ad is
displayed as an image link using the appropriate image and URL.
FIGURE 2:
This widget displays a ran-
dom ad (Listing 2).
FIGURE 3:
A different ad is displayed
with each page reload
(Listing 2).
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertAd()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Displaying Random Ads</H1>
<P ALIGN=”CENTER”>[Click reload to see another ad]</P>
</BODY>
</HTML>
The file randad.htm is very similar to fixedad.htm. It differs only in the way it
selects the ad to be displayed. Instead of selecting an ad based on the Date object,
it generates a random number, which is used to select an ad.
FIGURE 4:
Select ad preferences to
determine what types
of ads will be displayed
(Listing 3).
FIGURE 5:
Now ads are displayed
based on user preferences
(Listing 3).
“hardware.htm”,
“webmstr.htm”,
“travel.htm”,
“travel2.htm”,
“sports.htm”,
“tv.htm”)
prefIX=new Array(0,0,3,6,9,11)
function insertAd() {
readCookie()
setUserPreferences()
displayAd()
}
function displayAd() {
if(userPref==0){
adIX = Math.round(Math.random()*(urls.length-1))
}else{
var startIX=prefIX[userPref]
var numPrefs=urls.length-startIX
if(userPref!=prefIX.length-1)
numPrefs=prefIX[userPref+1] - startIX
adIX = Math.round(Math.random()*(numPrefs-1))
adIX += startIX
}
document.write(‘<P ALIGN=”CENTER”>’)
document.write(‘<A HREF=”’+urls[adIX]+’”>’)
document.write(‘<IMG SRC=”ir’+adIX+’.gif” BORDER=”0”>’)
document.writeln(‘</A></P>’)
document.write(‘<FORM NAME=”setPref”>’)
document.write(‘<P><B> Current ad preference: ‘)
document.write(preferences[userPref]+’ ‘)
document.write(‘</B></P>’)
displaySelectionList()
document.write(‘ <INPUT TYPE=”BUTTON” NAME=”update”’ )
document.write(‘VALUE=”Update” onClick=”updatePrefs()”>’)
document.writeln(‘</FORM>’)
}
function displaySelectionList() {
document.write(‘<SELECT NAME=”prefsList”>’)
for(var i=0;i<preferences.length;++i) {
if(i==userPref)
document.write(‘<OPTION DEFAULT>’+preferences[i])
else document.write(‘<OPTION>’+preferences[i])
}
document.write(‘</SELECT>’)
}
function updatePrefs() {
var list = window.document.setPref.prefsList
var selectedOption=list.options[list.selectedIndex].text
var newCookie=”adPref=”+selectedOption
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
window.document.cookie=newCookie
window.location=”prefad.htm”
}
function setUserPreferences() {
userPref=0
for(var i=0;i<preferences.length;++i) {
if(adPref==preferences[i]){
userPref=i
break
}
}
}
function readCookie() {
var cookie=document.cookie
adPref=”random”
if(nameDefined(cookie,”adPref”))
adPref=getCookieValue(cookie,”adPref”)
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertAd()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Displaying Ads Based on User Preferences</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>
these functions are used to parse cookies. The rest of the script’s arrays and func-
tions are described in the following sections.
NOTE You may wonder why displayAd() generated the entire preferences selection form.
Why not just put it in the HTML code? The reason for generating the HTML from
JavaScript was to combine the ad and the preference selection form into a single wid-
get, which could be inserted into a document using the simple insertAd() function
invocation.
FIGURE 6:
Opening a page for the first
time results in this display
(Listing 4).
FIGURE 7:
Opening a page for the
second time shows the
counter in operation
(Listing 4).
return false
}
function removeBlanks(s) {
var temp=””
for(var i=0;i<s.length;++i) {
var c=s.charAt(i)
if(c!=” “) temp += c
}
return temp
}
function getCookieValue(c,n) {
var s=removeBlanks(c)
var pairs=s.split(“;”)
for(var i=0;i<pairs.length;++i) {
var pairSplit=pairs[i].split(“=”)
if(pairSplit[0]==n) return pairSplit[1]
}
return “”
}
function insertCounter() {
readCookie()
displayCounter()
}
function displayCounter() {
document.write(‘<H3 ALIGN=”CENTER”>’)
document.write(“Welcome! You’ve accessed this page “)
if(counter==1) document.write(“for the first time.”)
else document.write(counter+” times!”)
document.writeln(‘</H3>’)
}
function readCookie() {
var cookie=document.cookie
counter=0
if(nameDefined(cookie,”pageCount”))
counter=parseInt(getCookieValue(cookie,”pageCount”))
++counter
var newCookie=”pageCount=”+counter
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
window.document.cookie=newCookie
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertCounter()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Keeping track of Web page access</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>
1. Open sitecnt.htm (Listing 5) with your browser. It will display the Web
page shown in Figure 8.
2. Close your browser and copy sitecnt.htm to another directory. This will
demonstrate the effect of having two Web pages at your site.
3. Open the copied file. It will be displayed as shown in Figure 9. Note that the
counter was updated even though the second file you opened was in
another directory (representing a separate Web page at the same site).
NOTE In order for this counter to keep an accurate count of accesses to your Web site,
you must copy the file sitecnt.htm to all the Web pages at your site.
FIGURE 8:
Opening sitecnt.htm
(Listing 5) for the first time
shows that you’re visiting
this site for the first time.
FIGURE 9:
The counter (Listing 5)
tallies your additional
accesses to the site, even
though your accesses may
be to different pages at
the site.
To show how easy it is to include a counter in your Web pages, I’ve separated the
code that implements the counter from the code that displays it. The sitecnt.htm
file shown in Listing 5 includes the counter.js file shown in Listing 6. In Listing 5,
only a single JavaScript line is needed to insert the site counter into the Web page.
NOTE Don’t rely on this technique being secure—mischievous users could manipulate
their cookie files to change the time value recorded.
Open timecnt.htm with your browser. Your display should look like Figure 10.
Wait a few seconds, and then click your browser’s reload button. It should dis-
play the Web page shown in Figure 11. Notice how it tracked the time in which
the page was loaded.
FIGURE 10:
The time-counter display
shows that you’re access-
ing this site for the first
time (Listing 7).
FIGURE 11:
The time counter can also
be used to track the
amount of time the user
has spent at your site
(Listing 7).
}
function getCookieValue(c,n) {
var s=removeBlanks(c)
var pairs=s.split(“;”)
for(var i=0;i<pairs.length;++i) {
var pairSplit=pairs[i].split(“=”)
if(pairSplit[0]==n) return pairSplit[1]
}
return “”
}
function insertTimeCounter() {
today = new Date()
startTime = today.getTime()
readCookie()
displayCounter()
setInterval(“setCookie()”,1000)
}
function displayCounter() {
document.write(‘<H3 ALIGN=”CENTER”>’)
document.write(“Welcome! You’ve accessed this site “)
if(prevTime==0) document.write(“for the first time.”)
else document.write(“over “+displayTime())
document.writeln(‘</H3>’)
}
function displayTime() {
var seconds=Math.round(prevTime/1000)
var minutes=Math.round(seconds/60)
var hours=Math.round(minutes/60)
if(seconds<60) return “”+seconds+ “ seconds.”
else if(minutes<60) return “”+minutes+ “ minutes.”
else return “”+hours+” hours “
}
function readCookie() {
var cookie=document.cookie
prevTime=0
if(nameDefined(cookie,”timeCount”))
prevTime=parseInt(getCookieValue(cookie,”timeCount”))
}
function setCookie() {
now = new Date()
endTime = now.getTime()
duration = endTime-startTime
var newCookie=”timeCount=”+(prevTime+duration)
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
newCookie += “; path=/”
window.document.cookie=newCookie
}
FIGURE 12:
Nagging the user is easy
using counters and alert
dialog boxes (Listing 9).
Scrolling Messages 27
Scrolling Messages
Another popular way of attracting a user’s attention is through the use of scrolling
messages. These types of messages are very eye-catching and can be used to divert
even the most focused Web surfer.
Scrolling Text
One of the easiest ways to implement scrolling messages is via scrolling text. There
are a number of ways of accomplishing this. For example, you can scroll text in a
form’s text field, you can scroll it in the browser’s status message area (the status
bar), or you can get real fancy and scroll different images that contain separate
parts (or even the separate characters) of your message. In this section, we’ll take a
look at scrolling a single text message across the browser’s status bar. We’ll look at
scrolling different messages or images in the section “Adding Simple Animation,”
later in this discussion.
NOTE Use setScrollText() to tailor the scrolled message for your applications.
Listing 10 generates a catchy scrolling text message using the browser’s status
message area. Figure 13 shows the Web page that it displays. To run this script
with your browser, open textscrl.htm.
}
function scrollText() {
var text=space(maxScroll-scrollCount)+scrolledText
++scrollCount
scrollCount %= (maxScroll+1)
window.defaultStatus=text
window.setTimeout(“scrollText()”,500)
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
setScrollText(“This is scrolling text!!!”)
scrollText()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Scrolling text in the status window</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>
FIGURE 13:
Scrolling text in the status
message area is a good
way to get the user’s atten-
tion (Listing 10).
Scrolling Messages 29
The script in the document’s body sets the text to be scrolled using the set-
ScrollText() function. It then invokes scrollText() to begin the scrolling
process. scrollText() prepends up to 127 spaces to the text to be scrolled and
gradually reduces the number of prepended spaces to create a right-to-left scrolling
effect. A timeout is set to run scrollText() every half second.
Scrolling Images
Scrolling images are even more effective than scrolling text in getting a user’s
attention. Imagine a picture of a hand appearing on one side of a Web page and
moving across the top of the Web page to point to a link. Wouldn’t that get your
attention? And wouldn’t you be tempted to click on the link?
Open imgscrl.htm (see Listing 11) with your browser. Watch the hand scroll
across the top of the browser screen as shown in Figure 14. Doesn’t it catch
your eye?
loadImages()
// —></SCRIPT>
<P ALIGN=”CENTER”>
<IMG SRC=”blnkhand.gif” BORDER=”0”>
<IMG SRC=”blnkhand.gif” BORDER=”0”>
<IMG SRC=”blnkhand.gif” BORDER=”0”>
<IMG SRC=”blnkhand.gif” BORDER=”0”>
<IMG SRC=”blnkhand.gif” BORDER=”0”>
<A HREF=”javascript: void(0)”>Click here!</A>
</P>
<H1 ALIGN=”CENTER”>Scrolling an image across the screen</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>
FIGURE 14:
Scrolling a hand across the
top of a Web page calls
attention to an important
part of your Web page
(Listing 11).
Scrolling Messages 31
The scrolling hand is very easy to implement. You create a GIF file with an
image of the hand and a blank GIF file that is the same size as the hand. You then
display five blank images in a row across the top of a page. These blank images
are then successively replaced by the hand to create a scrolling effect.
The loadImages() function is used to load the two images into the hand and
blank variables. The scrollImages() function performs the scrolling by chang-
ing the position where the hand is displayed. It is invoked every 500 milliseconds
as the result of the page’s onload event. It sets the current image to a blank image
and sets the next image to the hand image.
blank.src = “blnkface.gif”
max = 5
current = 0
timeout=500
}
function animateImage(n) {
window.document.images[n].src = faces[state].src
state = (state + 1) % faces.length
if(state!=0) setTimeout(“animateImage(“+n+”)”,timeout)
}
function scrollImages() {
state = 0
animateImage(current)
current = (current+1) % max
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”
onLoad=”setInterval(‘scrollImages()’,4000)”>
<SCRIPT LANGUAGE=”JavaScript”><!—
loadImages()
// —></SCRIPT>
<P ALIGN=”CENTER”>
<IMG SRC=”blnkface.gif” BORDER=”0”>
<IMG SRC=”blnkface.gif” BORDER=”0”>
<IMG SRC=”blnkface.gif” BORDER=”0”>
<IMG SRC=”blnkface.gif” BORDER=”0”>
<IMG SRC=”blnkface.gif” BORDER=”0”>
<A HREF=”javascript: void(0)”>Click here!</A>
</P>
<H1 ALIGN=”CENTER”>Scroll and animate an image</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>
Listing 12 is very similar to Listing 11. The major difference between the two is
that Listing 12 displays a seven-image array of faces rather than a single hand.
This causes the simple animation effect of the changing face. The animateImage()
function animates an individual image position by displaying the seven images
within 500 milliseconds of each other. The scrollImages() function starts a new
image position every four seconds.
FIGURE 15:
The scrolling face illustrates
simultaneous animation
and scrolling (Listing 12).
By giving users control over these options, you can get them more involved with
your Web pages and heighten their awareness and interest in what you publish.
Listing 13 shows how simple page format controls can be added to a Web page
to permit the user to change the text and background colors. Figure 16 shows the
browser display that it produces. Experiment with the document’s background
and text colors by changing them to different color combinations. Doesn’t this
simple widget make you feel like you have greater control over what’s displayed
and that you are interacting with and improving upon it?
background=”white”
text=”black”
if(nameDefined(cookie,”background”))
background=getCookieValue(cookie,”background”)
if(nameDefined(cookie,”text”))
text=getCookieValue(cookie,”text”)
}
function setCookie() {
var newCookie=”background=”+background
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
window.document.cookie=newCookie
var newCookie=”text=”+text
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
window.document.cookie=newCookie
window.location=”prefs.htm”
}
function prefsForm() {
document.writeln(‘<FORM name=”prefs”>’)
document.writeln(‘Background color: ‘)
document.writeln(‘<SELECT name=”bg” size=”1”>’)
document.writeln(‘<OPTION>black’)
document.writeln(‘<OPTION SELECTED>white’)
document.writeln(‘<OPTION>red’)
document.writeln(‘<OPTION>orange’)
document.writeln(‘<OPTION>yellow’)
document.writeln(‘<OPTION>green’)
document.writeln(‘<OPTION>blue’)
document.writeln(‘<OPTION>brown’)
document.writeln(‘</SELECT>’)
document.writeln(‘ Text color: ‘)
document.writeln(‘<SELECT name=”fg” size=”1”>’)
document.writeln(‘<OPTION SELECTED>black’)
document.writeln(‘<OPTION>white’)
document.writeln(‘<OPTION>red’)
document.writeln(‘<OPTION>orange’)
document.writeln(‘<OPTION>yellow’)
document.writeln(‘<OPTION>green’)
document.writeln(‘<OPTION>blue’)
document.writeln(‘<OPTION>brown’)
document.writeln(‘</SELECT>’)
document.writeln(‘<INPUT type=”button” value=”Set Colors”
onClick=”setPrefs()”’)
document.writeln(‘</FORM>’)
}
function setPrefs() {
bgField = window.document.prefs.bg
bgIndex = bgField.selectedIndex
background = bgField.options[bgIndex].text
fgField = window.document.prefs.fg
fgIndex = fgField.selectedIndex
text = fgField.options[fgIndex].text
setCookie()
}
// —></SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript”><!—
readCookie()
document.bgColor=background
document.fgColor=text
prefsForm()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Setting color preferences</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>
To insert the color preferences form into a Web page, you invoke the prefsForm()
function. You do so after executing the following three lines of code:
readCookie()
document.bgColor=background
document.fgColor=text
The above statements read the current cookie value (if any) and update the docu-
ment’s background and foreground colors.
FIGURE 16:
JavaScript makes it easy to
change document colors
(Listing 13).
NOTE The SRC attribute of the script tag may be used to include the JavaScript code
shown in the document head.
The new functions defined in the document’s head are used as described in the
following sections.
Summary
In this chapter, you learned how to create a variety of interesting widgets for use
in your Web pages. You learned how to develop and display ads and usage coun-
ters. You also learned how to create scrolling text and images and animated icons.
Finally, you learned how to include format controls in your Web pages. In the
next chapter you’ll learn how to integrate common desktop accessories into your
pages.