Stanford University Wiki
Advertisement

jQuery JavaScript Library[]

Jquerylogo
jQuery Homepage
Team: Johnny Zhou and Juho Kim

Overview[]

jQuery is a Javascript library that provides abstractions for simpler and rapid web development. The underlying design goal is to help the developer 'write less, do more', it abstracts away a large amount of the more repetitive, low-level, and browser-specific code, allowing the developer to do many common things in a very intuitive and simple manner, such as selecting and manipulating particular DOM elements, modifying CSS classes, handling events with minimal code, and using the simplified cross-browser AJAX facilities.

In order to generate a lightweight footprint, the main .js file only includes the core API. The core library also provides some pre-baked interactions such as drag and drop, resizing, and reordering, which can be attached to any div element via a single function call, e.g. $(".somediv").draggable(). The core library has also been extended with full-featured custom UI components with the jQuery UI library, which includes fancier UI elements such as magnifiers, accordions, color pickers, progress bars, sliders, spinners, tabs, and transition effects. Plugin architecture facilitates open plugin development by the community, making jQuery even more powerful.

After its first released by John Resig in January 2006, it soon gained great popularity due to simplicity and easy of use. Major websites including Google, Twitter, Digg, and Amazon, just to name a few, are using jQuery. Currently, the jQuery Team of 10+ developers are making contributions. Its license model is dual license:the MIT License and the GNU General Public License. jQuery is free and open source software. The current stable version is 1.2.6.

Examples[]

jQuery can replace all behavior-related codes from HTML files, so that HTML file is dedicated to structure of the document, while behavior is taken care of by Javascript and jQuery. Adding jQuery functionality is as easy as adding a single line of code. This makes it possible to use the complete core API of jQuery within an HTML file.

<script type="text/javascript" src="/path/to/jquery.js"></script>

jQuery replaces the existing 'onload' event handler. Everything inside ready() will load as soon as the DOM is loaded and before the page contents are loaded. This solves a problem of 'onload', which waits until it finishes downloading all images (even banner ads).

$(document).ready(function() {
// your code
});

jQuery uses '$' as the factory method, meaning 'get this'. For example, $("a") returns all <a> tag elements from the HTML file. The magic of jQuery comes from the 'chainability' of function calls. Just like pipe mechanism in Unix system, every method within jQuery allows you to chain methods to the current set of elements. This is possible due to the fact that every function call returns the query object itself, and developers do not need to worry about the return type of functions. Another benefit of chaining is dramatically reduced line of codes. Based on such structure, developers can easily traverse DOM tree and manipulate elements and styles. Here are some examples of capabilities of the core jQuery library that make common tasks simple to almost a single line of code.

Slide animation of a paragraph:

$("div.someContent p.firstparagraph:hidden").slideDown("slow");
$("div.someContent p.firstparagraph:visible").slideUp("slow");

Append text to the end of every paragraph except the paragraph with class "no":

$("div.someContent p:not(.no)")
  .append("<strong class="addedtext"> Text that is just appended.</strong>")});
$("strong.addedtext").remove();

Remove a paragraph with a fade-out animation:

$("div.someContent p.paragraph").hide("slow");

Changing font of all italic text:

$("div.someContent em").css({color:"#90ABCDEF", fontWeight:"bold"});

Modifying CSS classes:

$("p.paragraph").addClass("newClass");
$("p.paragraph").removeClass("newClass");

Core API Examples

Jquery ui

jQuery UI Example

UI Examples

Developers can customize the content and size of the footprint by selectively adding or removing UI components they plan to use. There are UI core, interaction modules, reusable widgets that are built on top of simple interactions, and additional visual effects. Such modularity enables users to easily combine desired components the way they want to present on the screen. The size of the UI package may vary from less than 10Kb (just the core) to 338Kb (full package, not compressed).

Uniqueness[]

