Tải bản đầy đủ - 0 (trang)
Chapter 6. Implementing JavaScript Source Files

Chapter 6. Implementing JavaScript Source Files

Tải bản đầy đủ - 0trang

cookies.js

This awesome library, mostly from JavaScript veteran Bill Dortch, makes leveraging cookie

power a snap.

dhtml.js

You've seen all of these functions in Chapter 3, and Chapter 4. This is a nice package to

create, show, and hide cross-browser DHTML layers.

events.js

This source file contains code that will enable and disable capturing mousemove and keypress

events in both NN and MSIE.

frames.js

These functions help keep your web pages in or out (whichever you prefer) of other

framesets.

images.js

Rollover code, which you've probably seen in earlier chapters, makes for a neat package here.

navbar.js

Contains code that generates a dynamic navigation bar based on the current document loaded.

Impressive.

numbers.js

Contains code to correct JavaScript rounding errors and provide number formatting.

objects.js

Contains code for generic object creation and object inspection.

strings.js

This file contains a few string manipulation functions.

Except for navbar.js, each .js file has a correspondingly named HTML document (for example,

arrays.html goes with arrays.js). The functions aren't explained in as much detail here as they are in

the applications. In most cases that's because it's just not necessary, although exceptions are noted. As

you make your way through the chapter, think about how each function can solve a common problem

you have. If it won't work for you as it is, consider how you can change it to make it do so.

Each section that describes a .js file starts with the file name, its practical uses, the version of

JavaScript required, and a list of the functions contained in the file.



6.1 arrays.js

Practical use

Array manipulation

Version requirement

JavaScript 1.2

Functions



avg(), high(), low(), jsGrep(), truncate(), shrink(),

integrate(), reorganize()

These functions take your arrays, manipulate them, and return other useful information, including

other arrays. Figure 6.1 shows arrays.html. Nothing exciting to look at, but you can see that each

function is demonstrated.

Figure 6.1. Showing off the power of arrays.js



Here is the laundry list of functions of arrays.js and their uses:

avg()

Returns the average value of all the numbers in the array

high()

Returns the highest number value of the array

low()

Returns the lowest value of the array



jsGrep()

Performs string matching and replacement on all array elements

truncate()

Returns a copy of the array without the last element

shrink()

Returns a copy of the array without the first element

integrate()

Combines the elements of two arrays starting with an index you define

reorganize()

Reorders the array elements according to a multiple you choose

Now look at the code for arrays.html, shown in Example 6.1. Not much here. Just a call to



document.write(). The string displayed contains the results of all the function calls with

sample arrays—someArray() and grepExample().

Example 6.1. arrays.html



1

2

3 arrays.js Example

4

5

6

7

29

30

You might have noticed that both SCRIPT tags require JavaScript 1.2. The only reason for this is the

function jsGrep(), which utilizes JavaScript 1.2 string-matching and replacement features. More

on jsGrep() in a moment. You can include JavaScript 1.1 browsers by removing (or rewriting)

jsGrep(). Now that you see how the functions are called, look at the functions themselves; in

Example 6.2, arrays.js.

Example 6.2. arrays.js



1 var sum = 0;

2

for (var i = 0; i < arrObj.length; i++) {

3

sum += arrObj[i];

4

}

5

return (sum / i);

6

}

7

8 function high(arrObj) {

9

var highest = arrObj[0];

10

for (var i = 1; i < arrObj.length; i++) {

11

highest = (arrObj[i] > highest ? arrObj[i] :

highest);

12

}

13

return (highest);

14

}

15

16 function low(arrObj) {

17

var lowest = arrObj[0];

18

for (var i = 1; i < arrObj.length; i++) {

19

lowest = (arrObj[i] < lowest ? arrObj[i] :

lowest);

20

}

21

return (lowest);

22

}



23

24 function jsGrep(arrObj, regexp, subStr) {

25

for (var i = 0; i < arrObj.length; i++) {

26

arrObj[i] = arrObj[i].replace(regexp, subStr);

27

}

28

return arrObj;

29

}

30

31 function truncate(arrObj) {

32

arrObj.length = arrObj.length - 1;

33

return arrObj;

34

}

35

36

37 function shrink(arrObj) {

38

var tempArray = new Array();

39

for(var p = 1; p < arrObj.length; p++) {

40

tempArray[p - 1] = arrObj[p];

41

}

42

return tempArray;

43

}

44

45

