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.
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, 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.
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.
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 (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.
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).
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. 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.
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.
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
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.
• 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.
18.226.93.137