Вы находитесь на странице: 1из 39

SYBEX Supplement

Mastering™ JavaScript® and JScript™


by James Jaworski

Bonus Chapter One: Creating Web Page Widgets

SYBEX is a registered trademark of SYBEX Inc.


Mastering is a trademark of SYBEX Inc.

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?

■ Including Advertisements in Your Web Pages

■ Usage Counters for Tabulating “Hits”

■ Scrolling Messages

■ Page Format Preferences

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 2

2 Bonus Chapter 1 • Creating Web Page Widgets

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.

Including Advertisements in Your Web


Pages
The Web has become a mecca for advertisement. It is hard to find a popular Web
page that does not have some sort of colorful ad strategically positioned across
the top or along the side of the page. And why not? It’s a great way to generate
interest in your products or services and thus possibly some extra income to pay
for Internet access. I can think of harder ways to make money!

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 3

Including Advertisements in Your Web Pages 3

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.

Working with Fixed Ads


Fixed ads are ads that stay in place for a given period of time—a day, a week, a
month, and so on. After the ad’s time interval expires, a new ad is displayed.
JavaScript can be used to simplify the management of fixed ads by automatically
displaying the next ad at the proper time.
Listing 1 provides an example of a script that displays a different ad for each
day of the week. To see how it works, open the file fixedad.htm with your
browser. Your browser will display a Web page similar to the one shown in Fig-
ure 1, except that the ad displayed by your browser will vary according to which
day of the week it is.

FIGURE 1:
This widget displays the ad
of the day (Listing 1).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 4

4 Bonus Chapter 1 • Creating Web Page Widgets

Listing 1 Displaying a New Ad Every Day (fixedad.htm)


<HTML>
<HEAD>
<TITLE>Displaying the Ad of the Day</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
urls = new Array(“widgets.htm”,
“webmstr.htm”,
“coffee.htm”,
“sports.htm”,
“news.htm”,
“stocks.htm”,
“travel.htm”)
function insertAd() {
var today = new Date()
adIX = today.getDay()
document.write(‘<P ALIGN=”CENTER”><A HREF=”’+urls[adIX]+’”>’)
document.write(‘<IMG SRC=”i’+adIX+’.gif” BORDER=”0”>’)
document.writeln(‘</A></P>’)
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertAd()
// —></SCRIPT>
</P><H1 ALIGN=”CENTER”>Displaying the Ad of the Day</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>

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.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 5

Including Advertisements in Your Web Pages 5

Placing Random Ads


Random ads are ads that are randomly selected and displayed, usually each time a
Web page is loaded. Random ads change often and are usually used by Web sites
with lots of advertisers. JavaScript can be used to simplify the processing of these
ads by randomly selecting and displaying a new ad each time a Web page is
loaded.
Listing 2 shows how random ads can be implemented using JavaScript. Open
randad.htm with your browser. It will display a Web page similar to the one
shown in Figure 2 except that the ad displayed by your browser will probably
differ, since the ad is randomly selected from a set of seven.
Click on your browser’s Reload button and another randomly selected ad is
displayed, as shown in Figure 3.

FIGURE 2:
This widget displays a ran-
dom ad (Listing 2).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 6

6 Bonus Chapter 1 • Creating Web Page Widgets

FIGURE 3:
A different ad is displayed
with each page reload
(Listing 2).

Listing 2 A Random Ad Display Page (randad.htm)


<HTML>
<HEAD>
<TITLE>Displaying Random Ads</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
urls = new Array(“widgets.htm”,
“webmstr.htm”,
“coffee.htm”,
“sports.htm”,
“news.htm”,
“stocks.htm”,
“travel.htm”)
function insertAd() {
adIX = Math.round(Math.random()*(urls.length-1))
document.write(‘<P ALIGN=”CENTER”><A HREF=”’+urls[adIX]+’”>’)
document.write(‘<IMG SRC=”i’+adIX+’.gif” BORDER=”0”>’)
document.writeln(‘</A></P>’)

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 7

Including Advertisements in Your Web Pages 7

}
// —></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.

Enabling User-Selected Ads


For an ad to be successful, a user must respond to it. Ideally, they will respond by
buying the product or service you’re advertising, but the first step to getting them
to do that is usually getting them to click on the ad. There are a number of strate-
gies that can be used to get users to click on an ad. For example, you can use off-
beat messages, colorful image links, or animated icons in the hope of catching the
user’s attention. You can also display only ads that the user is likely to be inter-
ested in. For example, a Web page that is devoted to sports is a better place to
advertise sports equipment than handmade blankets.
In fact, it’s a good idea to let the user decide what kind of ads he or she is inter-
ested in seeing. The Web page generated by Listing 3 does just that. It allows the
user to set his or her ad preferences, and it permanently stores the user’s prefer-
ence via a cookie.
To see how it works, open prefad.htm with your browser. It will display a
Web page similar to that shown in Figure 4. Note that a small form is provided
for you to select what type of ads you are interested in seeing. Select Travel from
the selection list, and click on the Update button. All the ads that you see in the
future will now be travel-related ads, as shown in Figure 5.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 8

8 Bonus Chapter 1 • Creating Web Page Widgets

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).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 9

