Click here to Skip to main content
15,120,078 members
Articles / Programming Languages / Javascript
Posted 6 Oct 2011


161 bookmarked

Learning jQuery using jQuery Lab

Rate me:
Please Sign up or sign in to vote.
4.79/5 (46 votes)
20 Jun 2013CPOL25 min read
Explainign the theory of jQuery using live examples


jQuery is a javascript library that helps developer to write browser compatible and less javascript code. jQuery library is written completely in javascript only. The DOM is mess and its behavior is different in all n-number of browsers. Therefore, in order to create a common layer over the DOM that would handle all weird behaviors of the DOM in every browsers jQuery and other such libraries had evolved. One day will come when, nobody will write javascript code directly to do manipulation, traversal and any other behavior change of DOM. JavaScript will become the machine or library level language and people will use DOJO , Prototype, YUI or jQuery like librarie's utility methods to do DOM manipulation, traversal etc. Because, these libraries saves developer’s time, testing efforts, lines of code and improves their productivity and efficiency of development.



jQuery is a complex JavaScript object. We can say it as a wrapper over selected DOM elements with extended jQuery functionality. In jQuery commands, each command boils down to 2 things only select the DOM element and do some action on it. When we write jquery command by passing search expression then jQuery Sizzle Selector Engine searches for the given search expression. Selected elements present in the DOM got combined in an array and the same array would be wrapped under jQuery object and would be returned. Therefore, one can again utilize the jQuery functionality on the selected DOM elements. It's just like a chain of selected DOM elements getting returned after each execution of jquery command.

What problems are we going to solve?

In order to learn jQuery, one should first start with simple-simple jquery commands. But, the problem is where one should write, execute and see the results of the comomand. Therefore, I have created one Asp.Net Web Application by using this, one can execute JQuery commands, run them, see the results and can learn jQuery quickly.

I call it as jQuery Lab . This jQuery lab Idea, I brought from JQuery in Action book. I learned JQuery by reading this book thoroughly. I will highly recommend to read this book, it is very much helpful and it had nicely explained jquery concepts. Learning new languages by doing them in a practical way is really a fun and quicker way of learning.

jQuery Lab is a solution to our problem

jQuery Lab is a dot net web application that will allow you to execute jquery command and show you the results. It contains Dummy DOM on which one can run the jQuery Commands. It's source code can be downloaded from link: Download - 43.64 KB. After downloading this application one can run it by making Lab.aspx page as startup page. Below are the screenshots of the souce code and Lab.aspx page.

LearnJQueryByLab/project.PNG         LearnJQueryByLab/pic1.PNG

The jquery lab page comprises of below things:

  1. Sample DOM:
    DOM will have one Grid view and one DIV. Grid view contains few rows and Div will be empty. The DIV will have class named as empty . We will learn jquery by running sample queries on this sample DOM only. Below is the html of the sample DOM used in jQuery Lab.
         <div id="domWrapper">
        <asp:GridView ID="gvLab" runat="server" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
            BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="false">
                <asp:BoundField HeaderText="Name" DataField="Name" />
                <asp:BoundField HeaderText="Town" DataField="Town" />
                <asp:BoundField HeaderText="Age" DataField="Age" />
                <asp:BoundField HeaderText="Employee Id" DataField="Id" />
                <asp:BoundField HeaderText="Skills" DataField="Skills" />
            <RowStyle BackColor="#F7F7DE" />
            <FooterStyle BackColor="#CCCC99" />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <HeaderStyle CssClass="header" />
            <AlternatingRowStyle BackColor="White" />
     <div class="empty" id="emptydiv">
        Empty Container
  2. Text Editor:
    There is one text area in black background color, where one can write /paste the jquery command.
  3. Execute Button:
    After writing jquery code in the give text area, if user clicks on Execute button then it will execute the query. And the selected Elements would be highlighted with thick red border on the sample DOM shown left side of the page. The highlighting work on selected elements would be done by Lab internal code only in order to show your selected elements. So don't be confused that why selected elements are getting highlighted :)
  4. DOM Button:
    On Click of DOM button, it will show the selected elements HTMLs below the button only.
  5. Reset Button:
    On click of Reset button, it will reset the text area.

