It is JavaScript that brings an HTML page to ‘life’. Whether it is client-side validation, animating the page elements or calling the server in the background to get updated page, one can use JavaScript to achieve all this and much more. However, using JavaScript in its ‘raw’ state compels the developer to write multiple lines to implement each of the afore-mentioned functionality and for each application. The pit-fall in such an approach is that each application will have its own pattern and trying to reuse JavaScript code developed for one application, will ultimately result in re-factoring most of the code so that it meets the requirements of both the applications. This is where JavaScript libraries come into picture. These libraries encapsulate the ordinary yet oft used functionalities (e.g. validation, selection of elements etc.) and provide simplified API to access these functionalities. Among the JavaScript libraries, one of the most used is jQuery. In this discussion, the focus will be on the basics of jQuery. The first section will be about the whys and wherefores of the jQuery. The second section will provide details about using various functionalities of jQuery. That’s the agenda for this discussion.

jQuery – the Whys and Wherefores

To understand how jQuery can ease web client (JavaScript based) development, one has to understand two aspects of jQuery. They are:

1. Functionalities

2. Modules

Understanding the functionalities/services provided by jQuery will tell you what jQuery provides and understanding the modules that constitute jQuery will tell you how to access the services provided by jQuery. Here are the details.

1. Functionalities

The functionalities provided by jQuery can be classified into following

a. Selection

b. Attributes handling

c. Element manipulation

d. Ajax

e. Callbacks

f. Event Handling

Among the above listed functionalities, selection, element manipulation and event handling makes common tasks very easily implementable or trivial.

a. Selection

Using this functionality one can select one or multiple HTML elements. The raw JavaScript equivalent of the selection functionality is

document.getElementByID(‘<element id>’) or

document.getElementByTagName(‘<tag name>’)

b. Attributes handling

One of most required task in JavaScript is to change the value of an attribute of a tag. The conventional way is to use getElementByID to get the element and then use index to get to the required attribute. jQuery eases it by using selection and attributes handling functionality in conjunction.

c. Element handling

There are scenarios where the values of tags need to be modified. One of such scenarios is rewriting text of a <p> tag based on selection from combo box. That is where element handling functionality of jQuery comes handy. Using the element handling or DOM scripting, as it is popularly known, one can not only access a tag but also perform manipulation such as appending child tags to multiple occurrences of a specific tag without using for loop.

d. Ajax

Ajax is of the concept and implementation that brought the usefulness of JavaScript to the fore. However, it also brought the complexities and the boilerplate code required for using Ajax to its full potential. The Ajax related functionalities of jQuery encapsulates away the boilerplate code and lets one concentrate on the result of the Ajax call. The main point to keep in mind is that encapsulation of the setup code does not mean that one cannot access the Ajax related events. jQuery takes care of that too and one can register to the Ajax events and handle them.

e. Callbacks

There are many scenarios in web development, where you want to initiate another task on the basis of completion of one task. An example of such a scenario involves animation. If you want to execute a task after completion of an animation, you will need callback function. The core of jQuery is implemented in such a way that most of the API supports callbacks.

f. Event handling

One of the main aspects of JavaScript and its relationship with HTML is the events triggered by the form elements can be handled using JavaScript. However, when multiple elements and multiple events come into picture, the code complexity becomes very hard to handle. The core of jQuery is geared towards handling the events in such a way that complexity can be maintained at manageable levels.

Now that we have discussed the main functionalities of jQuery, let us move onto the main modules of jQuery and how the functionalities map onto the functionalities.

2. Modules

The modules contain APIs that have one-to-one mapping with the functionalities (most of the time). The main modules of jQuery are

a. Selectors

b. Attributes/CSS

c. Manipulation

d. Ajax

e. Callback

f. Event Handling

The names are indicators as to which functionalities they map to. Here are the details

a. Selectors

As the name indicates, selectors provide the functionality to select elements.  As mentioned earlier, selectors are denoted by dollar ($) sign. Some of the commonly used selectors are

  • all selector – selects all the elements
  • :first and :last selectors – select the first and last occurrence of a recurring element/tag.
  • :eq (index) – selects the element with the index having the  value passed as argument.
  • #id – selects the element whose id is passed.

Following statements show how selectors are commonly used

$(“p”)

The above statement selects all <p> elements.

$(“p.start”)

It selects all <p> elements with class whose name is “start”.

$(“p#demo”)

It selects the first <p> element with “demo” as id.

b. Attributes/CSS:

The attribute handling functionality can be found in the API of this module. It also provides manipulation of CSS classes attached to the elements or attributes. Some of the most commonly used API is

·         .attr( attributeName ) – gets the value of an attribute for the first element having the attribute with name equal to the passed attribute name

  • .addClass (classname) – sets the CSS class of a particular element.
  • .val() – gets the current value of the first element in the set of matched elements. It is primarily used to get the values from form elements.
  • .css(name, value)  – sets the style property that matches the name of the style passed to the value passed for style

Following is an example of css() API

$(“p”).css(“background-color”,”yellow”);

It will set the style of all the <p> elements. In this case the style is background color. Its value is set to yellow.

c. Manipulation

The API related to DOM scripting can be found in this module. In other words, the API in this module is used to manipulate DOM in one way or other. One point to keep in mind is that many of the API in this module overlaps with API in Attributes/CSS module. Some of the most commonly used API is:

  • .after(content) – adds the specified content after each of the elements from a set of matched elements.
  • clone() – duplicates the elements in a set o matched elements.
  • replaceWith(newContent) – replaces each element from a set of matched elements with the specified content.

The term “set of matched elements” means that these APIs need to be used along with selectors. A selector may return more than one element. Hence, the returned values are collectively termed as set. For example, the following statement appends “This is appended” to all the <p> elements

$(“p”).append(“This is appended “);

And the following replaced all the values between <p> and <

d. Ajax

The Ajax related functionality can be found in this module. Following are the most commonly used APIs

  • get() – retrieve data from the server specified by the URL, with the data passed.
  • Post() – same as get but uses POST HTTP method to retrieve the data.

For example, the following statements depict the use of get() API

$.get(

http://mysite.org/test.php&#8221;,

function(data) { alert(data); },

);

In the above example, get takes two parameters – URL of the remote site and the callback that performs some operation on the data passed into the callback by get API. Here the URL is “http://mysite.org/test.php” and the operation performed is alerting the user.

e. Callbacks

One of the aspects of jQuery that is heavily used is callbacks. A callback is a function that is registered with another method and gets called when a specific condition, such as response from the server is fulfilled. Following statements display callback in its simplest form

$(“p#test”).hide(1000,function(){

alert(“The paragraph is now hidden”);

});

