Chapter 22. Using Third-Party Libraries


WHAT YOU’LL LEARN IN THIS CHAPTER:

• Why you might use a third-party JavaScript library

• How to download and use one of the more popular third-party JavaScript libraries in your applications


Third-party JavaScript libraries, or code libraries written and maintained by another party for easy implementation in your own code, offer many advantages. First and foremost, using these libraries enables you to avoid reinventing the wheel for common tasks. Additionally, these libraries enable you to implement cross-browser scripting and sophisticated user interface elements without first having to become an expert in JavaScript.

Using Third-Party Libraries

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.

Prototype

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>


Note

Prototype is free, open-source software. You can download it from its official website at http://www.prototypejs.org/. Prototype is also built into the Ruby on Rails framework for the server-side language Ruby—see http://www.rubyonrails.com/ for more information.


jQuery

The first implementation of jQuery was introduced in 2006. What was originally an easy, cross-browser means DOM manipulation has subsequently become a stable, powerful library containing not just DOM manipulation tools, but many additional features that make cross-browser JavaScript coding much more straightforward and productive.


Note

jQuery’s home page is at http://jquery.com/, where you can not only download the latest version, but also gain access to extensive documentation and example code.

The companion UI library can be found at http://jqueryui.com/.


The library is currently up to version 1.6.2 and now also has an additional advanced user interface extensions library that can be used alongside the existing library to rapidly build and deploy rich user interfaces or add a variety of attractive effects to existing components.

Like the Prototype library described previously, jQuery has at its heart a sophisticated, cross-browser method for selection of page elements. The selectors used to obtain elements are based on a combination of simple CSS-like selector styles, so with the CSS techniques you learned in Part III, “Advanced Web Page Design with CSS,” you should have no problem getting up to speed with jQuery. For example, if you want to get an element that has an ID of someElement, all you do is use the following:

$("#someElement")


Tip

If you don’t want to download and store the jQuery library on your own computer, you can use a remotely hosted version, such as the one by Google. Instead of including a locally hosted .js file in your page head, use the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

In many cases, this provides better performance than hosting your own version, due to Google’s servers being optimized for low-latency, massively parallel content delivery.


Or to return a collection of elements that have the someClass class name, you can simply use the following:

$(".someClass")

We can very simply get or set values associated with our selected elements. Let’s suppose, for example, that we want to hide all elements having the class name hideMe. We can do that, in a fully cross-browser manner, in just one line of code:

$(".hideMe").hide();

Manipulating HTML and CSS properties is just as straightforward. To append the phrase “powered by jQuery” to all paragraph elements, for example, we would simply write the following:

$("p").append(" powered by jQuery");


Tip

You can even extend jQuery yourself by writing further plug-ins or use the thousands already submitted by other developers. Browse http://www.jqueryplugins.com/ to see lots of examples in searchable categories.


To then change the background color of those same elements, we can manipulate their CSS properties directly:

$("p").css("background-color","yellow");

Additionally, jQuery includes simple cross-browser methods for determining whether an element has a class, adding and removing classes, getting and setting the text or innerHTML of an element, navigating the DOM, getting and setting CSS properties, and handling of easy cross-browser events.

The associated UI library adds a huge range of UI widgets (such as date pickers, sliders, dialogs and progress bars), animation tools, drag-and-drop capabilities, and much more.

Script.aculo.us

By the end of this book, you’ll learn to do some useful things with JavaScript, often using complex code. But you can also include impressive 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);


Note

You will create a script that demonstrates several Script.aculo.us effects in the Try It Yourself section later this chapter.


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"));

AJAX Frameworks

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.

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, and you’ll try your hand at this later in this book.

Both jQuery and the Prototype library, described previously, include 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.


Note

See Chapter 24, “AJAX: Remote Scripting,” for examples of remote scripting, with and without using third-party libraries.


Other Libraries

There are many more JavaScript libraries out there, and more are appearing all 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.

• MooTools (http://mootools.net/) is a compact, modular JavaScript framework enabling you to build powerful, flexible, and cross-browser code using a simple-to-understand, well-documented API (application programming interface).


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.

Downloading the Library

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.


Caution

This example was created using version 1.9.0 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.


The download is available as a Zip file. Inside the Zip file you will find a folder following the naming convention of scriptaculous-js-x.x.x where each x stands for part of the version number (the version as of this writing is 1.9.0). 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.


Note

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

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

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 <div> 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'))">


Tip

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.


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.

Building the Script

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

Listing 22.1 The Complete Library Effects Example


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <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 &lt;div&gt; element
   with the <strong>id</strong> value of <strong>test</strong>.
   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>
   </div>
</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 <div> 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 it into a browser. The display should look like Figure 22.1, and you can use the six buttons at the top of the page to trigger effects.

Figure 22.1 The library effects example.

image

Summary

In this chapter, you learned about some of the many third-party libraries available for JavaScript. These can offer many advantages including easy cross-browser scripting, selection and editing of HTML and CSS values, animation, and more sophisticated user-interface tools such as drag-and-drop.

Q&A

Q. How do I include a third-party JavaScript library into my pages?

A. The process varies slightly from library to library. Usually it’s simply a matter of including one or more external .js files into the <head> part of your web page. See the documentation supplied with your chosen library for specific details.

Q. Can I use more than one third-party library in the same script?

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

Q. Can I build my own library to simplify scripting?

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

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. Which of the following objects is not a JavaScript library?

a. MooTools

b. Prototype

c. AJAX

2. How can you extend jQuery yourself?

a. jQuery can’t be extended.

b. By writing server-side scripts.

c. By writing a plug-in or using a prewritten one.

3. What other JavaScript third-party library does Script.aculo.us employ?

a. Prototype

b. Dojo

c. jQuery

Answers

1. c. AJAX is a programming technique enabling your scripts to use resources hosted on your server. There are many libraries to help you employ AJAX functionality, but AJAX itself is not a library.

2. c. jQuery has a well documented way to write and use plug-ins.

3. a. Script.aculo.us uses the prototype.js library.

Exercises

• Write a simple script using the jQuery library or use an example script from the jQuery website. Run the script using both locally and remotely hosted versions of jQuery. Can you see any difference in performance?

• Visit the Script.aculo.us page at http://script.aculo.us/ to find the complete list of effects. Modify Listing 22.1 to add buttons for one or more additional effects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.93.137