$ is the alias of jQuery object. After referring jquery file in the page by writing <script src="jquery-1.5.1.js" type="text/javascript"></script> jQuery object or $ becomes available globally. We will use alias name of jquery to learn / write jquery sample commands. In the argument of the $, we can pass search expression or new html to create elements.

jQuery Sample Commands and their explainations

Let’s learn JQuery from the beginning using jQuery Lab . Below are the jQuery sample commands. Inside the jquery lab project there is a

 file that contains all the sample codes that had been listed and discussed below in this article. I have used few css classes those can be found in lab.css file in the source code. Please read explaination and learn one by one by running below commands on jQuery Lab .

We shall start our learning from the basic jQuery selectors. In the below discussions, I will write the ask then will write the code for that ask and then will explain the same code.

Searching all tables


In the above query, we are passing element name 'table' as a search expression in the argument of $. Therefore, jquery will search for all the table elements present in the page DOM. Say in the DOM there are 3 tables then the above jquery command for searching table will return one wrapper object that will wrap an array of 3 selected table objects, jquery utility Methods, and few other required javascript objects. Please see the below screen shot for the same.


Searching all rows


This query will search all the TR elements present in the DOM and will return the array of tr objects. If you run the above code in jQuery Lab , then you will see all the rows would be highlighted with red border and the html of the selected rows are being displayed below the buttons in the DOM section.

Searching all cells


This query will search all the TD elements present in the DOM and will return the array of tr objects. If you run the above code in jQuery Lab , then you will see all the table cells would be highlighted with red border.

Searching by Class Name


.empty is the search expression that will look for all the elements having empty as a class name. jQuery will return a wrapper object contaning array of elements those are having empty as their class name.

Creating new DIV element


Using jQuery we can create the Element in the client side only at runtime. In the above code, we are creating div element and wrapping it on jquery object. Now this newly created div can be utilized / appended at anywhere.


In the DOM, the most difficult part is traversing. The word difficult indicates that one can travers to the elements, however the javascript code for traversing through elements are not same thorughout the browsers. If some code will work on mozila then the same may not work on IE. However, if we use jQuery then we have to write less code and we don't have to bother about the browser compatibility. jQuery will take care of that. jQuery code will run homogenously in all browser. Therefore, developer can concentrate more on functionality rather than writing 100 lines of code to handle the DOM traversal behaviour for multiple browser. Hence, jQuery is great and it makes a standard on writing code that runs on all browsers.



.children() is a command that fetches all the elements which are present inside the selected element. Suppose there is a table and when you say table.children() then it will fetch the elements inside the table that is nothing but tbody . As I said earlier that jquery command returns itself along with the selected wrapped set of DOM elements. Hence one can again call jquery commands to manipulate the selected DOM elements. Therefore, if you see "$('table').children().children()", in this command, we have written .children()command 2 times. First Time $('table').children(), the selected DOM is only table and we are finding its children. And on the second time "$('table').children().children()" the selected DOM is tbody because first children of table is tbody. Then we are again finding the children of tbody. Finally, the whole query will return entire rows inside the tbody.


$("table>tbody tr").add("td") ;

In this code we are using special character > it means that it will fetch all the immediate children of the selected element. $("table>tbody") will get the Tbody element. In our search expression, we have one space and tr that means inside the selected Tbody find all TRs.Therefore, $("table>tbody tr") will return all the trs of the tbody. We could have used .find method of jquery also to do that like $("table>tbody").find("tr"). After that we have used add command. It adds another set of wrapped DOM elements on top of the selected DOM elements. So in our command, first we have selected all TRs then we are adding all TDs on top of the selected trs.
add command is helpful in merging multiple sets of wrapped elements. For example, suppose if you want all links/anchors to be in green color and then you want links those are having href attribute should have bold font weight. There you can use add command. The code would be