Including Advertisements in Your Web Pages 9

Listing 3 Code to Display an Ad Based on User Preferences (prefad.htm)


<HTML>
<HEAD>
<TITLE>Displaying Ads Based on User Preferences</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
function nameDefined(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 true
}
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 “”
}
preferences = new Array(“Random”,”Home”,”Business”,”Computers”,
“Travel”,”Entertainment”)
urls = new Array(“decorate.htm”,
“coffee.htm”,
“repair.htm”,
“news.htm”,
“stocks.htm”,
“widgets.htm”,
“software.htm”,

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 10

10 Bonus Chapter 1 • Creating Web Page Widgets

“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])

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 11

Including Advertisements in Your Web Pages 11

}
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>

Even though prefad.htm is noticeably longer than fixedad.htm and randad


.htm, it is only slightly more complex. It consists of some familiar code. You’re
already familiar with nameDefined(), removeBlanks(), and getCookieValue();

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 12

12 Bonus Chapter 1 • Creating Web Page Widgets

these functions are used to parse cookies. The rest of the script’s arrays and func-
tions are described in the following sections.

The preferences Array


This array identifies the ad categories that a user is allowed to select.

The urls Array


This array lists the URLs to be used in the ads.

The prefIX Array


This array identifies the index into the urls array of the first ad in each ad cate-
gory specified by the preferences array.

The insertAd() Function


This function is used to insert an ad and the preferences form into a document. It
invokes readCookie() to load any preferences that were previously selected by
the user, setPreferences() to set those preferences, and displayAd() to dis-
play the ad.

The displayAd() Function


This function displays an ad based on user preferences. It sets adIX to the index
of the ad (with respect to URLs) to be displayed. It calculates this index (for non-
random preferences) by selecting a random index within the portion of the urls
array occupied by URLs of the user-preferred category.
After computing adIX, displayAd() displays the ad, followed by the prefer-
ence selection form.

The displaySelectionList() Function


This function displays the selection list containing the ad categories identified in
the preferences array.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 13

Usage Counters for Tabulating Hits 13

The updatePrefs() Function


This function updates the adPref cookie with the value of the preference selected
in the prefsList selection list. It then reloads the current document with the
selected preference in effect.

The setUserPreferences() Function


This function sets the userPref variable to the index within the preferences array
of the current user preferences, as identified by the adPref cookie.

The readCookie() Function


This function reads the adPref cookie value and stores it in the adPref variable.

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.

Usage Counters for Tabulating Hits


Many Web sites display usage counters of the form, “This Web site has been vis-
ited 102,987 times.” These counters help keep track of how many times a site has
been visited and display this number to users (and would-be advertisers). In
Internet lingo, the visits are called hits.
In this section, we’ll look at how you can use JavaScript to create usage coun-
ters that are tailored to the individual user rather than the mass of humanity that
visits your Web site.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 14

14 Bonus Chapter 1 • Creating Web Page Widgets

Web Page Access Counters


Most usage counters keep track of how many times Web surfers as a whole access
a Web site. Wouldn’t it be nice to have a counter that reported to each user how
many times each individual user had accessed your site?
Let’s start with tabulating individual user accesses to a Web page before we
move on to tracking accesses to your Web site as a whole. The script shown in
Listing 4 tallies Web page accesses. Run this script by opening pagecnt.htm with
your browser. You will see the display shown in Figure 6. It tells you that you’ve
loaded the Web page for the first time. Click your browser’s Reload button and
you will see the display shown in Figure 7. It tells you that you’ve accessed the
Web page for the second time.

FIGURE 6:
Opening a page for the first
time results in this display
(Listing 4).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 15

Usage Counters for Tabulating Hits 15

FIGURE 7:
Opening a page for the
second time shows the
counter in operation
(Listing 4).

Listing 4 A Personal Web Page Access Counter (pagecnt.htm)


<HTML>
<HEAD>
<TITLE>Keeping track of Web page access</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
function nameDefined(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 true
}

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 16

16 Bonus Chapter 1 • Creating Web Page Widgets

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
}

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 17

Usage Counters for Tabulating Hits 17

// —></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>

The script in the document body invokes the insertCounter() function to


generate and insert the counter in the Web page. The script in the document head
defines three new functions—insertCounter(), readCookie(), and display-
Counter(). These functions are used as described in the following sections.

The insertCounter() Function


This function invokes readCookie() to load the current access counter and
displayCounter() to display the counter.