46 function integrate(arrObj, elemArray, startIndex) {

47

startIndex = (parseInt(Math.abs(startIndex)) <

arrObj.length ?

48

parseInt(Math.abs(startIndex)) : arrObj.length);

49

var tempArray = new Array();

50

for( var p = 0; p < startIndex; p++) {

51

tempArray[p] = arrObj[p];

52

}

53

for( var q = startIndex; q < startIndex +

elemArray.length; q++) {

54

tempArray[q] = elemArray[q - startIndex];

55

}

56

for( var r = startIndex + elemArray.length; r <

(arrObj.length +

57

elemArray.length); r++) {

58

tempArray[r] = arrObj[r - elemArray.length];

59

}

60

return tempArray;

61

}

62

63 function reorganize(formObj, stepUp) {

64

stepUp = (Math.abs(parseInt(stepUp)) > 0 ?

65

Math.abs(parseInt(stepUp)) : 1);

66

var nextRound = 1;

67

var idx = 0;

68

var tempArray = new Array();



69

70

71

72

73

74

75

76

77

78

79

80



for (var i = 0; i < formObj.length; i++) {

tempArray[i] = formObj[idx];

if (idx + stepUp >= formObj.length) {

idx = nextRound;

nextRound++;

}

else {

idx += stepUp;

}

}

return tempArray;

}



Functions avg(), high(), and low() don't seem all that shocking. avg() adds up all the

values, then divides that sum by arrObj.length and returns that quotient. The other two

functions iterate through the passed array, comparing the elements with one another to determine the

highest or lowest valued element.

Function jsGrep() iterates through the elements of an array and executes string matching or

replacement. Anyone familiar with Perl has probably used the subroutine grep() plenty of times.

Perl's grep() is much more powerful, but works much the same way.

Functions truncate() and shrink() are simple JavaScript 1.1 equivalents of JavaScript 1.2

array function pop() and shift(). Actually, pop() and shift() are also named after the

similarly named and performing subroutines in Perl.

Function integrate() is also a JavaScript 1.1 equivalent for the JavaScript 1.2 array method

slice().



slice() is also named after the Perl subroutine. This function is fairly simple. Although there are

three for loops, the total number of iterations is always arrObj.length +

elemArray.length.

Function reorganize() reorders array elements by a multiple you select. In other words, if you

"reorganize" a 10-element array (that starts out as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) by 3, the new order comes

out as 0, 3, 6, 9, 1, 4, 7, 2, 5, 8.



6.2 cookies.js

Practical uses

Individual hit counters, form repopulation, user preferences settings

Version requirement

JavaScript 1.1

Functions



getCookieVal(), GetCookie(), DeleteCookie(), SetCookie()

You want client-state management? How about cool web site greetings for repeat visitors? Need to set

up a language switching interface or other user preferences? This code makes setting and getting

cookie information really easy. Figures 6-2, 6-3, and 6-4 show cookies.html in action. Notice in Figure

6.2 that the first time the page is loaded, the user is prompted to provide a name. Figure 6.3 displays

the greeting that the first-time visitor receives. Figure 6.4 shows that repeat visitors are welcomed

back warmly with a personalized hit count.

Figure 6.2. First timers fill in their name once . . .



Figure 6.3. ... get a newcomer's welcome . . .



Figure 6.4. ... then become one of the gang



This is definitely a simple example of cookie power. Chapter 7, applies this same code to "remember"

user preferences. By the way, if you haven't fully digested the concept of a cookie, check out the



Unofficial Cookie FAQ at http://www.cookiecentral.com/unofficial_cookie_faq.htm. As unofficial as

it is, you'll get the low-down on all your cookie questions. Also, we'll go into more detail in Chapter 7.

File cookies.html works like this: when the user loads the page, it checks for a cookie of the name

user_id. If the name does not exist (equals null), it prompts the user for his or her name. Then it sets

the cookie user_id to the value of the user's name, and cookie hit_count to 2 (the number of times the

user will have visited on next return).

If user_id does exist, it grabs its value and the value of hit_count. If the user_id cookie exists, the user

has been to the site before. It's safe to say, then, the cookie hit_count has also been set. It displays the

name and the number of times the user has come to the site, then resets the value of hit_count to a

string equivalent of hit_count+1. Take a look at cookies.js,in Example 6.3, to see what all this

setting and getting is about.

Example 6.3. cookies.js



1 var today = new Date();

2 var expiry = new Date(today.getTime() + 365 * 24 * 60

* 60 * 1000);

3

4 function getCookieVal (offset) {

5

var endstr = document.cookie.indexOf (";", offset);

6

if (endstr == -1) { endstr = document.cookie.length;

}

7

return unescape(document.cookie.substring(offset,

endstr));

8

}

9

10 function GetCookie (name) {

11

var arg = name + "=";

12

var alen = arg.length;

13

var clen = document.cookie.length;

14

var i = 0;

15

while (i < clen) {

16

var j = i + alen;

17

if (document.cookie.substring(i, j) == arg) {

18

return getCookieVal (j);

19

}

20

i = document.cookie.indexOf(" ", i) + 1;

21

if (i == 0) break;

22

}

23

return null;

24

}