In above query, we have used filter command. Filter command will return elements that is written on filter expression. So in this command it will return all the tds only.



Here we have used not command. Not command removes all the elements written in the not expression or you can say that it does not return the elements present in the search expression. In this above written query, it will only return tds.


$("table>tbody>tr").add("td") //all TDs are being returned
$("table>tbody>tr").add("td").end(); //all Trs are being returned.

Here we have used end command. In order to understand the end command, we have to first understand one important concept in jQuery that is

. In jquery after each command the selected DOM elements are placed in a stack so that whenever user wants to traverse back to the initial selected wrapped DOM set then user can go back and manipulate them again. Let’s understand stack with example in our code, we have first searched for TR then we added TD. Therefore, jquery will internally create a stack where first it will store wrapped set of TR then wrapped set of TD. When we say end then it will go back and fetch all TR from the stack and return you back. So end is just going one step backward.


Manipulation means, changing the DOM layout by injecting new DOM or by removing existing DOM or manipulating the size, offsets etc. As I already said, manipulation is difficult in DOM because of its different behavior in different sets of browsers. Therefore, one should learn jQuery manipulation commands to write standard code to manipulate DOM uniformly in all browsers. JQuery selects all the elements satisfying the search expression and then it applies the manipulation command in all selected elements in one-shot. Hence, we don’t have to loop each element and apply the command individually. This is very strong point of jQuery because, it reduces the lines of code. DOM manipulation causes DOM reflow that increases the rendering time of page. One can use jquery commands in an organized manner to avoid DOM reflows.



Here we have used empty command. It will remove all the rows from the table so there would be only table element with no rows.

Suppose you had below html before execution:

After execution of above command



remove command completely removes the selected elements from the DOM. It is very useful when we show some UI element at run time by injecting html elements in to DOM and after its use, we normally hide it but if we hide it then it will increase the page size. Therefore, instead of hiding, we should remove it completely from the DOM.

Before execution :

After execution:
//No Table element present. It was removed completely from DOM


$("<div>Appended in empty div</div>").appendTo(".empty");

appendTo command appends the selected element to the target html element i.e., (source)appendTo(target). In the above command we have created one DIV at runtime and appended it to the element having class name empty. After executing above query, a new div will be created and would be moved and appended to the existing DIV having .empty class name.

Before execution :

<div class="empty"></div>
After execution:
<div class="empty">
 <div>Appended in empty div</div>


$(".empty").append("<div>I have been appended dynamically</div>") 

append command appends the elements given in argument to the selected DOM element ie., (target)append(source). In above query in the argument of append, we have created and passed one new DIV. After executing above query, the new DIV would be appended in to the DIV containing class name empty.

Before execution :

<div class="empty"></div>
After execution:
<div class="empty">
 <div>Appended in empty div</div>


$(".empty").after($("<div>I am after the empty</div>")) 

after command appends the elements given in argument after the selected DOM element. In above query, we have created and passed one new DIV in the argument of after command. After executing above query, the new DIV would be appended after the the DIV containing class name empty.

Before execution:

<div class=""empty""></div>
After execution:
<div class=""empty""></div> 
<div>I am after the empty<div>


$(".empty").before($("<div>I am before the empty</div>")) 

before command appends the elements given in argument before the selected DOM element. In above query, we have created and passed one new DIV in the argument of before command. After executing above query, the new DIV would be appended before the the DIV containing class name empty.

Before execution:

<div class=""empty""></div>
After execution:
<div>I am after the empty<div>
<div class=""empty""></div> 


$("table").wrap("<fieldset>I am the Wrapper</fieldset>") 

wrap is a powerfull and useful method. It wraps the selected elements under the supplied html element. In above query, we are creating one new fieldset and wrapping table inside the fieldset. You can run this query in jQuery Lab to see wrap in action.

Before execution:

After execution:
<fieldset>I am the Wrapper


Along with the element name, id, class name etc selectors, jQuery alos supports css3 selectors It enables user to search elements using css3 search expressions. Let's learn few selectors query.

