Mazarin

Articles

jQuery - The latest buzz in the Javascript frameworks

jQuery is a popular open source JavaScript Library, which provides many advanced and cross-browser functions, that can enhance the web applications. It is written based on few very simple intuitive principles. jQuery would help achieving considerable productivity gains and it is easy to learn and work. This tool has the potential to bring about quiet a change in client side development with complex UIs. It has a small library with Document Object Model (DOM) and a small memory footprint, quick access to AJAX, and some basic animations. It simplifies event handling, animations and developing Ajax - enabled web pages thus promoting rapid application development. This JavaScript toolkit is designed to simplify various tasks such as element selection, DOM manipulation, event handling, AJAX and animations, as its tagline states, “Write less, do more”.

jQuery was released in 2006 by John Resig. Since then, it has been widely popular and acceptable amongst the web application development community worldwide. Most importantly, numerous plugins of jQuery have been developed.

Why jQuery ?

1. Easy to Use & Easy to Learn
  • jQuery is very easy to learn because it does so much in few statements. The documentation on jQuery.com is very good and the huge online community and samples can help anyone to become a master with it, within a short period.
2. Lightweight Library
  • The basic jQuery is just 15K and it has a lightweight memory footprint too.
3. Browser Compatibility
  • Working with RAW JavaScript or DOM Programming does bring-in its challenges while handling the browser-specific compatibility issues. jQuery provides few utilities to help working in multiple browser environments. JavaScript had varying DOM and CSS implementations across different browsers. In addition, the event management interfaces used to differ in JavaScript for different browsers. jQuery on the other hand provides a common browser API that provides cross browser support and provides more robust and readable JavaScript code with simplicity of use. jQuery also provides support for an excellent, easy to use normalized event handling model with much reduced code. The jQuery Event Handling model is consistent across all browsers. The event object is a cross browser normalized one and one event object is always passed as a parameter to an event handler. It supports CSS 1-3 and basic X-Path. It works well with Firefox 1+, Internet explorer 5.5+, Safari 1.3+ and Opera 8.5+.
4. Supports gracefully degrading code
  • With the traditional JavaScript code, programmers had to use browser sniffing, an old and buggy method of detecting the version of the browser and to provide supporting code to handle each and every browser specific issue. jQuery supports writing functions that gracefully degrade depending on the browser version, thus enabling the web programmers to develop feature rich JavaScript code that gracefully degrade in cases where the code is not supported by the browser.
5. Highly Modular architecture
  • jQuery is highly modular. We take only the modules we want (i.e. the query system, events, the basic effects, ajax) and can then extend these as needed. Module developers could even provide their module-specific plugins/extensions to jQuery, so we will have lots of code reused by having all the required flexibility.
6. Plugin based extensibility
  • It Support for Seamless extensibility. jQuery provides support for extensibility through an easy to use plug-in API that enables extending the jQuery core library seamlessly. jQuery holds a strong and flexible mechanism for adding methods and functionalities which bundles as plug-ins. One of the reasons for the success of jQuery is its vibrant community, which provides hundreds of high-quality plug-ins. One such important plug-in is JQury-UI.
7. Widespread usage of the library
  • Since its inception in 2006, jQuery has gained lot of popularity and as a result of that, few key organizations in the world have adopted it to enhance the usability of their web applications. IBM, Google and Microsoft are to name a few.
8. Minimizing code and increasing Readability
  • Usage of jQuery also reduces the amount of code drastically. Method chaining helps to reduce code and increase the code readability.
9. Easy DOM manipulation
  • Adhering to CSS3 selector specifications for DOM manipulation makes it easy to traverse through the DOM using jQuery syntax.
10. Well documented API and ample amount of resources to be used
  • jQuery has solid API documentation and a host of tutorials readily available in the internet and a very active community around the toolkit, for example on the general mailing list, where lots of people have been contributing to the success of the API. Eg: A useful API listing

How jQuery can be used ?

The basic idea of using jQuery is to select one or more DOM elements and to perform some activities with them. To achieve this, jQuery has a powerful selection mechanism using CSS syntax. jQuery uses ‘$’ as an alias for the jQuery class, which is the starting point for any of its scripts. All is initiated by constructing a jQuery object and giving it some arguments. These arguments depict the elements in the DOM that are to be selected.

Eg: Retrieving an element with a given id

$('#element');

In this case, an object of the jQuery class is created, the $(...) works like a constructor. The object looks up the element identified by the given id and stores it. The traditional way of using the DOM to achieve this same effect is to use

document.getElementById ('elem');

Which involves more code hence code maintenance is difficult. The simplicity of jQuery syntax makes the code more readable and easy to maintain too.

The argument to the $ constructor can be a CSS selector expression. This can be used to jQuery to obtain and manipulate various sections of the DOM to get the desired behaviors of the web applications.

The $ object itself contains an array of DOM elements matched by the given query.

$('a').length;

It is possible to retrieve the actual elements found by the query by using the get method. By default, it returns all the matched elements as an array. When the argument number is given, it returns the elements at that position in the array.

var anchors = $('a').get(); //an array
var first = $('a').get(0);
1. Chaining of methods

The jQuery method calls can be chained indefinitely. This brings a lot of power to the world of jQuery, particularly when the manipulation of DOM is concerned.

$('a').slice(0,3).each( function (i) {
	alert(this);
});
2. Manipulating the Selected elements

