jQuery Overview

In this tutorial I will discuss jQuery and some important exciting features in jQuery. If you've used event handling, animation functions and DOM Manipulation or are interested in implementing one, you should be serious about jQuery. These features will lead to projects with a shorter time, faster performance and smaller size and so on. In this article we will discuss the jQuery basics and as the article progresses, we will focus on jQuery features and selectors.

In the tutorial we will talk about the following points:

  1. What is jQuery?
  2. Why use jQuery?
  3. Who uses jQuery?
  4. Downloading jQuery
  5. jQuery File Structure in in ASP.NET
  6. jQuery Important Features
    • HTML/DOM Manipulation
    • Event handling
    • AJAX Support
    • Animations in jQuery
    • Lightweight
    • Cross Browser Support
  7. jQuery $ sign
  8. jQuery $(document).ready() Function
  9. jQuery Selectors
1. What is jQuery?

jQuery is a JavaScript library that emphasizes interaction between JavaScript and HTML. It was created by John Resig in 2006. jQuery has many new features, like small size, many plugins, built-in function and cross-browser support.

2. Why use jQuery?

In JavaScript we write more code because it doesn't have more functions like animation effects functions and event handling. So if you use JavaScript, developers write more code and they often feel embrace when they execute the code on the browser and get a problem related to cross-browser support. To solve these types of problems, John has created a JavaScript library with the nice motto, write less and do more in 2006; that is called jQuery. So you can use all the functions and other capabilities available in JavaScript. It saves developer's time, testing efforts, lines of code and improves their productivity and efficiency of development. The following are some important points to use jQuery.

  • Fully documented
  • Lot of plugins
  • Small size
  • Everything works in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

We will also learn some great features of jQuery later in the article.

3. Who use jQuery?

Today jQuery is the most popular tool in the software development field. Many developers agree that jQuery is awesome. There are many small and big companies that use jQuery, like Microsoft, Google, Mozilla, IBM, Amazon, HP and Intel.

4. Download jQuery

To get your application running quickly with jQuery, let us start by downloading jQuery. You can download the jQuery file from here.

5. jQuery File Structure in ASP.NET

After downloading Bootstrap from the preceding link, you will see a Zip folder. Once unzipped, you will find that there are several files and folders available within the root folder. Visual Studio 2010 and 2012 includes jQuery by default and provides intellisense to use jQuery.

Now you can see the Scripts folder; expand it and it will look such as in the following:

jQuery File Structure

 The Scripts folder contains a set of three files as in the following:

js file

Now let's see the differences among these files.

vsdoc.js File

This file has been commented to support Visual Studio Intellisense. You should not use this file at runtime inside the browser. It is only intended to be used only for design-time IntelliSense.

min.js File

The .min version has been minified. The normal min.js file is not readable. It is smaller in size than the js file. So the .min version is useful for code.

js File

There is no difference between the min and js files. Your browser's JavaScript engine won't notice the difference. The js file is larger than the min. The normal .js file is for debugging, because as you say, it's more readable.

You can see the file size differences between them and also check the speed in a browser.

file size

Include with HTML

Next up is to include them into the project. So let's imagine we have a blank HTML file that goes something like this:

HTML file

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  
  2. <html>  
  3.    <head>  
  4.         <title></title>  
  5.    </head>  
  6.   <body>  
  7.   </body>  
  8. </html> 

Now we need to add a reference to the JS file with the HTML file as in the following:

  1.  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  
  2. <html>  
  3.      <head>  
  4.            <title></title>  
  5.         <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  6.                </head>  
  7.       <body>             
  8.      </body>  
  9. </html> 

6. jQuery Important Features