The hide() API takes two arguments, speed with which the element has to be hidden and the method that needs to be called when the task of hiding is done. In the above example, when the <p> element with id as test is hidden an alert is displayed. In this case callback function is directly defined within hide().

f. Event handling

As stated before, event handling is part of the core functionalities of jQuery. However, to use it, one point needs to be understood. It is the place (within the HTML document) where event and its handler will be attached. The answer to this question is the correct place is the section which gets called before body section is called and it is the head section.

To attach a handler with an event, the statements need to be place within the ready() function of document DOM element. For example, following statements attach the click event of button to its handler

$(document).ready(function(){

$(“button#test”).click(function(){

$(“p”).hide();

});

});

The click event button with id ‘test’ is attached to the handler using callback functionality which in turn is defined inside the callback for ready(). One point to keep in mind is that any kind event handling code must be defined inside ready() and read() itself must be a part of the head section (<head></head>).

This completes the bird’s eye view of the APIs of jQuery. Next section will deal with the steps in using jQuery and some its APIs. It will also cover how to use some of the APIs discussed in this section.

Developing with jQuery – Step-by-Step:

The steps to use jQuery  include downloading and installing (in some cases), referencing the jQuery library and calling the API. Following are the details

1. Downloading and installing jQuery

This step is not mandatory. The reason for this step being optional is that there are alternative ways to reference jQuery library which will be discussed as a part of next step. To download jQuery, one has to download it from the following URL

http://docs.jquery.com/Downloading_jQuery#Current_Release

Unzip it to the local folder from where it will be referenced. That completes the step for downloading and installing.

2. Referencing the Library

There are two ways to reference jQuery. They are

a. Local reference

c. Remote reference

Both use src attribute of //

a. Local reference

When the library (JS files of jQuery) resides within the application directory structure, then the files are locally referenced. Following statement references files stored in the scripts folder of the application

// <![CDATA[
src="../script/jquery-1.4.2.js">
// ]]>

</script>

b. Remote reference

When the library is hosted on another site ( e.g. code.google.com) and the URL is used to access the functionalities of the library, it is known as remote referencing. The steps to remotely refer jQuery hosted at code.google.com are as follows

i. Refer to the jQuery hosted on code.google.com using the src attribute of the //
statement does the same

// <![CDATA[
javascript"
// ]]>

src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”&gt;

</script>

The main point to remember is that the URL for the jQuery library may change based on the version of jQuery.

ii. Call the initialization function i.e. ready() after the referencing statement. The following example shows both the steps together

<script

src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”&gt;

</script>

<script>

$(document).ready(function() {

// provide the initialization such as event handling here

});

</script>

3. Calling the API

To call the API, one can use one of the following ways

a. Fully qualified name

When calling the API with fully qualified name, the statement starts with jQuery. The following statement calls the selector using fully qualified name

jQuery(‘:first’)

b. Using Dollar sign

The dollar sign ($) can be used to call the APIs, instead of using ‘jQuery’. The following statement uses dollar sign to call the selector instead of jQuery

$(‘:first’)

4. Putting it all Together:

Let’s put all the steps together.  The following example will implement  a simple time server. There are two files –one that sits at the server and the one executed at the client. They are

1. SimpleTimeServer.php – it will reside at the server and respond with the current server time.

2. Client.html – it will send request to the server for current server  time via Ajax and display the response it
receives.

First is the SimpleTimeServer.php.  It will have the following code

<?php

$time_now=mktime(date(‘h’)+5,date(‘i’)+30,date(‘s’));

$time_now_str = date(‘l M dS, Y, h:i:s A’,$time_now)

print $time_now_str;

?>

It uses the mktime function to get the current date time and the date function to convert it to human readable string.

Next is Client.html. Following is the code

xmlns=”http://www.w3.org/1999/xhtml&#8221; xml:lang=”en” lang=”en”>

<head>

<title>Current Date and Time</title>

<script src=”jquery-1.2.6.js”></script>

<script>

function  getTime()

{

$.ajax({

url : “SimpleTimeServer.php”,

success : function (data) {

$(“#contentArea”).html(data);

}

});

setTimeout(“getTime()”, 1000);

}

</script>

</head>

<body onload=”getTime();”>

<table width=”100%”>

<tr>

<td  width=”100%” align=”center”>

14px arial;padding-top:140px;”>

</div>

</td>

</tr>

</table>

</body>

</html>

The core of the client is the getTime function. It make call to the server using the get API and displays the received value using the manipulator html(). Then the function uses setTimeOut() to call itself at specified interval. The getTime() is called when the body section loads, thus once the body is loaded the time is displayed at a specific interval.

That completes the example. What I discussed here is just the tip of the ice-berg. In the next article, the selectors will be covered in details. Till then…

About these ads