The readCookie() Function


This function reads the pageCount cookie, increments it by 1, and then stores it as
an updated cookie.

The displayCounter() Function


This function displays the counter message.

Web Site Access Counters


The script shown in Listing 4 can be easily extended to report how many times a
single user has accessed your Web site as a whole. This is accomplished by storing
the usage counter in a cookie that has the path set to / (simply a forward slash).
This causes the cookie to apply to all Web pages located on a particular host.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 18

18 Bonus Chapter 1 • Creating Web Page Widgets

To see how the counter works, follow these steps:

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.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 19

Usage Counters for Tabulating Hits 19

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.

Listing 5 A Web Site Access Counter (sitecnt.htm)


<HTML>
<HEAD>
<TITLE>Keeping track of Web site access</TITLE>
<SCRIPT LANGUAGE=”JavaScript” SRC=”counter.js”><!—
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertSiteCounter()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Keeping track of Web site access</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 20

20 Bonus Chapter 1 • Creating Web Page Widgets

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.

Listing 6 The Code That Implements the Counter (counter.js)


function nameDefined(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 true
}
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 insertSiteCounter() {
readCookie()
displayCounter()
}
function displayCounter() {
document.write(‘<H3 ALIGN=”CENTER”>’)
document.write(“Welcome! You’ve accessed this site “)

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:18 AM Page 21

Usage Counters for Tabulating Hits 21

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,”siteCount”))
counter=parseInt(getCookieValue(cookie,”siteCount”))
++counter
var newCookie=”siteCount=”+counter
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
newCookie += “; path=/”
window.document.cookie=newCookie
}

You probably noticed that counter.js is very similar to pagecnt.htm. The


only significant difference between the two files is that counter.js stores the
cookie with the path set to /. This enables the cookie to work with any file in any
directory on your system. However, the cookie cannot be shared between pages
from different domains. Consult Chapter 23, “Securing Your Scripts,” for more
information on JavaScript’s Same Origin security policy.

Time Usage Counters


In some cases, you may be more interested in telling users how many hours or
minutes they have spent at your Web site, rather than how many times they have
accessed it. This is especially true if your Web site provides some sort of interac-
tive content, like a game or tutorial. In this case, you may want to display a mes-
sage of the form, “You’ve accessed this Web site for over 120 hours—Get a life!”
This type of usage counter can be easily implemented with JavaScript, as shown
in Listing 7. Note that this file uses timecnt.js (Listing 8).

NOTE Don’t rely on this technique being secure—mischievous users could manipulate
their cookie files to change the time value recorded.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 22

22 Bonus Chapter 1 • Creating Web Page Widgets

Listing 7 Keeping Track of User Access Time (timecnt.htm)


<HTML>
<HEAD>
<TITLE>Keeping track of Web site access time</TITLE>
<SCRIPT LANGUAGE=”JavaScript” SRC=”timecnt.js”><!—
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertTimeCounter()
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Keeping track of Web site access time</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>

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).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 23

Usage Counters for Tabulating Hits 23

FIGURE 11:
The time counter can also
be used to track the
amount of time the user
has spent at your site
(Listing 7).

Listing 8 Implementing the Time Counter (timecnt.js)


function nameDefined(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 true
}
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

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 24

24 Bonus Chapter 1 • Creating Web Page Widgets

}
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()

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 25

Usage Counters for Tabulating Hits 25

duration = endTime-startTime
var newCookie=”timeCount=”+(prevTime+duration)
newCookie += “; expires=Wednesday, 10-Nov-10 23:12:40 GMT”
newCookie += “; path=/”
window.document.cookie=newCookie
}

The timecnt.js file uses five new functions—insertTimeCounter(), display-


Counter(), displayTime(), readCookie(), and setCookie(). These functions are
used as described in the following sections.

The insertTimeCounter() Function


This function sets the starting time in which a page is loaded, invokes read-
Cookie() to load the previous elapsed time, and then invokes displayCounter()
to display the current elapsed time.

The displayCounter() Function


This function displays the total time that a page was accessed up to the time that
it was loaded.

The displayTime() Function


This function converts elapsed time from milliseconds to seconds, minutes, and
hours.

The readCookie() Function


This function reads the timeCount cookie and stores its value in the prevTime
variable.

The setCookie() Function


This function updates the timeCount cookie by adding the time in which a Web
page is loaded to the previous value of the cookie.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 26

26 Bonus Chapter 1 • Creating Web Page Widgets

Implementing Nag Counters