Selecting even rows (:even)

$("table>tbody>tr:even td") 

We can use few filter commands like :even , :odd. :even command will return the selected even wrapped set of elements. :odd command will return the selected odd wrapped set of elements. Above query ,will return all even rows including footer of the gridview.


$("table>tbody>tr:last td")

:last command will return the last selected wrapped set of elements. Above query ,will return all cells of last row that is footer.

Selecting Header (:first)

$("table>tbody>tr:first th")

:first command will return the first selected wrapped set of elements. Above query ,will return all cells of first row that is header.

Selecting Header & Footer (:last, :first)

$("table>tbody>tr:last td, :first th")

In Gridview, it is always required to manipulate header and footer with some background color or something else. We can use above command to select both header and footer. After selecting both of them we could apply background color or do whatever is needed. Our above, query will return header and footer cells.

Selecting even rows excluding header and footer

$("table>tbody>tr:not(:first,:last):even td") 

We have used :not along with :first, :last, :even . This command will return all even rows by filtering out header and footer rows.



:contains searches for the exact word and it is case sensitive. It returns the DOM element that contains the searched word. In the above query, it will return all the cells those contain "Rupesh" word.

$("#gvLab>tbody td:not(:contains('Rupesh'))") 

In the above query, it will return all the cells those don't contain "Rupesh" word.



We can search based on the type of the element. Like :button , :checkbox, :submit etc. The above command will return all the buttons present in the DOM.


We can also apply filter on element names in order to reduce the scope of search. In the above query we have written input so it will look for all input elements only having type as reset. Above query will return all the input elements having type as reset.

Searching with attributes


In Dot net web application, we face problem on selecting element using ID name because while rendering their id name got changed. Thats why, there we can use jquery attribute selector to get the element easily.

We can search the element by writing their attributes name and value. Say we want to find the elements having attribute ID with value starts with btn. Then we can write above given query for that and it will return all the elements those will have ID starts with "btn". Suppose if there are buttons having id = btnSet, id=btnSubmit, or id=btnReset then these all buttons would be wrapped and returned. We can also use other matching criterions like:

  1. [ID$=btn] here $= means ends with, It will retrun all the elements having id ending with "btn". ID name could be $l101Control_btnSubmit or $l102Control_btnSearch . If you want btnsubmit then you can write $("[ID$=btnSubmit]") .
  2. Similarly we can use other criterions like: == it means look for exact match.
  3. *= it means look for any match.

Attributes & CSS

In manipulation, sometimes it is required to change the attributes of the element or the CSS styles of the elements. That can also be done uniformly in all browsers by using jquery commands.

Changing CSS rules


For changing css style, we can pass the style key and value in the arguments of the CSS method. Above written query will select gridview having id gvLab and change its font size to 18px.

Chaning multiple CSS rules


If we want to create/update multiple css rules at one time then we can pass one object of css rule key and value to the argument of the CSS method. In our above query, we have created one object containing backgroundColor and color value. After executing this command the first row of the Grid that is header will change its background color to green and font color to orange.

Applying red color to all Even rows.


In our web application development, it is always required to change the color of alternative rows of the gridview. That can be achieved with one line of code in jquery. If we want all even rows to have background color as red then we can execute above query.

Chaning background color of Header and Footer


This query will Change the header and footer background color to red.

Changing all even rows except Header and Footer


Above query will change the even rows background color to red except for header and footer.


$("#gvLab td").addClass("blackTheme") 

addClass is a very useful command, it applies the class name to the selected element. In our above query, we are selecting all cells of gridview and applying a blackTheme class to them. If you run this query in jQuery Lab then you will see that grid will have black background color.


$("#gvLab td").removeClass("blackTheme") 

removeClass does the reverse action of addClass. It removes the given class name from the selected element. In our above query, we are removing blackTheme class from entire cells of the gridview having id gvLab.

Applying / Modifying Attributes (.attr)

$("#gvLab td:first").attr("title","My Name").css("cursor","hand") 
    $("#gvLab td:first").attr({"title":"My Name", "class":"MyClass"}); //passing object of attributes key and vlues.

