Popular JavaScript Framework Libraries: JQuery, the Yahoo! UI Library (YUI) and MochiKit | WebReference

Popular JavaScript Framework Libraries: JQuery, the Yahoo! UI Library (YUI) and MochiKit

By Rob Gravelle


[next]

Welcome back to our overview of the most popular JavaScript Framework Libraries. Our goal is to help you make a more informed decision when choosing the right Framework. Last time we discussed the Prototype, script.aculo.us and MooTools Frameworks, three of the most popular ones out there. This week, we look at three strong contenders for the title of Framework supremacy: JQuery, the Yahoo! UI Library (YUI) and MochiKit.

JQuery

The jQuery Framework is built upon the jQuery object that extends the DOM. It's provided using the $ operator. This approach differs from a class-oriented one such as Prototype in that it allows for chainability of method calls, much like the C# language. Since every call returns the queried object, you can link functions one after another, making many calls in one statement:

The $(document).ready Handler

A common dilemma faced by developers when moving code from the <BODY> tag's onload event to the JavaScript file is that the window onload fires before the page has completed loading. jQuery has created a function that solves this problem. The $(document).ready() function accepts a function as an argument that it calls only after the page has loaded. This is the ideal place to call any code that references DOM elements. The following example assigns code to all the links' click events on the page:

DOM Utilities

It should come as no surprise that jQuery provides many ways to traverse and manipulate DOM elements, since it directly extends the DOM. jQuery's selector expressions cover the full range of CSS 1-3, along with basic XPath. In addition, jQuery provides many of its own expressions and functions:

jQuery Selectors:

  • :even/:odd
    Selects every other even or odd element from a matched element set; e.g.: $('li:even') selects only even list items, whereas $('li:odd') selects only odd list items
  • :eq(N) and :nth(N)
    Selects the Nth element from the matched element set; e.g.: $('li:6') selects the sixth list item.
  • :gt(N)/lt(N)
    Selects all matched elements whose index is greater or less than N; e.g.: $('li:gt(6)') selects all list items after the sixth, whereas $('li:lt(6)') selects all list items before the sixth.
  • :first
    Equivalent to :eq(0) or nth(0); e.g.: $('p:first') selects the first paragraph on the page.
  • :last
    Selects the last matched element; e.g.: $('p:last') selects the last paragraph on the page.
  • :parent
    Selects all elements which have child elements (including text); e.g.: $('div:parent') selects all <DIV> elements that have content (which they probably all do!).
  • :contains('text')
    Selects all elements which contain the specified text; e.g.: $(div:contains('pick me')) selects all <DIV> elements that contain the text 'pick me'.
  • :visible
    Selects all visible elements (this includes items that have a display of block or inline, a visibility of visible, and aren't form elements of type hidden); e.g.: $('div:visible') selects all visible <DIV> elements.
  • :hidden
    Selects all hidden elements (this includes items that have a display of none, or a visibility of hidden, or are form elements of type hidden); e.g.: $('div:hidden') selects all hidden <DIV> elements.

Selectors can also be combined for more precise filtering. For instance, $('ol .menu > strong') gets all strong elements that are children of any element with a class of "menu" as long as the class is a descendent of an ordered list. $('li + li > a[href$=pdf]') gets all links ending in "PDF" that are children of any list item that has another list item as its previous sibling.

jQuery also provides many functions for manipulating DOM elements. For instance, there are getters and setters for both an element's innerHTML and innerText properties. Named html() and text() respectively, these functions allow you to easily change a node's attributes in a browser-independent fashion. The following example sets all the paragraphs' onclick events to an anonymous function that retrieves the <P> tag's innerHTML and replaces it with the escaped HTML tags, replacing "<" and ">" by their HTML counterparts of "&lt;" and "&gt;":

Other, more specialized functions insert, replace, remove and copy elements.

Ajax Requests

jQuery handles Ajax calls using simple functions. The most commonly used are jQuery.post() and jQuery.get(). They accept four parameters, the last three of which are optional: the URL of the page to load, a JavaScript object literal of name/value pairs to send to the server, the callback function and the data type to be returned to callback function (JSON, XML, etc.). The callback function will receive two string arguments: the data and the textStatus, which can be one of the following values: "timeout", "error", "notmodified", "success", and "parsererror". The Ajax request options can be retrieved via the this pointer. Here's an example of the post() function which sends some name/value pairs to a PHP script and then sends the resulting XML data to a function for further processing:

Events

Like most Frameworks, jQuery offers a number of different Ajax events for subscription. Here's a full list of the events and in what order they are broadcast:

There are two types of events: Local events and Global events. Local events are callbacks that you can subscribe to within the Ajax request object. Global events are broadcast to all elements in the DOM, triggering any handlers which may be listening.

Local events include: beforeSend, success, error and complete. The global events can be identified by their "ajax" prefix. They are: ajaxStart, ajaxSend, ajaxSuccess, ajaxError, ajaxComplete and ajaxStop. The ajaxStart and ajaxStop events relate to all Ajax requests on the page. The following code retrieves an XML document using the local success and error events and displays them in a list:

In the following example, several global Ajax events are bound to a <DIV> element to display messages on the call's progress:

jQuery also has the capability to easily load a chunk of HTML into an area of the page. To do that, simply select the element you need and use the load() function. Here's an example that updates some statistics:

Effects

jQuery is a well rounded Framework that can handle basic animation and effects, in addition to the functionality outlined above. Once of the most useful is the animate() function, which changes any numeric CSS style value, such as height, width, opacity, or position, over time. You can also specify the speed of the animation, either in milliseconds or in one of the predefined speeds: slow, normal, or fast. You can even attach a callback function! Here's an example that animates the height and width of an element. There's no start value; only the end value is required as the start values are taken from the current size of the element:


[next]