In terms of the core functionalities provided, jQuery is not an extreme departure from the norm with existing JavaScript libraries such as Google Web Toolkit, Yahoo UI Library, and MooTools. All of these libraries aim to provide a clean abstraction of most of the fine-grained details and underpinnings of common JavaScript-powered capabilities. To varying extents, all of these full function libraries provide cross-browser support and encapsulation for handling DOM manipulation, CSS, AJAX, events, UI effects, etc. Furthermore, these libraries all provide mechanisms for easy selection and traversal of the DOM via string queries. However, jQuery is different from the rest in that it provides a much cleaner abstraction with uniformity and ease of use. It is uniform in the sense that every method in jQuery returns the universal jQuery object, allowing for the chaining of various method calls. This is based on the object-oriented programming paradigm, and offers the programmer much more ease of use, as there would no longer be a need to try to figure out what return values are for all the library functions.

For example, consider the following snippet of jQuery code:

$("a").addClass("test").show().html("foo");

Each of the 4 jQuery method calls ($(), addClass(), show(), and html()) returns a jQuery object, allowing these calls to be chained together for consistency and a minimal amount of code. The above snippet selects all "a" elements, adds the "test" CSS class to them, make them visible if they are hidden, and sets their inner html to "foo". This is a significant improvement from other existing packages for minimizing the amount of code necessary to perform all sorts of tasks. This consistency is definitely unique to jQuery, and it entails one less thing that developers will need to keep track of and reference via documentation that’s often obscure or unnecessarily difficult and long to navigate through.

Another unique and helpful feature about jQuery is its ability for interoperability with other JavaScript libraries. jQuery is contained entirely in its own namespace, thus eliminating any potential variable and function naming collisions. Like other toolkits, jQuery leverages the $ operator to provide a shortcut to the “jQuery()” function. This would have been in problem when using jQuery with other JavaScript libraries that employ the same shortcut, except that jQuery provides a mechanism for either overriding the $ function or renaming the shortcut via the jQuery.noConflict() function. In other words, $(…) can be reverted back to jQuery(…) or renamed to a different shortcut such as $j(…). This is extremely beneficial for both extensibility and interoperability.

Moreover, another welcome feature that makes jQuery unique is its ease of extensibility via custom third-party plugins. By following a short list of simple rules including file naming convention, semicolon usage, and return value consistency, anybody can easily write a plugin to jQuery enhancing its already well-capable core functionalities. jQuery is very lightweight, and consequently contains fewer out-of-the-box widgets and UI elements that larger toolkits such as Yahoo UI Libraries Google Web Toolkit ship with. However, if desired, the jQuery UI package can be deployed along with the core jQuery library, providing abstractions for many low-level interactions and pre-built UI widgets, such as dynamic mouse interactions and interactive sliders.

jQuery is not a full web application platform such as Ruby on Rails or Java Server Pages, nor is it merely an effects library such as Script.aculo.us or a provider of a specific function such as JavaScrypt for cryptography. Rather, it is a simple compilation of the common but all too repetitive and unnecessarily browser-inconsistent JavaScript functions, abstracting away the messy underpinnings and thus allowing developers to implement various interesting interactions and UI dynamics without the need to have to understand the gory details of how the interaction is implemented. Fundamentally, it is similar to Dojo, MooTools, and MochiKit, but adds its own flavor of uniformity and extensibility that the others do not have.

Critique[]

The overwhelming upside of jQuery is its extreme versatility and extensibility while having functionality comparable to some of the more heavyweight packages such as Google Web Toolkit and Yahoo UI Library. jQuery is very lightweight; its minimized production version is only a mere 15kb .js file. It is very easy to integrate into any web application by simply loading the .js file via <script type="text/javascript" src="jquery.js"></script>. jQuery simplifies many of the common tasks and functions required of JavaScript in modern web applications, including but not limited to DOM element and attribute selection and manipulation, CSS controls, event handling, uniform AJAX handling, and a unique UI effects library. It is not too much unlike some other lightweight JavaScript toolkits such as MooTools and Dojo. At their cores, these libraries essentially allow a web developer to do more with less code in a portable, cross-browser manner. jQuery supports most modern browsers: Internet Explorer 6.0+, Firefox 2.0+, Safari 2.0+, and Opera 9.0+. For example, jQuery allows the developer to write portable AJAX code, obviating the need to handle browser-specific inconsistencies, such as how Internet Explorer handles the XMLHttpRequest differently than Firefox. Additionally, via innate namespace separation and the ability to override the $() function shortcut, jQuery is able to easily work with other JavaScript libraries without any conflicts. jQuery is also very extensible since it is quite easy to enhance jQuery with additional functionality via third-party or custom plugins. As described earlier, these plugins are just additional .js files that are required to follow a small set of rules and conventions to work with the core jQuery library.