As a final example of usage counters, consider a situation in which you want to
inform your users that they need to do something like register or pay their usage
bills. In this case, you may want to display a message along the lines of “You’ve
used this Web page 75 times, and you still haven’t registered!” These types of “nag”
messages can be easily added to a usage counter. Listing 9 shows how. It uses the
counter.js file that you studied in the “Web Site Access Counters” section, ear-
lier in this discussion, and displays an alert message after the user has accessed
your Web site 10 or more times. Figure 12 shows how this message is displayed.
As a practical matter, you would also want to tie the alert message to the value of
a cookie that tracked user registration.

Listing 9 Implementing a Nag Counter (nag.htm)


<HTML>
<HEAD>
<TITLE>Nagging the user to register</TITLE>
<SCRIPT LANGUAGE=”JavaScript” SRC=”counter.js”><!—
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”>
<SCRIPT LANGUAGE=”JavaScript”><!—
insertSiteCounter()
if(counter>=10) alert(“Don’t you think its time you registered?”)
// —></SCRIPT>
<H1 ALIGN=”CENTER”>Nagging the user to register</H1>
<P ALIGN=”CENTER”>[The rest of the Web page goes here.]</P>
</BODY>
</HTML>

FIGURE 12:
Nagging the user is easy
using counters and alert
dialog boxes (Listing 9).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 27

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.

Listing 10 Implementing a Scrolling Text Message (textscrl.htm)


<HTML>
<HEAD>
<TITLE>Scrolling text in the status window</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
function setScrollText(s) {
scrollCount=0
maxScroll=127
scrolledText=s
}
function space(n) {
result=””
for(var i=0;i<n;++i) result+=” “
return result

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 28

28 Bonus Chapter 1 • Creating Web Page Widgets

}
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).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 29

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?

Listing 11 Implementing a Scrolling Image (imgscrl.htm)


<HTML>
<HEAD>
<TITLE>Scrolling an image across the page</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
function loadImages() {
hand = new Image()
blank = new Image()
hand.src = “hand.gif”
blank.src = “blnkhand.gif”
max = 5
current = 4
}
function scrollImages() {
window.document.images[current].src = blank.src
current = (current + 1) % max
window.document.images[current].src = hand.src
}
// —></SCRIPT>
</HEAD>
<BODY BGCOLOR=”#FFFFFF”
onLoad=”setInterval(‘scrollImages()’,500)”>
<SCRIPT LANGUAGE=”JavaScript”><!—

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 30

30 Bonus Chapter 1 • Creating Web Page Widgets

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).

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 31

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.

Adding Simple Animation


The example scrolling image that you created in the previous section is very
catchy and is, in itself, an example of animation. However, the image remains
fixed in shape while it travels across the Web page. To make it even more eye-
catching, try using an animated image that travels across the page.
Listing 12 provides an example of this kind of animation. Open aniscrl.htm
with your browser and watch the animated face move across the top of the page
as shown in Figure 15.

Listing 12 Implementing an Animated Scrolling Image (aniscrl.htm)


<HTML>
<HEAD>
<TITLE>Scroll and animate an image</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
function loadImages() {
hand = new Image()
blank = new Image()
faces = new Array(7)
for(var i=0;i<faces.length;++i) {
faces[i]=new Image()
faces[i].src=”face”+i+”.gif”
}

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 32

32 Bonus Chapter 1 • Creating Web Page Widgets

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.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 33

Page Format Preferences 33

FIGURE 15:
The scrolling face illustrates
simultaneous animation
and scrolling (Listing 12).

Page Format Preferences


As a final type of Web page widget you’ll create a simple form that can be used to
control the way that your Web pages are displayed. There are a number of page
formatting and display options that you may wish to allow users to control:

• Whether to use frames


• Whether to display images
• What colors to use for the document background, text, and links
• Whether to display navigation buttons, a usage clock, or other widgets

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.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 34

34 Bonus Chapter 1 • Creating Web Page Widgets

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?

Listing 13 Implementing User Preferences (prefs.htm)


<HTML>
<HEAD>
<TITLE>Setting color preferences</TITLE>
<SCRIPT LANGUAGE=”JavaScript”><!—
function nameDefined(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 true
}
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 readCookie() {
var cookie=document.cookie

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 35

Page Format Preferences 35

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()”’)

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 36

36 Bonus Chapter 1 • Creating Web Page Widgets

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.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 37

Page Format Preferences 37

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.

The readCookie() Function


This function reads the cookies containing the background and text colors.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com


2492web1.qxd 3/4/99 10:19 AM Page 38

38 Bonus Chapter 1 • Creating Web Page Widgets

The setCookie() Function


This function sets the background and text color cookies to the values selected
by the user. It then reloads the Web page to bring the new values into effect.

The prefsForm() Function


This function displays the color preferences selection form.

The setPrefs() Function


This function handles the onClick event associated with the Set Colors button by
reading the color values selected by the user and invoking setCookie() to store
the cookie values.

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.

Copyright 1999 ©SYBEX, Inc., Alameda, CA www.sybex.com

Вам также может понравиться