25

26 function DeleteCookie (name,path,domain) {

27

if (GetCookie(name)) {

28

document.cookie = name + "=" +

29

((path) ? "; path=" + path : "") +

30

((domain) ? "; domain=" + domain : "") +

31

"; expires=Thu, 01-Jan-70 00:00:01 GMT";



32

}

33

}

34

35 function SetCookie

(name,value,expires,path,domain,secure) {

36

document.cookie = name + "=" + escape (value) +

37

((expires) ? "; expires=" + expires.toGMTString()

: "") +

38

((path) ? "; path=" + path : "") +

39

((domain) ? "; domain=" + domain : "") +

40

((secure) ? "; secure" : "");

41

}

There are four functions here, but you'll only need to call three: SetCookie(), GetCookie(),

and DeleteCookie(). getCookieVal() is an internal function. You never need to call it

directly.

Creating cookies with SetCookie() is easy. You need only pass in a cookie name (to access it

later with GetCookie()), the information you want to store (such as a username or hit count), and

an expiration date, in that order. You must provide the first two parameters. The expiration date,

however, is provided by way of variables today and expiry. Variable expiry is set to a date one year

from the day the user loads the page. This happens by instantiating variable today to a new Date

object and using the getTime() method. Here's how it works.

Variable today is a Date object. So today.getTime() returns the current time in terms of

milliseconds (since 1970 at 00:00:00, Greenwich Mean Time). That brings us to the present time in

milliseconds, but we want an expiration date of one year from now. There are 365 days in a year, 24

hours in a day, 60 minutes in an hour, 60 seconds in a minute and 1,000 milliseconds in a second. Just

multiply them together and add the product (which is 3.1536e10 milliseconds) to the return of

getTime().

The syntax for GetCookie() and DeleteCookie() are even easier. All you do is pass in the

name associated with the cookie. GetCookie() will return the value of the cookie (or null if it

isn't found), and DeleteCookie() deletes the cookie associated with the name passed in.

Deleting simply means setting the cookie with an expiration date in the past.



6.3 dhtml.js

Practical use

DHTML layer creation, hiding, and revealing

Version requirement

JavaScript 1.2

Functions



genLayer(), hideSlide(), showSlide(), refSlide()



If you've been reading the book in order, you've seen this code in two previous applications (the

slideshow and the multiple search engine interface). Figures 6-5 and 6-6 show the code that has

created a layer and allows you to hide and show it at will.

Figure 6.5. "Eye-catching" DHTML: Now you see it



Figure 6.6. Now you don't



Example 6.4 shows the contents of dhtml.js. I haven't changed a thing. Check Chapter 3 and Chapter 5

for the code details.

Example 6.4. dhtml.js



1 var NN

= (document.layers ? true : false);

2 var hideName = (NN ? 'hide' : 'hidden');

3 var showName = (NN ? 'show' : 'visible');

4 var zIdx

= -1;

5 function genLayer(sName, sLeft, sTop, sWdh, sHgt,

sVis, copy) {

6

if (NN) {

7

document.writeln('
LEFT=' + sLeft +

8

' TOP=' + sTop +

9

' WIDTH=' + sWdh + ' HEIGHT=' + sHgt + '

VISIBILITY="' + sVis +

10

'" z-Index=' + zIdx + '>' + copy + '
');

11

}

12

else {

13

document.writeln('
' + copy +

17

'
');

18

}

19

}

20

21 function hideSlide(name) {

22

refSlide(name).visibility = hideName;

23

}

24

25 function showSlide(name) {

26

refSlide(name).visibility = showName;

27

}

28

29 function refSlide(name) {

30

if (NN) { return document.layers[name]; }

31

else { return eval('document.all.' + name +

'.style'); }

32

}



6.4 events.js

Practical uses

Cross-browser event handler assignment, mouse movement tracking

Version requirement

JavaScript 1.2

Functions



enableEffects(), showXY(), keepKeys(), showKeys()

If you haven't experimented with cross-browser event handling scripts, this might be just the primer

for you. This example utilizes three event handlers: onclick, onmousemove, and onkeypress. When you

first click anywhere in the document space, the JavaScript captures the initial x and y coordinates of

the mouse-pointer arrow with respect to the browser window. After that, the status bar displays the x

and y coordinates as the user moves the pointer arrow around. Clicking once again "turns off" the

coordinate tracking and calculates the pixel distance between the point the user first clicked and

current location. You can see this in Figure 6.7 and Figure 6.8.

Figure 6.7. x and y mouse coordinates in the status bar



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6. Implementing JavaScript Source Files

Tải bản đầy đủ ngay(0 tr)

×