User:Moncur/08
8. Using Built-in Functions and Libraries
[wax ka badal]Using the Math Object
[wax ka badal]The Math object is a built-in JavaScript object that includes math constants and functions. You don't need to create a Math object; it exists automatically in any JavaScript program. The Math object's properties represent mathematical constants, and its methods are mathematical functions.
Rounding and Truncating
[wax ka badal]Three of the most useful methods of the Math object enable you to round decimal values up and down:
- Math.ceil() rounds a number up to the next integer.
- Math.floor() rounds a number down to the next integer.
- Math.round() rounds a number to the nearest integer.
All of these take the number to be rounded as their single parameter. You might notice one thing missing: the capability to round to a decimal place, such as for dollar amounts. Fortunately, you can easily simulate this. Here is a simple function that rounds numbers to two decimal places:
function round(num) { return Math.round(num * 100) / 100; }
This function multiplies the value by 100 to move the decimal, and then rounds the number to the nearest integer. Finally, the value is divided by 100 to restore the decimal to its original position.
Generating Random Numbers
[wax ka badal]One of the most commonly used methods of the Math object is the Math.random() method, which generates a random number. This method doesn't require any parameters. The number it returns is a random decimal number between zero and one.
You'll usually want a random number between one and a value. You can do this with a general-purpose random number function. The following is a function that generates random numbers between one and the parameter you send it:
function rand(num) { return Math.floor(Math.random() * num) + 1; }
This function multiplies a random number by the value specified in the num parameter, and then converts it to an integer between one and the number by using the Math.floor() method.
Other Math Functions
[wax ka badal]The Math object includes many functions beyond those you've looked at here. For example, Math.sin() and Math.cos() calculate sines and cosines. The Math object also includes properties for various mathematical constants, such as Math.PI. See [Appendix D], "JavaScript Quick Reference," for a complete list of math functions and constants.
Working with Math Functions
[wax ka badal]The Math.random() method generates a random number between 0 and 1. However, it's very difficult for a computer to generate a truly random number. (It's also hard for a human being to do so—that's why dice were invented.)
Today's computers do reasonably well at generating random numbers, but just how good is JavaScript's Math.random function? One way to test it is to generate many random numbers and calculate the average of all of them.
In theory, the average should be somewhere near .5, halfway between 0 and 1. The more random values you generate, the closer the average should get to this middle ground.
As an example of the use of the Math object's methods, you can create a script that tests JavaScript's random number function. To do this, you'll generate 5,000 random numbers and calculate their average.
- Did you Know?
- Rather than typing it in, you can download and try this hour's example at this book's website.
In case you skipped [Hour 7], "Controlling Flow with Conditions and Loops," and are getting out your calculator, don't worry—you'll use a loop to generate the random numbers. You'll be surprised how fast JavaScript can do this.
To begin your script, you will initialize a variable called total. This variable will store a running total of all of the random values, so it's important that it starts at 0:
total = 0;
Next, begin a loop that will execute 5,000 times. Use a for loop because you want it to execute a fixed number of times:
for (i=1; i<=5000; i++) {
Within the loop, you will need to create a random number and add its value to total. Here are the statements that do this and continue with the next iteration of the loop:
num = Math.random(); total += num; }
Depending on the speed of your computer, it might take a few seconds to generate those 5,000 random numbers. Just to be sure something is happening, the script will display a status message after each 1,000 numbers:
if (i % 1000 == 0) document.write("Generated " + i + " numbers...<br>");
- By the Way?
- The % symbol in the previous code is the modulo operator, which gives you the remainder after dividing one number by another. Here it is used to find even multiples of 1,000.
The final part of your script will calculate the average by dividing total by 5,000. Your script can also round the average to three decimal places, using the trick you learned earlier in this hour:
average = total / 5000; average = Math.round(average * 1000) / 1000; document.write("<H2>Average of 5000 numbers: " + average + "</H2>");
To test this script and see just how random those numbers are, combine the complete script with an HTML document and <script> tags. [Listing 8.1] shows the complete random number testing script.
- Listing 8.1. A Script to Test JavaScript's Random Number Function
<html> <head> <title>Math Example</title> </head> <body> <h1>Math Example</h1> <p>How random are JavaScript's random numbers? Let's generate 5000 of them and find out.</p> <script language="JavaScript" type="text/javascript"> total = 0; for (i=1; i<=5000; i++) { num = Math.random(); total += num; if (i % 1000 == 0) document.write("Generated " + i + " numbers...<br>"); } average = total / 5000; average = Math.round(average * 1000) / 1000; document.write("<H2>Average of 5000 numbers: " + average + "</H2>"); </script> </body> </html>
To test the script, load the HTML document into a browser. After a short delay, you should see a result. If it's close to .5, the numbers are reasonably random. My result was .502, as shown in [Figure 8.1].
- By the Way?
- The average you've used here is called an arithmetic mean. This type of average isn't a perfect way to test randomness. Actually, all it tests is the distribution of the numbers above and below .5. For example, if the numbers turned out to be 2,500 .4s and 2,500 .6s, the average would be a perfect .5—but they wouldn't be very random numbers. (Thankfully, JavaScript's random numbers don't have this problem.)
Using the with Keyword
[wax ka badal]The with keyword is one you haven't seen before. You can use it to make JavaScript programming easier—or at least easier to type.
The with keyword specifies an object, and it is followed by a block of statements enclosed in braces. For each statement in the block, any properties you mention without specifying an object are assumed to be for that object.
As an example, suppose you have a string called lastname. You can use with to perform string operations on it without specifying the name of the string every time:
with (lastname) { window.alert("length of last name: " + length); capname = toUpperCase(); }
In this example, the length property and the toUpperCase method refer to the lastname string, although it is only specified once with the with keyword.
Obviously, the with keyword only saves a bit of typing in situations like this. However, you might find it more useful when you're dealing with a DOM object throughout a large procedure, or when you are using a built-in object, such as the Math object, repeatedly.
Working with Dates
[wax ka badal]The Date object is a built-in JavaScript object that enables you to conveniently work with dates and times. You can create a Date object anytime you need to store a date, and use the Date object's methods to work with the date.
You encountered one example of a Date object in [Hour 2], "Creating Simple Scripts," with the time/date script. The Date object has no properties. To set or obtain values from a Date object, you must use the methods described in the next section.
- By the Way?
- JavaScript dates are stored as the number of milliseconds since midnight, January 1, 1970. This date is called the epoch. Dates before 1970 weren't allowed in early versions, but are now represented by negative numbers.
Creating a Date Object
[wax ka badal]You can create a Date object using the new keyword. You can also optionally specify the date to store in the object when you create it. You can use any of the following formats:
birthday = new Date(); birthday = new Date("June 20, 2003 08:00:00"); birthday = new Date(6, 20, 2003); birthday = new Date(6, 20, 2003, 8, 0, 0);
You can choose any of these formats, depending on which values you wish to set. If you use no parameters, as in the first example, the current date is stored in the object. You can then set the values using the set methods, described in the next section.
Setting Date Values
[wax ka badal]A variety of set methods enable you to set components of a Date object to values:
- setDate() sets the day of the month.
- setMonth() sets the month. JavaScript numbers the months from 0 to 11, starting with January (0).
- setFullYear() sets the year.
- setTime() sets the time (and the date) by specifying the number of milliseconds since January 1, 1970.
- setHours(), setMinutes(), and setSeconds() set the time.
As an example, the following statement sets the year of a Date object called holiday to 2003:
holiday.setFullYear(2003);
Reading Date Values
[wax ka badal]You can use the get methods to get values from a Date object. This is the only way to obtain these values, because they are not available as properties. Here are the available get methods for dates:
- getdate() gets the day of the month.
- getMonth() gets the month.
- getFullYear() gets the year.
- getTime() gets the time (and the date) as the number of milliseconds since January 1, 1970.
- getHours(), getMinutes(), getSeconds(), and getMilliseconds() get the components of the time.
- By the Way?
- Along with setFullYear and getFullYear, which require four-digit years, JavaScript includes setYear and getYear methods, which use two-digit year values. You should always use the four-digit version to avoid Year 2000 issues.
Working with Time Zones
[wax ka badal]Finally, a few functions are available to help your Date objects work with local time values and time zones:
- getTimeZoneOffset() gives you the local time zone's offset from UTC (Coordinated Universal Time, based on the old Greenwich Mean Time standard). In this case, local refers to the location of the browser. (Of course, this only works if the user has set his or her system clock accurately.)
- toUTCString() converts the date object's time value to text, using UTC. This method was introduced in JavaScript 1.2 to replace the toGMTString method, which still works but should be avoided.
- toLocalString() converts the date object's time value to text, using local time.
Along with these basic functions, JavaScript 1.2 and later include UTC versions of several of the functions described previously. These are identical to the regular commands, but work with UTC instead of local time:
- getUTCDate() gets the day of the month in UTC time.
- getUTCDay() gets the day of the week in UTC time.
- getUTCFullYear() gets the four-digit year in UTC time.
- getUTCMonth() returns the month of the year in UTC time.
- getUTCHours(), getUTCMinutes(), getUTCSeconds(), and getUTCMilliseconds() return the components of the time in UTC.
- setUTCDate(), setUTCFullYear(), setUTCMonth(), setUTCHours(), setUTCMinutes(), setUTCSeconds(), and setUTCMilliseconds() set the time in UTC.
Converting Between Date Formats
[wax ka badal]Two special methods of the Date object allow you to convert between date formats. Instead of using these methods with a Date object you created, you use them with the built-in object Date itself. These include the following:
- Date.parse() converts a date string, such as June 20, 1996, to a Date object (number of milliseconds since 1/1/1970).
- Date.UTC() does the opposite. It converts a Date object value (number of milliseconds) to a UTC (GMT) time.
Using Third-Party Libraries
[wax ka badal]When you use JavaScript's built-in Math and Date functions, JavaScript does most of the work—you don't have to figure out how to convert dates between formats or calculate a cosine. Third-party libraries are not included with JavaScript, but they serve a similar purpose—enabling you to do complicated things with only a small amount of code.
Using one of these libraries is usually as simple as copying one or more files to your site and including a <script> tag in your document to load the library. Several popular JavaScript libraries are discussed in the following sections.
- Did you Know?
- JavaScript libraries are a relatively new phenomenon, and new libraries are appearing regularly. See this book's website for an updated list of libraries.
Prototype
[wax ka badal]Prototype, created by Sam Stephenson, is a JavaScript library that simplifies tasks such as working with DOM objects, dealing with data in forms, and remote scripting (AJAX). By including a single prototype.js file in your document, you have access to many improvements to basic JavaScript.
For example, you've used the document.getElementById method to obtain the DOM object for an element within a web page. Prototype includes an improved version of this in the $() function. Not only is it easier to type, but it is also more sophisticated than the built-in function and supports multiple objects.
Adding Prototype to your pages requires only one file, prototype.js, and one <script> tag:
<script type="text/javascript" src="prototype.js"> </script>
- By the Way?
Prototype is free, open-source software. You can download it from its official website at http://prototype.conio.net. Prototype is also built into the Ruby on Rails framework for the server-side language Ruby—see http://www.rubyonrails.com/ for more information.
Script.aculo.us
[wax ka badal]By the end of this book, you'll learn to do some impressive things with JavaScript—for example, animating an object within a page. The code for a task like this is complex, but you can also include effects in your pages using a prebuilt library. This enables you to use impressive effects with only a few lines of code.
Script.aculo.us by Thomas Fuchs is one such library. It includes functions to simplify drag-and-drop tasks, such as rearranging lists of items. It also includes a number of Combination Effects, which enable you to use highlighting and animated transitions within your pages. For example, a new section of the page can be briefly highlighted in yellow to get the user's attention, or a portion of the page can fade out or slide off the screen.
After you've included the appropriate files, using effects is as easy as using any of JavaScript's built-in methods. For example, the following statements use Script.aculo.us to fade out an element of the page with the id value test:
obj = document.getElementById("test"); new Effect.Fade(obj);
Script.aculo.us is built on the Prototype framework described in the previous section, and includes all of the functions of Prototype, so you could also simplify this further by using the $ function:
new Effect.Fade($("test"));
- Did you Know?
- You will create a script that demonstrates several Script.aculo.us effects in the Try It Yourself section later this hour.
AJAX Frameworks
[wax ka badal]AJAX (Asynchronous JavaScript and XML), also known as remote scripting, enables JavaScript to communicate with a program running on the web server. This enables JavaScript to do things that were traditionally not possible, such as dynamically loading information from a database or storing data on a server without refreshing a page.
Unfortunately, AJAX requires some complex scripting, particularly because the methods you use to communicate with the server vary depending on the browser in use. Fortunately, many libraries have been created to fill the need for a simple way to use AJAX.
The Prototype library, described previously, includes AJAX features. There are also many dedicated AJAX libraries. One of the most popular is SAJAX (Simple AJAX), an open-source toolkit that makes it easy to use AJAX to communicate with PHP, Perl, and other languages from JavaScript. Visit the SAJAX website for details at http://www.modernmethod.com/sajax.
- By the Way?
- See [Hour 17], "AJAX: Remote Scripting," for examples of remote scripting, with and without using third-party libraries.
Other Libraries
[wax ka badal]There are many more JavaScript libraries out there, and more are appearing all of the time as JavaScript is taken more seriously as an application language. Here are some more libraries you might want to explore:
- Dojo (http://www.dojotoolkit.org/) is an open-source toolkit that adds power to JavaScript to simplify building applications and user interfaces. It adds features ranging from extra string and math functions to animation and AJAX.
- The Yahoo! UI Library (http://developer.yahoo.net/yui/) was developed by Yahoo! and made available to everyone under an open-source license. It includes features for animation, DOM features, event management, and easy-to-use user interface elements such as calendars and sliders.
- MochiKit (http://mochikit.com/) is a lightweight library that adds features for working with the DOM, CSS colors, string formatting, and AJAX. It also supports a nice logging mechanism for debugging your scripts.
Try It Yourself
[wax ka badal]Adding Effects with a Library
[wax ka badal]To see how simple it is to use an external library, you will now create an example script that includes the Script.aculo.us library and use event handlers to demonstrate several of the available effects.
- Watch Out!
- This example was created using version 1.5.1 of the Script.aculo.us library. It should work with later versions, but the library might have changed since this was written. If you have trouble, you might need to use this specific version.
Downloading the Library
[wax ka badal]To use the library, you will need to download it and copy the files you need to the same folder where you will store your script. You can download the library from the Script.aculo.us website at http://script.aculo.us/downloads.
The download is available as a Zip file. Inside the Zip file you will find a folder called scriptaculous-js-x.x.x. You will need the following files from the folders under this folder:
- prototype.js (the Prototype library) from the lib folder
- effects.js (the effects functions) from the src folder
Copy both of these files to a folder on your computer, and be sure to create your demonstration script in the same folder.
- By the Way?
- The Script.aculo.us download includes many other files, and you can include the entire library if you intend to use all of its features. For this example, you only need the two files described here.
Including the Files
[wax ka badal]To add the library to your HTML document, simply use <script> tags to include the two JavaScript files you copied from the download:
<script type="text/javascript" src="prototype.js"> </script> <script type="text/javascript" src="effects.js"> </script>
If you include these statements as the first things in the <head> section of your document, the library functions will be available to other scripts or event handlers anywhere in the page.
Using Effects
[wax ka badal]After you have included the library, you simply need to include a bit of JavaScript to trigger the effects. We will use a section of the page wrapped in a tag with the id value test to demonstrate the effects. Each effect is triggered by a simple event handler on a button. For example, this code defines the Fade Out button:
<input type="button" value="Fade Out" onClick="new Effect.Fade($('test'))">
This uses the $ function built into Prototype to obtain the object for the element with the id value test, and then passes it to the Effect.Fade() function built into Script.aculo.us.
- Did you Know?
- This example will demonstrate six effects: Fade, Appear, SlideUp, SlideDown, Highlight, and Shake. There are more than 16 effects in the library, plus methods for supporting Drag and Drop and other features. See http://script.aculo.us for details.
Building the Script
[wax ka badal]After you have included the libraries, you can combine them with event handlers and some example text to create a complete demonstration of Script.aculo.us effects. The complete HTML document for this example is shown in [Listing 8.2].
- Listing 8.2. The Complete Library Effects Example
<html> <head> <title>Testing script.aculo.us effects</title> <script type="text/javascript" src="prototype.js"> </script> <script type="text/javascript" src="effects.js"> </script> </head> <body"> <h1>Testing script.aculo.us Effects</h1> <form name="form1"> <input type="button" value="Fade Out" onClick="new Effect.Fade($('test'))"> <input type="button" value="Fade In" onClick="new Effect.Appear($('test'))"> <input type="button" value="Slide Up" onClick="new Effect.SlideUp($('test'))"> <input type="button" value="Slide Down" onClick="new Effect.SlideDown($('test'))"> <input type="button" value="Highlight" onClick="new Effect.Highlight($('test'))"> <input type="button" value="Shake" onClick="new Effect.Shake($('test'))"> </form> <div id="test" style="background-color:#CCC; margin:20px; padding:10px;"> <h2>Testing Effects</h2> <hr> <p>This section of the document is within a <div> element with the <b>id</b> value <b>test</b>. The event handlers on the buttons above send this object to the <a href="http://script.aculo.us/">script.aculo.us</a> library to perform effects. Click the buttons to see the effects. </p> </body> </html>
This document starts with two <script> tags to include the library's files. The effects are triggered by the event handlers defined for each of the six buttons. The section at the end defines the test element that will be used to demonstrate the effects.
To try this example, make sure the prototype.js and effects.js files from Script.aculo.us are stored in the same folder as your script, and then load the HTML file into a browser. The display should look like [Figure 8.2], and you can use the six buttons at the top of the page to trigger effects.
Summary
[wax ka badal]In this hour, you learned some specifics about the Math and Date objects built into JavaScript, and learned more than you ever wanted to know about random numbers. You also learned how third-party libraries can simplify your scripting, and you used a library to create special effects in a web page.
You've reached the end of Part II, which covered some basic building blocks of JavaScript programs. In Part III, you'll learn more about the Document Object Model, which contains objects that refer to various parts of the browser window and HTML document. This begins in [Hour 9], "Responding to Events."
Q&A
[wax ka badal]Q1: | The random numbers are generated so quickly I can't be sure it's happening at all. Is there a way to slow this process down? |
A1: | Yes. If you add one or more form fields to the example and use them to display the data as it is generated, you'll see a much slower result. It will still be done within a couple of seconds on a fast computer, though. |
Q2: | Can I use more than one third-party library in the same script? |
A2: | Yes, in theory: If the libraries are well written and designed not to interfere with each other, there should be no problem combining them. In practice, this will depend on the libraries you need and how they were written. |
Q3: | Can I build my own library to simplify scripting? |
A3: | Yes, as you deal with more complicated scripts, you'll find yourself using the same functions over and over. You can combine them into a library for your own use. This is as simple as creating a .js file. |
Quiz Questions
[wax ka badal]Test your knowledge of JavaScript libraries and built-in functions by answering the following questions.
1. Which of the following objects cannot be used with the new keyword?
- Date
- Math
- String
2. How does JavaScript store dates in a Date object?
- The number of milliseconds since January 1, 1970
- The number of days since January 1, 1900
- The number of seconds since Netscape's public stock offering
3. What is the range of random numbers generated by the Math.random function?
- Between 1 and 100
- Between 1 and the number of milliseconds since January 1, 1970
- Between 0 and 1
Quiz Answers
[wax ka badal]1. | b. The Math object is static; you can't create a Math object. |
2. | a. Dates are stored as the number of milliseconds since January 1, 1970. |
3. | c. JavaScript's random numbers are between 0 and 1. |
Exercises
[wax ka badal]To further explore the JavaScript features you learned about in this hour, you can perform the following exercises:
- Modify the random number script in [Listing 8.1] to run three times, calculating a total of 15,000 random numbers, and display separate totals for each set of 5,000. (You'll need to use another for loop that encloses most of the script.)
- Visit the Script.aculo.us page at http://script.aculo.us/ to find the complete list of effects. Modify [Listing 8.2] to add buttons for one or more additional effects.