jQuery has some important feature such as event handling, Ajax support and animation effects functions. Here is the list of important features supported by jQuery.

  1. HTML/DOM Manipulation

    JavaScript doesn't have any features related to the DOM, but JavaScript in the browser does include some intelligence about the DOM.

    Example

    GetElementById() function

    DOM is the important feature of jQuery. It defines the logical structure of documents and the way a document is accessed and manipulated. jQuery has the extra intelligence regarding the DOM. With it, you access and create DOM elements (tags) by using the many selectors and traversing operations it offers. jQuery can read and manipulate the DOM of your HTML page using a set of simple methods. These methods are: Text(), html(), Append(). The DOM is separated into 2 different parts:
     
    • XML DOM: Standard model for XML documents
    • HTML DOM: The HTML DOM defines the objects and properties of all HTML elements.

      Example
      1. <table id="TableID" cellpadding="0" cellspacing="0" border="1"  width="400px" >  
      2.       <tr>  
      3.            <td style="background-color: green; color:white">Name</td>  
      4.            <td style="background-color: green; color:white">LastName</td>  
      5.            <td style="background-color: green; color:white">Email</td>  
      6.      </tr>  
      7. </table> 

      Now using the append method to add another row and column to the table.

      1. $('#TableID > tr:last').append($('<tr><td>Phone Number</td></tr>')); 
  2. Event handling

    jQuery
    introduced a feature called Event handling. Before starting event handling you need to understand event. Events are actions. This means that you can write code that runs when a user clicks on a certain part of the page, or when she moves her mouse over a form element. jQuery contains many events, such as a user clicking on a button, moving a mouse over an element and so on. When an event is fired you can show the custom result or you can use a custom function and much more, whatever you want with the event called EventHandler.

    Binding event handlers

    The binding of event handlers are the most confusing part of jQuery for many developers when working on jQuery projects. Many of them are unsure of which is better to use.

    Bind() Method

    The bind method will only bind event handlers for the currently existing items. That means this works for the current element.

    Example

     

    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication137.WebForm1" %>        
    2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
    3. <html xmlns="http://www.w3.org/1999/xhtml">   
    4. <head runat="server">   
    5.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>   
    6.     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>   
    7.     <title></title>   
    8.     <script type="text/javascript">   
    9.         $(document).ready(function () {             
    10.             $('P').bind('click', function () {   
    11.                 alert("Example of Bind Method");   
    12.                 e.preventDefault();   
    13.             });                      
    14.         });   
    15.     </script>  
    16. </head>   
    17. <body>   
    18.     <form id="form1" runat="server">   
    19.     <P>Test for bind and live</>        
    20.     </form>   
    21. </body>   
    22. </html> 

    Now Press F5 to execute it.

    JQuery-bind-method

    Now you add a paragraph tag with body. The following shows the added paragraph tag code.

    1. $('body').append('<p>Adding Future items</p>') 

    Now the code looks like the following code:

    1. <script type="text/javascript">  
    2.         $(document).ready(function () {             
    3.             $('P').bind('click', function () {  
    4.                 alert("Example of live method");  
    5.                 e.preventDefault();  
    6.             });  
    7.           $('body').append('<p>Adding Future items</p>');  
    8.              
    9.         });  
    10.     </script>  
    11. </head>  
    12. <body>  
    13.     <form id="form1" runat="server">  
    14.     <P>Test for bind and live</>        
    15.     </form>  
    16. </body> 

    Now press F5 to execute it.

    JQuery-bind-method-with future-items
    When you click on the Adding Future items text, it will not show a message; that means it will not work for future items. That means this works for new and old elements. Or Live() adds events to the selector you pass in (which you haven't here) and continues to look at the DOM as nodes are inserted / removed.

    The preceding method will work fine with currently existing items. It will not work with future items. To solve this problem you can use the Live method.

    Live() Method

    The bind method can bind event handlers for currently existing items or future items.

    Example

    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication137.WebForm1" %>  
    2.    
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    4. <html xmlns="http://www.w3.org/1999/xhtml">  
    5. <head runat="server">  
    6.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
    7.     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>  
    8.     <title></title>  
    9.     <script type="text/javascript">  
    10.         $(document).ready(function () {             
    11.             $('P').live('click', function () {  
    12.                 alert("Example of live method");  
    13.                 e.preventDefault();  
    14.             });  
    15.             $('body').append('<p>Adding Future items</p>');              
    16.         });  
    17.     </script>  
    18. </head>  
    19. <body>  
    20.     <form id="form1" runat="server">  
    21.     <P>Test for bind and live</>        
    22.     </form>  
    23. </body>  
    24. </html> 

    Now press F5 to execute it and click on the "Adding Future items".

    JQuery-Live-method
     

  3. AJAX Support

    We often see in a project that we do not want to reload the page. For example when you select an item from a DropDownList or other control on the same page then that can cause a loss of data. Ajax is used to update the part of the web page without reloading the page. For example, if you create a search functionality in your website like Google Searching. When you enter text into the Search TextBox then without reloading the page you see the related text. You can do it easily using Ajax Methods.

    Other examples of applications using AJAX are Gmail, YouTube and Facebook tabs.

    jQuery with Ajax

    All jQuery AJAX methods use the ajax() method. The ajax() method performs an AJAX (Asynchronous HTTP) request.

    Syntax

    $.ajax({ Parameter1, parameter2..........})

    or
     
    $.ajax({
    type: ,
    contentType: ,
    url:, data:,   
    async:,......
    });

    The following is the description of some important parameters used by the "$.ajax" method:

    • Type: The default value of type is GET. A string defining the HTTP method to use for the request (GET or POST).
    • GET: Requests data from a specified resource
    • POST: Submits data to be processed to a specified resource
    • ContentType: When sending data to the server, use this content type. The default is "application/x-www-form-urlencoded"
    • URL: A string containing the URL to which the request is sent. The default is the current page.
    • Data: Data defines the data to be sent to the server.
    • async: The default is true. A Boolean value indicating whether the request should be handled asynchronously or not.
    • Success: A callback function that is executed if the request succeeds.

    Now, let's see how to do that.

    Example 1

    My database table:
    1. CREATE TABLE [dbo].[Slider_Table](  
    2.       [Id] [int] IDENTITY(1,1) NOT NULL,  
    3.       [Title] [varchar](100) NULL,  
    4.       [Description] [varchar](200) NULL,  
    5.       [ImageName] [varchar](100) NULL,  
    6.       [IsActive] [bitNULL,  
    7.  CONSTRAINT [PK_Slider_Table] PRIMARY KEY CLUSTERED   
    8.  (  
    9.       [Id] ASC  
    10. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
    11. ON [PRIMARY
    My table structure looks like:

    Table
     
    Stored Procedure for insert and Update

    You now need to create a Stored Procedure in a SQL Server database for inserting records into the table. Later in the article we use it to update records in the database table.
    1. Create procedure [dbo].[SliderInsertImage1]  
    2. (  
    3. @Id int,  
    4. @Title varchar(100),  
    5. @Description varchar(200),  
    6. @ImageName varchar(100),  
    7. @IsActive bit  
    8. )  
    9. AS  
    10. begin  
    11. insert into Slider_Table values(@Title, @Description, @ImageName, @IsActive)  
    12. end 
    The back-end database work is now done. Now again move to the front-end to make a connection with the database. We store only the name of the image in the database table, the column called ImageName.

    Now, add the following code to the .cs file.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.UI;  
    6. using System.Web.UI.WebControls;  
    7. using System.Web.Services;  
    8. using System.IO;  
    9. using System.Data;  
    10. using System.Data.SqlClient;  
    11.    
    12. public partial class Insert : System.Web.UI.Page  
    13. {  
    14.     protected void Page_Load(object sender, EventArgs e)  
    15.     {  
    16.     }   
    17.     [WebMethod]  
    18.     public static void InsertMethod(string title, string description, string image_name, bool is_active)  
    19.     {                 
    20.         int ID=0;  
    21.         SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");  
    22.         con.Open();  
    23.         SqlCommand cmd = new SqlCommand("SliderInsertImage1", con);  
    24.         cmd.CommandType = CommandType.StoredProcedure;  
    25.         cmd.Parameters.AddWithValue("@Id", ID);  
    26.         cmd.Parameters.AddWithValue("@Title", title);  
    27.         cmd.Parameters.AddWithValue("@Description", description);  
    28.         cmd.Parameters.AddWithValue("@ImageName", image_name);  
    29.         cmd.Parameters.AddWithValue("@IsActive", is_active);         
    30.         cmd.ExecuteNonQuery();                
    31.         con.Close();          
    32.     }     

    So you can drag and drop controls onto the form. The form has the following code:
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Insert.aspx.cs" Inherits="Insert" %>  
    2.    
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    4. <html xmlns="http://www.w3.org/1999/xhtml">  
    5. <head runat="server">  
    6.     <title></title>  
    7.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
    8.     <style type="text/css">  
    9.         .style1  
    10.         {  
    11.             color: #FFFFFF;  
    12.         }  
    13.     </style>  
    14.     <script type="text/javascript">  
    15.         $(document).ready(function () {  
    16.             $('#Button1').click(function () {  
    17.                 debugger;  
    18.                 var Title = $('#TextBox1').val();  
    19.                 var Description = $('#TextBox2').val();  
    20.                 var UploadImage = $('#FileUpload1').val();  
    21.                 var Isactive = $('#CheckBox1').attr('checked');  
    22.                 $.ajax({  
    23.                     type: 'POST',  
    24.                     contentType: "application/json; charset=utf-8",  
    25.                     url: '<%=ResolveUrl("~/Insert.aspx/InsertMethod") %>',  
    26.                     data: JSON.stringify({title: Title, description: Description, image_name: UploadImage, is_active: Isactive }),  
    27.                     success: function (response) {  
    28.                     alert("Record Has been Saved in Database. Status code: " + response);  
    29.                     }  
    30.                 });  
    31.             });  
    32.         });          
    33.     </script>  
    34. </head>  
    35. <body style="color: #FF66FF; background-color: #99FFCC">  
    36.     <form id="form1" runat="server">  
    37.     <div style="color: #FF33CC; background-color: #00CCFF">  
    38.                         
    39.         <span class="style1">Title: </span>  
    40.         <asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>  
    41.         <br class="style1" />  
    42.         <br class="style1" />  
    43.         <span class="style1">   Description: </span>  
    44.         <asp:TextBox ID="TextBox2" runat="server" ClientIDMode="Static"></asp:TextBox>  
    45.         <br class="style1" />  
    46.         <br class="style1" />  
    47.         <span class="style1">Upload Image: </span>  
    48.         <asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />  
    49.         <br class="style1" />  
    50.         <br class="style1" />  
    51.         <span class="style1">IsActive: </span>  
    52.         <asp:CheckBox ID="CheckBox1" runat="server" Style="color: #FFFFFF" ClientIDMode="Static" />  
    53.         <br class="style1" />  
    54.         <br />  
    55.         <input id="Button1" type="button" value="Submit" />  
    56.         <asp:Label ID="Label1" runat="server" Text="Label" Style="color: #FFFFFF"></asp:Label>  
    57.     </div>      
    58.     </form>  
    59. </body>  
    60. </html>  
    61. <style> 
    Now execute the application and test it.

    run the application

    Now enter the title, description, Imagename and ischecked.

    Fill the form

    Now check it in the database table.

    Database Table

    Similarly, you can upload more images onto the server and save the name in the database table.
     
  4. Animations in jQuery

    The jQuery comes with plenty of built-in animation effects that you can use in your websites. For example: animation, show, hide and so on. In jQuery the animate() method is very useful. By using this method we can change the size of elements.
     
    • Animation method
    • Show method
    • Hide method

    Now for an example of an animation method.

    In this example we create a div element that contains an image. When we move the mouse over the image, the image size will change. First of all you add an image to the application. Add a new form to the application and add the following HTML code to the aspx page.

    1. <div style="height: 100px; width: 100px; position: relative">  
    2.         <img src="animate.gif" id="img" />  
    3.     </div> 

    Now add the following code to the head section.

    1. <script type="text/javascript">  
    2.         $(document).ready(function () {    
    3.             $("div").mouseover(function ()//mouseover function will execute when mouse pointer will reach on <div>element  
    4.             {  
    5.                $("img").animate({ height: 300 }, "slow"); //image height will change by using animate method  
    6.                $("img").animate({ width: 300 }, "slow");  
    7.                $("img").animate({ height: 100 }, "slow");  
    8.                 $("img").animate({ width: 100 }, "slow");  
    9.             });  
    10.         }  
    11.    );  
    12.   </script> 

    In the code above we created a mouseover function.

    1. $("img").animate({ height: 300 }, "slow"); //image height will change by using animate method  
    2. $("img").animate({ width: 300 }, "slow");  
    3. $("img").animate({ height: 100 }, "slow");  
    4. $("img").animate({ width: 100 }, "slow"); 

    This code defines how to change the image height using the animate method.

    Now execute the application.

    animation

    The image height and width will change when the mouse pointer is over the image as shown below.

    Hide method in jQuery 

    In jQuery the Hide () method is very useful. By using this method you can hide HTML elements with the hide().

    Example

    We are showing you the code for the .aspx page below:

    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    2. <html xmlns="http://www.w3.org/1999/xhtml">  
    3. <head>  
    4.     <title>here</title>  
    5.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
    6.     <script type="text/javascript">  
    7.         $(document).ready(function () {  
    8.             $("button").click(function () {  
    9.                 $("#div1").hide();  
    10.             });  
    11.         });  
    12.     </script>  
    13. </head>  
    14. <body>  
    15.     <h2>  
    16.         This is a heading</h2>  
    17.     <div id="div1">  
    18.          jQuery is great library for developing ajax based application.  
    19.         <br>  
    20.         jQuery is great library for the JavaScript programmers, which simplifies the development  
    21.         of web 2.0 applications.<br />  
    22.         <br />  
    23.         <br />  
    24.     </div>  
    25.     <button>  
    26.         Hide</button>  
    27. </body>  
    28. <html> 

    Now execute the application and see the Text.

    Animation1

    Now click on the Button (hide) to hide the contents.

  5. Lightweight

    jQuery is a very lightweight library, about 19KB in size (minified and gzipped). The filesize is small when gzipped, it also concentrates on only having useful features, so it doesn't include things like a lightbox plugin or a way to create tabs, it just offers basic building blocks to build complex things. UI features (that many developers don't need) are moved to a separate plugin, as are templates, advanced animations and effects, and so on. This helps to keep the framework lightweight.
     
  6. Cross Browser Support

    jQuery is constantly tested with all of its supported browsers via unit tests. jQuery has cross-browser support and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+.

7. Using jQuery $ sign

By default, jQuery uses $ as a shortcut for jQuery. If you use jQuery instead of the $ sign then it will work the same.

So, using $("#id") or jQuery("#id") is the same.

8. jQuery $(document).ready() Function

Whenever you use jQuery to manipulate your web page, you wait until the document ready event has fired. The document ready event signals that the DOM of the page is now ready, so you can manipulate it without worrying that parts of the DOM has not yet been created.

The document ready event in jQuery looks like this:

  1. $(document).ready(function() {  
  2.    // Write your jQuery code here  
  3. }); 

9. jQuery Some important Selectors

Selectors are the important parts of the jQuery Library. In jQuery sectors are used to find HTML elements based on the their id, classes, types, attributes and so on. Then you can manipulate these HTML elements. Selectors always start with the dollar sign and parentheses: $(). jQuery lets you select elements based on the following criteria:

  1. Selecting by Element Name: The jQuery element selector selects elements based on the element name.
  2. Selecting by Element Id: The jQuery id selector uses the id attribute of an HTML tag to find the specific element.
  3. Selecting by CSS Class and so on: The jQuery class selector uses the class attribute to find the specific class.

Now we will see an example of how to use selectors in jQuery.

  1. <html>  
  2. <head>  
  3. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  4. <script>  
  5.     $(document).ready(function () {  
  6.         $("button").click(function () {  
  7.             $("#myid").hide(); //using id      
  8.             $("p").show(); //using element name  
  9.         });  
  10.     });  
  11. </script>  
  12. </head>  
  13. <body>  
  14. <p class="myclass">example of class selector.</p>  
  15. <p id="myid">example of id selector.</p>  
  16. <p>example of element name selector.</p>  
  17. <button>Click me</button>  
  18. </body>  
  19. </html> 

Up Next
    Ebook Download
    View all
    Learn
    View all