jQuery supplies several methods for manipulating the matched elements. CSS selectors play a key role here. Several CSS manipulations can be done with minimal jQuery code.

$('a').css( { text-decoration: 'none', color: 'green'} );

In the traditional DOM manipulation, the code will be much more complicated.

var anchors = document.getElementsByTagName('a');
	for ( var i = 0, a; a = anchors[i]; i++ )
		{
			a.style.textDecoration = 'none';
			a.style.color = 'green';
		}
3. Event binding with jQuery

The first function that we can mention is $.ready(). Everything in the jQuery utility is HTML and DOM. So to process this, the document should be loaded before the jQuery features are being used. This can be done using the above mentioned ready event. “Ready” is the first event fired once the document is loaded. This is bound to the event DOMContentLoaded, which fires when the DOM is fully constructed.

$( function () {
	//Do init stuff here
});

jQuery has one general and several specific functions for adding the event handlers. The general function is called $.bind(), and it works identically as the DOM addEventListener function.

$('#submitButton').bind( 'click', function() {
	//Submit request
});

This action can be replaced by the usage of the click function that is readily available with jQuery.

$('# submitButton'').click( function() {
	//Submit request
});
4. Use of Ajax

Ajax related implementations using jQuery involves the usage of the $.get() and $.post() methods to send simple GET and POST requests respectively. Each take three arguments, the request URL, a set of parameters (optional) and a callback function (optional) for the resulting data.

$.get( 'orderBooks.php', { 'isbn' : 'ISBN 0-202-098761-9' }, showOrderDetails );
$.post('addBook.php' { 'name' : 'jQuery CookBook', 'e-mail' : 'author@jquery.org' } 
, showBookDetails );

jQuery has another flexible variant to control the queries. That is The $.ajax() function which takes a single dictionary, which can set several properties of the request.

$.ajax( { url: 'addBook.php',  type : 'POST', success : showBookDetails, 
data : {'name' : ''jQuery CookBook, 'e-mail' : 'author@jquery.org } }, 
dataType : 'json', error : showError } );
5. Animations and Visual Enhancements

jQuery has extensive support for animations and visual enhancements too. This includes effects such as fading, sliding, hiding and toggling.

$('#commentControls').toggle();

For some functions, even the behaviors can be controlled.

$('.inactive').slideUp('fast');
6. Resolving conflicts

The jQuery toolkit separates all the code into one place, the jQuery class. This ensures that the jQuery code can co-exist with other libraries and APIs. The use of $ conflicts with a similar function in the Prototype library, but jQuery provides an alternative mechanism by calling $.noConflict(), releasing the $ back to Prototype. Users can alias the jQuery class again by simply creating another variable like $jquery and referring to it.

<script src="prototype.js"></script> 
<script src="jQuery.js"></script> 
<script> 
	jQuery.noConflict(); // Use jQuery via jQuery(...) 
	jQuery(document).ready(function() { 
	jQuery("div").hide(); }); 
	// Use Prototype with $(...). 
	$('newDiv').hide(); 
</script>
7. Test driven development

The jQuery plugin development has created an invaluable plugin to promote one of the best practices in software development in to the custom jQuery code and its test driven development. QUnit allows the web programmers to write supporting test cases for their jQuery code, which will be very useful, in terms of maintaining complex and extended jQuery code.

8. jQuery UI

If the developers want to create slick UIs with rich visual effects, the jQuery core library doesn’t quite support that sort of features and the alternative is a nice extension of jQuery that provides some common and practical rich user interface features, such as dropdowns and tabs.

jQuery: Today and Tomorrow

JQuery gained Microsoft support in 2008 as part of the ASP.NET MVC project. It is distributed with Visual Studio 2010 including JQuery intellisense, snippets, examples, and documentation. Additionally Microsoft will be developing additional controls or widgets, to run on top of JQuery that will be easily deployable within any .NET applications.

Nokia is using JQuery to develop applications for their WebKit-based Web Run-Time. The run-time is a scaled down browser rendering engine that allows for easy, yet very powerful, application development. This means that JQuery will be distributed on all Nokia phones that include the web run-time in the near future.

To start this, Nokia will be moving a number of their applications to work on the run-time including the maps and building them using JQuery. It will become an integral part of their widget development platform, resulting that any mobile developer will be able to use JQuery in the construction of widgets for Nokia phones.

Disadvantages of jQuery

  • Due to the usage of $, there can be conflicts with other APIs which shares the $ that needed to resolved, while using JQuery.
  • Since the JQuery is a rapidly evolving API, developers can face versioning issues that need to be carefully handled.
  • Chaining unnecessarily can cause performance degrading, so it has to be used with caution.
  • Formatting and manipulating the standard JavaScript types is not directly supported by JQuery, thus needing to implement them separately.

Conclusion

JQuery has simplified the way JavaScript has been written so far, and the versatility of the API is visible for its demand and popularity. Burst to the web development world in 2006, it has taken the client side scripting to a new dimension with its unique DOM selector mechanism and the highly usable plugin repository. With the rapid popularity, the resources available for learning and sharing knowledge have increased too. It is also known to have a relatively short learning curve.

Comparison of JS Frameworks

References:

Online Resources
Books
  • Sitepoint: jQuery – Novice to Ninja – Earle Castledine and Craig Sharkie

Related Topics

| Share