We can change the attributes of the elements by using .attr command. In our above query, first we are selecting entire 1st cells then we are applying title attribute to them and then we are also applying one css rule. Similar to .css method in .attr method we can pass an object of having multiple attributes also.

Changing inner html (.html)


We can change the inner html of the element by using .html command. In our above written query, we are passing the class name of the gridview in the innerhtm. After executing above query, the DIV will show the class name of gridview.



hasClass is a method that checks the selected element for the given class name. If it finds the selected element having the suplied class name then it returns true else returns false. In this query, $("#gvLab").hasClass("blackTheme"), we are chcking if gridview has class having name blackTheme.


$(".empty").text( $("#gvLab").is(":hidden")) 

:hidden is a filter criteria to search, if it is hidden or not? If element is having style="display:none" then it returns true. Above query will show true or false based on the hidden status of gridview. You can run this query in jQuery Lab and see the result.

Binding Events

Fun with click and color

$("#gvLab>tbody>tr>td:nth-child(2)") //finding the 2nd column of the grid.
    .click(function(){ //binding click event
        $(this).css("backgroundColor","pink");  //applying backgroundcolor pink.
    .mouseleave(function(){ //binding mouseleave event
        $(this).css("backgroundColor","yellow"); //applying backgroundcolor yellow.
    .mouseenter(function(){ //binding mouseenter event
        $(this).css("backgroundColor","aqua"); //applying backgroundcolor aqua.

We can bind the events on the elements using jquery. There are many events that jquery supports. jQuery supports the standard names of event like click , mouseenter , mouseleave , change etc. In our above query we have used nth-child(), this is the searching criteria based on 1 index. It fetches the child positioned at the given index number, index starts with 1. Here first, we found the 2 column $("#gvLab>tbody>tr>td:nth-child(2)") and then we are binding click event on all the cells in 2nd column position. In the click event, we are assigning the background color to pink. Similarly we have binded mouseleave and mouseenter events. If you execute this query in jQuery Lab then you will see, if you hover on the cell, it will become aqua color, on click of cell it will become pink color and once you leave out of the cell it will become yellow color.

Let’s show custom tooltip

//Search cells that contians "Rupesh"
    .css('cursor','pointer') //apply css with cursor as pointer 
    .click( function(event) { //binding click event on selected cell
        $("<div>") //creating new div element on click event.
        .css({ //assigning few styles to the new DIV 
       .html($(this).text()) //on the new DIV, we are putting the text of the cell.
       .click(function(){ //binding click event on newly created DIV element.
            $(this).hide() //here this is the newly created DIV. We are hiding the div itself on click of it. 
        .appendTo("body") //Finally, we are appending this div in the body to show in the UI.

In our above query, on click of the 2nd cell of the gridview, we are creating new div at runtime and then we are showing it as a tooltip box. This is just an idea, one can work on it and create some more fancy tooltips.


jQuery provides various effects and animations. Many front-end developer learn jquery because of effects and animations that it provides. These commands are very easy to understand and impliment.



hide will hide the selected element



toggle is a method that changes the style=display property of the selected element based on its initial value. If display value is already hidden then toggle command makes it's value to displayed and vice versa. We can pass "slow" ,"normal" and "fast" these are the values of the speed of animation.



fadeTo is a method that fades the element to extend of given number. Here in our above query, we are passing 0.5.



fadeOut is a method that hides the selected element.



fadeIn is a method that displays the selected element.



slideUp is a method that hides the selected element. While hiding the element, it starts hiding it from the bottom. It will look like shutter up.



slideDown is a method that displays the selected element. While displaying the element, it starts fading in from the top. It will look like shutter down.



slideToggle is a method that remembers the initial style of the selected element. If initially it is hidden then it makes it visible and vice versa with sliding effects.


$("td:first")//selecting first td.
.css({//adding css rules to selected td element
    top: $("td:first").offset().top,
    left: $("td:first").offset().left
.animate(//calling animate method
        {top:0,left:0}//final position of the animated element.
        ,4000 //total time for animation
        ,'linear' //easing of animation.
        ,function(){ //callback method after animation done

In jQuery, we can animate element by using animate method. The first argument of the method is the final poistion towards that element will move, 2nd argument is the total duration for animation, 3rd argument is the way or easing of animation it can be "linear" or "swing" swing is the default easing. 4th argument is the callback method that would be called automatically after the completion of the animation. In our above query, we are animating very first cell of the gridview and moving it to the top left corner of the screen. Please run it in jQuery Lab and see the fun.

Ajax using jQuery

Making Ajax calls is very simple and easy using jquery utility methods.


$('.empty').load(//calling  load method on the div having empty class name.
    'default.aspx' //loading this page.
    ,{} // passing empty javascript object to the server.
    ,function(){ //callback method that would be executed automatically after the successful load of page.
        alert("data.htm page is loaded successfully")

In jQuery, we have load method, this method loads the page in the selected element asynchronously. In the first argument, we pass the page name that we want to load, 2nd argument is the data that we pass to the page it can be any javascript object, 3rd argument is the callback method that gets called after the successfully completion of the load of the page. If there would be any error while fetching / loading the given page then the callback method would not be fired.

$('.empty').load('default.aspx li:first',{},function(){alert("data.htm page is loaded successfully")}) 

While loading the page in the selected element. We can filter the DOM elements that we want to fetch out of the page. In our above 2nd query, see we have put the search expression in the page name itself 'default.aspx li:first. This will get the default.aspx page then search for the first list item li:first and fetch it only. Therefore, in the empty container DIV, we will load only the first list item of the default page.

This filtering while before fetching way is cool and it saves lots of bandwidth, if you want only one element from the page then you should fetch only that instead of fetching it completely and then filtering them out. Similarly there are few more ajax utility methods like $.get makes get call, $.getJSON gets the json object passed from the server and etc.

Advance Ajax

All the ajax utility methods of jquery internally makes $.ajax method call. If you use $.get method then it will call the same ajax method using type:get. Therefore, the main /common ajax method of jquery is $.ajax. If we want more control on ajax call and want to utilize the adavance features of the ajax calls then we should use $.ajax method only.

Loading default page using get command

$.ajax({ //making ajax call, it is same as $.get method call
    url:"default.aspx", //url to fetch
    success:function(data){ //success calback method
    type:"get" //passing type as get.

In our above query, we are are loading the default.aspx page using $.ajax method and by passing type:get. We have used the Success event, this is the event that would be triggered automatically on the successfull completion of the ajax call. Here on successfully load of the page we are calling alert method to show the page data.

Loading default page and used complete and beforeSend events.

    url : "default.aspx" //url of the page to fetch
    ,success : function(data) { //callback method called on successful load.
    ,type : "get" //making get call.
    ,complete : function( ) { //creating event handler for complete event.
        $(".load").remove();//removing the dynamic div after completion of the ajax call. 
    ,beforeSend : function( ) {
        $("body").append($("<div class="load">Loading</div>")) //creating 

In the above query, we have used below events of ajax method

  1. beforeSend, this is the event that would be triggered automatically before making ajax call. In this callback method, we are creating one dynamic div with message loading and showing it. It is just like showing progress bar while fetching data from server.
  2. complete, this is the event that would be triggered automatically on the completion of the ajax call. In this callback method, we are removing the dynamically created loading div.

Calling WebService using jQuery ajax

using $.ajax method, we can call Webservice webmethods , WCF methods or static method of .aspx page . Let's see one example of calling webservice method using jquery ajax method.

    type:"POST" //type is post because, we are sending few data from client side.
    ,dataType:"json" //datatype says that the response type from the server. 
    ,contentType: "application/json; charset=utf-8" //contenttype is the formate of communication protocol, it could be html or json.
    ,url:"mySvc.asmx/getEmpByName('Rupesh')" //method name with svc name and parameter to be passed.
    ,success:function(data){ //callback method on suceess.
    ,error:function(data){ //callback method on error.
    ,beforeSend:function ( ) { //callback method on before making ajax call
    ,complete:function(){ //callback method on completion of the ajax call.

In above query, we are calling getEmpByName method of the webservice mySvc.asmx. While calling webservice one should take care of few things like passing default data as a string"{}", and passing contentType: "application/json; charset=utf-8" in $.ajax method. I will recommend to read Dave's article .


If you want to make jquery more useful and extend it's functionalities by introducing your own custom methods then you can create the plugin that will have your own methods and once you load these plugins with jquery file then jquery will get those methods in itself. Say, you want to create your own method $.myPlugin() this method does not exists in jQuery. For adding it into jquery object you have to create your own plugin. See below code:

My first plugin

//creating plugin.
        function(){ //creating anonymous method and passing it in the argument of $.
            $.fn.myPlugin = function(){ //adding on method myPlugin into prototype of jquery object.
                return $(this).each(function(){ //returning the selected elements to continue the chain.
                    $(this).css('background-color','green'); //chaing background color to green
    //calling our own method on odd rows of gridview.

While writing plugin, one should concentrate on below things:

  1. Write your plugin method inside the ready event of the DOM . The ready event is triggered by jquery when the DOM is created and ready to parse. This is the correct stage to bind events on html elements or adding custom methods to jquery object. Ready event can be hooked up by writing code inside the anonymous method and passing it into argument of $() method.
        // write line of codes for getting executed on the ready event of the DOM
        //$('button').click(function ( ){ }); //binding events to elements.
        //...write plugin related code.
    Therefore, you can see in our above query, we have started writing our plugin related code inside the anonymous method only.
  2. Append your plugin's methods in the prototype of jquery object. $.fn is the alias for the prototype of the jquery object. In our above example, we have added our new method myPlugin in the prototype object of jquery.
  3. Use $.each helper method . In the plugin method, we should use the each method to the selected elements so that it will iterate through each and individual selected element and apply the changes on that.
  4. Return the selected wrapped set of elements, after writing plugin method on the the selected wrapped set of elements, we should return it so that the chain will continue and one can again apply the required jquery command on the selected wrapped set of element again.
In the above query, our custom plugin method myPlugin makes the selected DOM elements background color to green. Please run this plugin in jQuery Lab and see the action.


Online Tutorials

I would recommend to read online tutorials like Visual jQuery, jQuery . Along with that strong recommendation to read jQuery in Action Book .

Video Session on jQuery using jQuery Lab

I have taken one session on JQuery using <a href="#l">jQuery Lab </a> . In that session, I have explained jquery by running above listed jQuery sample codes on the jquery lab. Hence, while watching video one can copy the sample code from this article or get it from sample.js file and run it in jQuery Lab .

The video sessions are in two parts JQuery Part 1 and JQuery Part 2. I hope these videos will help you to learn jquery more better.

This is the copy of the presentation slides that I have used in my video talk.

<object type="application/x-shockwave-flash" codebase=",0,0,0" width="425" height="355" data=""><param name="movie" value="" /><param name="quality" value="high" /><param name="wmode" value="transparent" />


I have tried to explain the basics of jquery in this article. Now jquery has released there 1.6.4 version. Whatever, I have discussed in this article those will be applicable in all versions of jQuery. Because, I have discussed the basics of jquery that is same across the all versions. However, in latest version of jquery, they have intruduced some more shortcuts to create elements, increased the speed of append method and several other methods executions, converted few expressions in to methods and did many more good works. One can read them and get updated. Any suggestions , questions or feedbacks are welcome!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Rupesh Kumar Tiwari
Software Developer (Senior)
United States United States

I am a Senior Software Developer working since 2005 in Microsoft ASP.Net and related Technologies.

I work on C#, Asp.Net, MVC, RAZOR, Entity Framework, JavaScript, jQuery, HTML5, CSS3, WCF, Silverlight, WPF, MVVM, SQL, SSIS, etc. Did Function Point Analysis, WBS to estimate projects and worked on Agile Scrum team.

I enjoy on exploring new technologies by implementing and writing about them, great interest in learning Design Patterns and their implementations. I love learning, writing JavaScript; now my favorite JavaScript library is jQuery. I enjoy writing jQuery Plugins and core JavaScript. I also write Technical blogs here. You can find me on LinkedIn.

I wrote an article on Swami Vivekananda posted his audio speeches by reading them.

Comments and Discussions

QuestionI DID read the article first... Pin
blackbr18-Aug-14 8:42
Memberblackbr18-Aug-14 8:42 
QuestionI can't seem to get started Pin
blackbr16-Aug-14 12:04
Memberblackbr16-Aug-14 12:04 
AnswerRe: I can't seem to get started Pin
Rupesh Kumar Tiwari16-Aug-14 16:49
MemberRupesh Kumar Tiwari16-Aug-14 16:49 
Questionminor change Pin
SachinThunder8-Jul-14 15:11
MemberSachinThunder8-Jul-14 15:11 
GeneralAwesome article.. Thanks Rupesh! Pin
Shalu34519-Feb-14 7:33
MemberShalu34519-Feb-14 7:33 
Question[My vote of 1] English Pin
msdevtech18-Nov-13 16:21
Membermsdevtech18-Nov-13 16:21 
Questionthank you Pin
aqie1311-Sep-13 0:04
Memberaqie1311-Sep-13 0:04 
GeneralMy vote of 5 Pin
Member 85284093-Jul-13 5:30
MemberMember 85284093-Jul-13 5:30 
GeneralRe: My vote of 5 Pin
Rupesh Kumar Tiwari3-Jul-13 6:37
MemberRupesh Kumar Tiwari3-Jul-13 6:37 
GeneralRe: My vote of 5 Pin
Member 85284093-Jul-13 9:42
MemberMember 85284093-Jul-13 9:42 
GeneralMy vote of 5 Pin
Brian A Stephens27-Jun-13 7:56
professionalBrian A Stephens27-Jun-13 7:56 
GeneralGreat tutorial. Pin
k@ran30-Apr-13 9:06
Memberk@ran30-Apr-13 9:06 
GeneralMy vote of 5 Pin
csharpbd23-Apr-13 21:27
professionalcsharpbd23-Apr-13 21:27 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun22-Apr-13 22:11
MemberHumayun Kabir Mamun22-Apr-13 22:11 
QuestionVery helpful if in IE only Pin
ryanoc33322-Apr-13 4:20
Memberryanoc33322-Apr-13 4:20 
GeneralMy vote of 5 Pin
Prasad Khandekar21-Apr-13 8:59
professionalPrasad Khandekar21-Apr-13 8:59 
GeneralMy vote of 5 Pin
prem parihar21-Nov-12 8:43
Memberprem parihar21-Nov-12 8:43 
Questionthe source code is not found Pin
zsanhong14-Jul-12 15:49
Memberzsanhong14-Jul-12 15:49 
QuestionRe: the source code is not found Pin
GreatOak9-Nov-12 4:17
professionalGreatOak9-Nov-12 4:17 
GeneralMy vote of 5 Pin
Abinash Bishoyi19-Jun-12 12:24
MemberAbinash Bishoyi19-Jun-12 12:24 
GeneralMy vote of 5 Pin
Md. Marufuzzaman14-Nov-11 4:48
professionalMd. Marufuzzaman14-Nov-11 4:48 
GeneralMy vote of 4 Pin
nrutter12-Oct-11 0:26
Membernrutter12-Oct-11 0:26 
GeneralRe: My vote of 4 Pin
Member 85284092-Jul-13 10:32
MemberMember 85284092-Jul-13 10:32 
GeneralMy vote of 5 Pin
Jepy11-Oct-11 23:37
MemberJepy11-Oct-11 23:37 
GeneralMy vote of 5 Pin
KenBonny11-Oct-11 23:18
MemberKenBonny11-Oct-11 23:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.