Tuesday

How Jquery can help to create Web2 application

What's jQuery?

Created by John Resig in early 2006, jQuery is a great library for anyone who works with JavaScript code. Whether you're new to the JavaScript language and want a library to address some of the complexities of Document Object Model (DOM) scripting and Ajax or you're an advanced JavaScript guru and tired of the boring repetition involved with DOM scripting and Ajax, jQuery will suit you well.

jQuery helps you keep your code simple and succinct. You no longer have to write a bunch of repetitious loops and DOM scripting library calls. With jQuery, you can get right to the point and express yourself in the fewest possible characters.

The jQuery philosophy is certainly unique: It's designed to keep things simple and reusable. When you understand and feel comfortable with the philosophy, you'll start to see just how much jQuery can improve the way you program.

Back to top

Some simple simplifications

Here's a simple example of the impact jQuery can have on your code. To do something really simple and common, such as attach a click event to every link in an area of a page, you'd use plain JavaScript code and DOM scripting, as shown in Listing 1.

Listing 1. DOM scripting without jQuery


var external_links = document.getElementById('external_links');
var links = external_links.getElementsByTagName('a');
for (var i=0;i < link =" links.item(i);" onclick =" function()"> elements inside the external_links element. That's a mouthful to say in English -- and even in DOM scripting -- but in CSS, it couldn't be simpler.

The $() function returns a jQuery object containing all the elements that match the CSS selector. A jQuery object is something like an array but comes with a ton of special jQuery functions. For example, you can assign a click handler function to each element in the jQuery object by calling the click function.

You can also pass an element or an array of elements to the $() function, and it will wrap a jQuery object around the elements. You might want to use this functionality to employ jQuery functions on things like the window object. For example, you typically assign the function to the load event like this:

window.onload = function() {
// do this stuff when the page is done loading
};


Using jQuery, you write the same code like this:

$(window).load(function() {
// run this when the whole page has been downloaded
});


As you probably already know, waiting for the window to load is painfully slow, because the whole page must finish loading, including all the images on the page. Sometimes, you want the images to finish loading first, but most of the time, you just need the Hypertext Markup Language (HTML) to be there. jQuery solves this problem by creating a special ready event on the document, used like this:

$(document).ready(function() {
// do this stuff when the HTML is all ready
});


This code creates a jQuery object around the document element, then sets up a function to call the instance when the HTML DOM document is ready. You can call this function as many times as necessary. And, in true jQuery style, a shortcut calls this function. Simply pass a function to the $() function:

$(function() {
// run this when the HTML is done downloading
});


So far, I've shown you three different ways to use the $() function. With a fourth way, you can create an element using a string. The result is a jQuery object containing that element. Listing 3 shows an example that adds a paragraph to the page.

Listing 3. Creating and appending a simple paragraph


$('
')
.html('Hey World!')
.css('background', 'yellow')
.appendTo("body");


As you might have noticed from the previous example, another powerful feature of jQuery is method chaining. Every time you call a method on a jQuery object, the method returns the same jQuery object. This means that if you need to call multiple methods on a jQuery object, you can do it without re-typing the selector:

$('#message').css('background', 'yellow').html('Hello!').show();


Back to top

Ajax made simple

Ajax couldn't be any easier than it is with jQuery. jQuery has a handful of functions that make the easy stuff really easy and the complex stuff as simple as possible.

A common use of Ajax is to 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:

$('#stats').load('stats.html');


Often, you simply need to pass some parameters to a page on the server. As you'd expect, this is incredibly simple in jQuery, too. You can use choose between $.post() and $.get(), depending on which method you need. You can pass an optional data object and callback function if you need them. Listing 4 shows a simple example that sends data and uses a callback.

Listing 4. Sending data to a page with Ajax


$.post('save.cgi', {
text: 'my string',
number: 23
}, function() {
alert('Your data has been saved.');
});


If you really want to do some complex Ajax scripting, you need the $.ajax() function. You can specify xml, html, script, or json, and jQuery automatically prepares the result for your callback function so that you can use it right away. You can also specify beforeSend, error, success, or complete callbacks to give the user more feedback about the Ajax experience. In addition, other parameters are available with which you can set the timeout of an Ajax request or the "Last Modified" state of a page. Listing 5 shows an example that retrieves an XML document using some of the parameters that I mentioned.

Listing 5. Complex Ajax made simple with $.ajax()


$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});


