Introducing jQuery

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


The above statement selects all <p> elements.


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


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


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


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 “” 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


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






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

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[
// ]]>


b. Remote reference

When the library is hosted on another site ( e.g. 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 are as follows

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

// <![CDATA[
// ]]>



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





$(document).ready(function() {

// provide the initialization such as event handling here



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


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


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

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



$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=”; xml:lang=”en” lang=”en”>


<title>Current Date and Time</title>

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


function  getTime()



url : “SimpleTimeServer.php”,

success : function (data) {




setTimeout(“getTime()”, 1000);




<body onload=”getTime();”>

<table width=”100%”>


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

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







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…


26 thoughts on “Introducing jQuery

  1. Pingback: Tweets that mention Introducing jQuery « Wanderer's Thougths --

  2. how are you!This was a really impressive topic!
    I come from endland, I was luck to discover your subject in bing
    Also I obtain much in your subject really thank your very much i will come every day

  3. I find myself coming back to your web-site only because you have lots of awesome insights and also you happen to be at this a while, which is very impressive and tells me you know your stuff.

  4. I must say that overall I am really impressed with this blog.It is easy to see that you are passionate about your writing. If only I had your writing ability I look forward to more updates and will be returning.

  5. I must say that overall I am really impressed with this blog.It is easy to see that you are passionate about your writing. If only I had your writing ability I look forward to more updates and will be returning.

  6. Thanks for taking time for sharing this article, it was nice and very useful to me. It?s my first time that I visit your blog. I found a lot of good stuff in your article. Keep it up. Thanks a lot

  7. hey, this power be scant offtopic, but i am hosting my locality on hostgator and they wishes suspend my hosting in 4days, so i would like to request you which hosting do you usability or recommend?

  8. you are in reality a just right webmaster. The web site loading velocity is incredible. It seems that you are doing any unique trick. In addition, The contents are masterpiece. you’ve done a wonderful process on this matter!

  9. This blog appears to get a large ammount of visitors. How do you get traffic to it? It gives a nice unique twist on things. I guess having something real or substantial to post about is the most important factor.

  10. Fantastic learn, I just handed this onto letter colleague who was carrying out many research on that. And he really purchased me lunch considering I discovered it for him smile Thus allow me rephrase that: Thanks for lunch! Anyway, in my language, there should really not very much effective source like this.

  11. Hey I am so excited I found your blog, I really found you by mistake, while I was browsing on Digg for something else, Anyways I am here now and would just like to say cheers for a incredible post and a all round exciting blog (I also love the theme/design), I don’t have time to look over it all at the minute but I have saved it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent job.

  12. Wonderful piece of writing. Thanks a lot for sharing the information. I was certainly not informed of your site, but will certainly come back a lot more often at this point. Including you to my own favorites.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s