Another advantage of jQuery over other existing JavaScript libraries is its speed and performance. Its lightweight footprint allows for fast loading, and the implementers are constantly trying to improve performance. For example, in version 1.2.6, the speed of event handling was increased by 103%.

Wide use and popularity is another merit of jQuery. jQuery's advantages in functionality and ease of use can now be found in several other libraries because many Javascript libraries are adopting others' advantages. But the fact that jQuery is among the most widely used ones makes it unique. Rich resource and active community support save time for developers facing difficulties in their applications, and through documentation surely explains its popularity over dozens of competitors.

The jQuery toolkit also can incorporate the jQuery UI library ([1]), which contains many highly-interactive desktop-like web widgets and dynamic UI components such as sliders, magnifiers, and various mouse interactions. Unlike GWT and YUI, jQuery provides a nice separation between the core JavaScript library and the custom UI components, allowing the developer to incorporate the heavier UI library only if needed.

We believe jQuery does provide a "sweet" abstraction. The code is very easy to learn, and the API is simple and not too large. With the object-oriented chainability nature of jQuery (nearly every method returns the jQuery object), it is easy for different components to work together. jQuery also certainly allows the developer to write less code. For example, the following line of jQuery code:

$("div.test").add("p.quote").addClass("blue").slideDown("slow");

selects all div tags with the class attribute "test" and all p tags with the class attribute "quote", adds the CSS class "blue" to all of them, and finally animates them with a slow slide-down. This one line of code accomplishes what standard JavaScript would require perhaps 10+ lines to do. Clearly, jQuery provides the developer with a lot of functionality with minimal required code.

There are not many weaknesses with jQuery considering its scope. It is a significantly smaller library in comparison to GWT and YUI, and thus naturally provides somewhat less capability and abstraction than those larger packages. For example, GWT has a mechanism for transforming Java code to JavaScript. The same applies to its relatively new UI library. While focusing on easy deployment of interaction components, jQuery lacks in the UI customization, providing only a small set of parameters for tweaks. Compared to Flash or Silverlight, jQuery falls behind in the richness and performance of interactive components. This is probably the common challenge for all Javascript UI libraries.

Another apparent weakness of jQuery is also the result of one of its strengths. The chainable nature of the jQuery objects, although it allows for a minimal amount of code, also makes the code significantly harder to read. This encourages developers to cram lots of code into a very small space. Several actions can be chained together into one line of code, but often it can be advantageous to separate those out to individual lines to allow developers more ease in following the logic and progression of the code. This is one of those inherent trade-off problems found everywhere in technology - making something simpler and more efficient almost always entails more complexity in another area.

Conclusion[]

jQuery is very well suited for medium-complexity web applications that require a high level, but straightforward amount of interaction between JavaScript and the DOM. jQuery leverages XPath to make DOM selection very easy and very fast, and also provides many methods for event handling, AJAX, and CSS manipulation. Larger-scale applications may have a harder time utilizing jQuery because of its stringent focus on DOM manipulation. Web applications desiring many common yet simple animations would do well to leverage jQuery's pre-canned set of UI components and animations. Essentially, however, any web application desiring a well-designed abstraction for DOM selection and manipulation would benefit from using jQuery. jQuery is a very lightweight, versatile, and capable JavaScript library.

Advertisement