When you get the XML back in the success callback, you can use jQuery to look through the XML the same way you do with HTML. This makes it easy to work with an XML document and integrate the contents and data into your Web site. Listing 6 shows an expansion on the success function that adds a list item to the Web page for each element in the XML.

Listing 6. Working with XML using jQuery


success: function(xml){
$(xml).find('item').each(function(){
var item_text = $(this).text();

$('

  • ')
    .html(item_text)
    .appendTo('ol');
    });
    }


    Back to top

    Animate your HTML

    You can use jQuery to take care of basic animations and effects. At the heart of the animation code is the animate() function, which changes any numeric CSS style value over time. For example, you can animate height, width, opacity, or position. You can also specify the speed of the animation, either in milliseconds or in one of the predefined speeds: slow, normal, or fast.

    Here's an example that animates the height and width of an element at the same time. Notice that there is no start value -- only the end value. The start values are taken from the current size of the element. I've also attached a callback function.

    $('#grow').animate({ height: 500, width: 500 }, "slow", function(){
    alert('The element is done growing!');
    });


    jQuery makes the more common animations easier with built-in functions. You can use show() and hide() elements, either instantly or at a specified speed. You can also make elements appear and disappear by using fadeIn() and fadeOut() or slideDown() and slideUp(), depending on what kind of effect you're looking for. Here's a simple example that slides down a navigation:

    $('#nav').slideDown('slow');


    Back to top

    DOM scripting and event handling

    jQuery is, perhaps, best at simplifying DOM scripting and event handling. Traversing and manipulating the DOM is easy, and attaching, removing, and calling events is completely natural and much less error prone than doing it by hand.

    In essence, jQuery makes it easier to do things that are common with DOM scripting. You can create elements and use the append() function to link them to other elements, use clone() to duplicate elements, set the contents with html(), delete the contents with the empty() function, delete the elements altogether with the remove() function, and even use the wrap() function to wrap the elements with another element.

    Several functions are available for changing the contents of the jQuery object itself by traversing the DOM. You can get all the siblings(), parents(), or children() of an element. You can also select the next() or prev() sibling elements. Perhaps most powerful is the find() function, which allows you to use a jQuery selector to search through the descendants of elements in your jQuery object.

    These functions become more powerful when used with the end() function. This function is like an undo function, going back to the jQuery object you had before you called find() or parents() or one of the other traversing functions.

    When used together with method chaining, these functions allow complex operations to look simple. Listing 7 shows an example in which you find a login form and manipulate several elements around it.

    Listing 7. Traversing and manipulating the DOM with ease


    $('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()

    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()

    // add a submit handler to the form
    .submit(function(){
    return confirm('Are you sure you want to submit?');
    });


    Believe it or not, this example is just a single, chained, line of code spread out with whitespace. First, I selected the login form. Then, I found the optional labels inside it, hid them, and called end() to go back to the form. I found the password field, made the border red, and again called end() to go back to the form. Finally, I added a submit event handler to the form. What's especially interesting about this (besides its obvious brevity) is that jQuery completely optimizes all the query operations, making sure that you don't have to find an element twice when everything is nicely chained together.

    Handling common events is as simple as calling a function like click(), submit(), or mouseover() and passing it an event handler function. Additionally, you have the option of assigning a custom event handler using bind('eventname', function(){}). You can remove certain events using unbind('eventname') or all events with unbind(). For a complete list of ways to use these and other functions, check out the jQuery application program interface (API) documentation in the Resources.

    Back to top

    Unleash the power of jQuery selectors

    Often, you select elements by ID, such as #myid, or by class name, such as div.myclass. However, jQuery has a rather complex and complete selector syntax that allows you to select nearly any combination of elements in a single selector.

    jQuery's selector syntax is based heavily on CSS3 and XPath. The more you know about CSS3 and XPath syntax, the better you'll be at using jQuery. For a complete list of jQuery selectors, including CSS and XPath, check out the links in Resources.

    CSS3 contains some syntax that not every browser supports, so you don't see it often. However, you can still use CSS3 in jQuery to select elements, because jQuery has its own, custom selector engine. For example, to add a dash inside every empty column of a table, use the :empty pseudo-selector:

    $('td:empty').html('-');


    What about finding every element that doesn't have a certain class? CSS3 has a syntax for that, too, using the :not pseudo-selector. Here's how you can hide every input that doesn't have a class of required:

    $('input:not(.required)').hide();


    You can also join multiple selectors into one using commas, just as in CSS. Here's a simple example that hides every type of list on the page at the same time:

    $('ul, ol, dl').hide();


    XPath is a powerful syntax for finding elements in a document. It's a bit different than CSS and lets you do a few things you can't do with CSS. To add a border to the parent element of every check box, you can use XPath's /.. syntax:

    $("input:checkbox/..").css('border', '1px solid #777');


    jQuery adds extra selectors that aren't available in CSS or XPath, as well. For example, to make a table more readable, you would typically attach a different class name to every odd or even row of the table -- otherwise known as striping the table. Doing this with jQuery is a cinch, thanks to the :odd pseudo-selector. This example changes the background of every odd row in tables with a striped class:

    $('table.striped > tr:odd').css('background', '#999999');


    You can see how the power of jQuery selectors can simplify your code. Whatever selection of elements you want to affect, no matter how specific or obscure, you can probably find a way to define them using a single jQuery selector.

    Back to top

    Extend jQuery with plug-ins

    Unlike with most software, writing plug-ins for jQuery isn't a huge ordeal with a complex API. In fact, jQuery plug-ins are so easy to write that you might want to write a few to make your code even simpler. Here's the most basic jQuery plug-in you can write:

    $.fn.donothing = function(){
    return this;
    };


    Although simple, this plug-in does require a bit of explanation. First, to add a function to every jQuery object, you must assign it to $.fn. Next, this function must return this (the jQuery object) so that it doesn't break method chaining.

    You can easily build on top of this simple example. To write a plug-in to change the background instead of using css('background'), you use this:

    $.fn.background = function(bg){
    return this.css('background', bg);
    };


    Notice that I could just return the value from css(), because it already returns the jQuery object. So, method chaining will still work fine.

    I recommend that you use jQuery plug-ins anytime you find that you repeat yourself. For example, you might use a plug-in if you're using the each() function to do the same thing over and over.

    Because jQuery plug-ins are so easy to write, hundreds of them are available for you to use. jQuery has plug-ins for tabs, rounded corners, slide shows, tool tips, date selectors, and probably anything else you can imagine. For a complete list of plug-ins, check out the Resources.

    The most complex and most widely used plug-in is Interface, an animation plug-in that handles sorting, drag-and-drop functionality, complex effects, and other interesting and complex user interfaces (UIs). Interface is to jQuery what Scriptaculous is to Prototype.

    Also popular and useful is the Form plug-in, which allows you to easily submit a form in the background using Ajax. This plug-in takes care of the common situation in which you need to hijack the submit event of a form, then find all the different input fields and use them to construct an Ajax call.

    Back to top

    Life after jQuery

    I've only scratched the surface of what is possible with jQuery. jQuery is fun to use, because you always learn new tricks and features that seem so natural. jQuery simplifies your JavaScript and Ajax programming completely from the first moment you use it; every time you learn something new, your code gets a bit simpler.

    After learning jQuery, I've had a lot more fun programming in the JavaScript language. All the boring stuff is taken care of, so I can focus on coding the juicy stuff. With jQuery, I can barely remember the last time I wrote a for loop. I even cringe at the thought of working with other JavaScript libraries. jQuery has honestly and truly changed the way I look at JavaScript programing forever.
    courtsy: ibm.com

    No comments: