Getting friendly with jQuery (A beginners guide + added auto TOC generation + text entry limit)

Background

This article is the summation of my notes collected during my attempt to learn jQuery through various books and websites. As such this is still a work in progress and will be updated based on my understanding and study of this beautiful library and will add simple uses cases of jquery with asp.net/mvc.

Introduction

jQuery is a javascript library with rich API to manipulate DOM, event handling, animation and ajax interactions.  The following are the essential features of jQuery that makes it so appealing for client side scripting.

  1. jQuery is Cross-Browser

  2. jQuery supports Ajax

  3. Rich Selectors

  4. DOM Manipulation

  5. Animation

  6. Rich UI

Please feel free to download Questpond's  free 500 question and answer Videos or e-Book which covers .NET , ASP.NET , SQL Server , WCF , WPF , WWF, .Net Best Practises, Sharepoint Interview Questions, Linq, Silverlight, MVP, MVC, Design Pattern, UML, Function Points, Enterprise Application Blocks, Code Review Tools, Complete Dot Net Project With SDLC, 20 OOP'S Question and Answers, Azure, @ http://www.questpond.com/ .

Anatomy of jQuery

The jQuery architecture revolves around the following areas. 

rr1.jpg 

Setting up jQuery ready handler

jQuery lets you run your code when the page elements have been loaded. This is more efficient than the browser onload() functions, which is called only after all images have been loaded. To run the code when the page is ready you use the following syntax

$(document).ready(function() { .... }); There's a shorthand as well $(function() { .... }); 

A Quick Demo

Let's briefly have quick look at jQuery in action.

Selecting Page Elements by ID

The $('#id') is used to select elements by id. When you click on the button "Stripe" the stripe() JS method is triggered which toggles the class of the element whose id matches 'third'. On subsequent click the style will be reset. 

rr2.jpg 
The code and the markup is displayed below.

    <head>
    <title>Select a paragraph</title>
    <script type="text/javascript" src="jquery-1.3.2.min.js">
    </script>
    <script type="text/javascript"> function stripe( ) { $('#third').toggleClass('striped'); }
    </script>
    <style> p.striped { background-color: cyan; }
    </style>
    </head>
    <body> <h1>Select a paragraph</h1>
    <div> <p>This is paragraph 1.</p>
    <p>This is paragraph 2.</p>
    <p id="third">This is paragraph 3.</p>
    <p>This is paragraph 4.</p>
    </div>
    <form> <input type = "button" value="Stripe" onclick="stripe()">
    </input>
    </form>
    </body>

Selecting a Set of Elements

The $("div") selects all div elements. The fadeIn() effect is applied to each div matched. 

The div is hidden initially. 

rr3.jpg 
On clicking the button the all the div elements fades in slowly. 

4.jpg 
The code and the markup is displayed below.

     <head>
     <title>Selecting a set of Elements</title>
     <script type="text/javascript" src="Scripts/jquery-1.3.2.min.js">
     </script>
     <script type="text/javascript"> function fade() { $("div").fadeIn('slow'); }
     </script>
     </head>
     <body>
     <h1>Fade</h1>
     <div style ="display:none"> This div was hidden. </div>
     <div style ="display:none;border:solid 1px orange"> So as this. </div>
     <form> <input type = "button" value="Fade Div" onclick="fade()" />
     </form>
     </body>
 

Selecting Elements by Style

The $(p.mark) selects all paragraph elements with the class "mark".

 5.jpg
The code and the markup is displayed below.

     <head>
     <title>Select a paragraph</title>
     <script type="text/javascript" src="Scripts/jquery-1.3.2.min.js">
     </script>
     <script type="text/javascript"> function highlight() { $('p.mark').toggleClass("highlight"); }
     </script>
     <style type="text/css"> p.mark { font-weight: normal; } p.highlight { background-color: lightgray; }
     </style>
     </head>

     <body>
     <h1>Select a paragraph</h1>
     <div>
     <p class = "mark">This is paragraph 1.</p>
     <p>This is paragraph 2.</p>
     <p class = "mark">This is paragraph 3.</p>
     <p>This is paragraph 4.</p>
     </div>
     <input type = "button" value="Highlight" onclick="highlight()"/>
     </body>

Digging deeper into jquery

The above discussion summed up the very basics of jQuery. The next sections dig deeper into jQuery based on the antomical structure outlined.

 6.jpg

CSS Selectors

The CSS selectors are baed on the CSS 1-3 as outlined by the w3C. For additional information please visit w3.org

Selecting by Element

All elements selection takes the form of $('T') where 'T' stands for the element tag name.For e.g.

  1. $('div') selects all elements with a tag name of div in the document

  2. $('input') selects all elements with a tag name of input in the document.

jQuery uses the JavaScript's getElementsByTagName() function for tag-name selectors.

Selecting by ID

This takes the form $('#id') where ID equal to id.For e.g.

  1. $('#firstName') selects the unique element with id = 'firstName'.

  2. $('div#main') selects a single div with an id of 'main'.

If there are more than one element with the same id then jQuery selects the first matched element in the DOM.

Selecting by Class

This takes the form $('.myclass') where class equal to myclass.For e.g.

  1. $('.blink') selects all elements with class = 'blink'.

  2. $('p.blink') selects all paragraphs that have a class of blink.

  3. $('.mybold.myblink') selects all elements that have a class of 'mybold' and 'myblink'.

Performance wise the example 2 is preferable as it limits the query to a given tag name.

Selecting by Descendant (E1 E2)

Matches all elements matched by E2 that are descendants of an element matched by E1.For e.g.

  1. $('#menu li') selects all elements matched by <li> that are descendants of an element that has an id of menu.

  2. $('a img') selects all elements matched by <img> that are descendants of an element matched by <a>

A descendant of an element is any element that is a child, grandchild and so on of that element.

     <div id = "menu">
     <div id = "item1">
     <div id = "item-1.1">
     <div id = "item-1.2">
     <div id = "item-1.2.1"/>
     </div>
     </div>
     </div>

In the above example "item-1.2.1" is a descendant of "item-1.2", "item-1.1", "item1" and 'menu".

Selecting Child elements (E1 > E2)

Matches all elements matched by E2 that are children of an element matched by E1.For e.g.

  1. $('li > ul') selects all elements matched by <ul> that are children of an element matched by <li>.

  2. $('p > pre') matches all elements matched by pre that are children of an element matched by<p>.

The child selector works in all modern browser except IE 6 and below.  The child combinator is a more specific form of descendant
combinator as it selects only first-level descendants.

Adjacent Sibling (E1 + E2)

Matches all elements by E2 that immediately follow and have the same parent as an element matched by E1.For e.g.

  1. $('p + img') selects all elements matched by <img> that immediately follow a sibling element matched by <p>.

The + combinator selects only siblings i.e. elements at the same level as the matched element.

General Sibling (E1 ~ E2)

Matches all elements by E2 that follow and have the same parent as an element matched by E1.For e.g.

  1. $('p ~ img') selects all elements matched by <img> that follow a sibling element matched by <p>.

The difference between + and ~ is + combinator reaches only to the immediately following sibling element whereas the ~ combinator extends that reach to all following sibling elements as well.
Consider the following HTML.

     <ul>
     <li class = "1st"></li>
     <li class = "2nd"></li>
     <li class = "3rd"></li>
     </ul>
     <ul>
     <li class = "4th"></li>
     <li class = "5th"></li>
     <li class = "6th"></li>
     </ul>

$('li.1st ~ li) selects <li class = "2nd"> and <li class = "3rd">.
$(li.1st + li) selects <li class = "2nd">

Multiple Elements (E1, E2, E3)

Selects all elements matched by selector E1, E2 or E3.For e.g.

  1. $('div, p, pre') selects all elements matched by <div> or <p> or <pre>.

  2. $('p bold, .class-name) sleects all elements matched by <bold> that are descendants of <p> as well as all elements that have a class of '.class-name'.

The comma (,) combinator is an efficient way to select disparate elements.

Nth Child (:nth-child(n))

All elements that are the nth child of their parent.For e.g.

  1. $('li:nth-child(3)') selects all elements matched by <li> that are the 3rd child of their parent.

The 'n' is 1 based as this is strictly derived from the CSS specification.  For all other selectors jQuery follows 0-based counting.

First Child (:first-child)

All elements that are the first child of their parent.For e.g.

  1. $(li:first-child') selects all elements matched by <li> that are the first child of their parent.

The :first-child  pseudo-class is shorthand notation for :nth-child(1).

Last Child (:last-child)


All elements that are the last child of their parent.For e.g.

  1. $(li:last-child') selects all elements matched by <li> that are the last child of their parent.

Only Child (:only-child)


All elements that are the only child of their parent.For e.g.

  1. $(':only-child') selects all elements that are the only child of their parent.

  2. $('p:only-child') sleects all elements matched by <p> that are the only child of their parent.

Not (:not(s))

All elements that do not match selector 's'.For e.g.

  1. $('li:not (.myclass)') selects all elements matched by <li> that do not have class="myclass".

  2. $('li:not(:last-child)') selects all elements matched by <li> that are not the last child of their parent element.

Empty (:empty)

All elements that have no children (including text nodes).For e.g.

  1. $('p:empty') selects all elements matched by <p> that have no children.

  2. $('empty') selects all elements that have no children.

All Elements (*)

All elementsFor e.g.

  1. $('*') selects all elements in the document.

  2. $(p > '*') selects all elements that are children of a paragraph element.

XPath Selectors

XPath selectors are modelled after the file system's directory-tree navigation.

Descendant (E1//E2)

All elements matched by E1 that are descendants of an element matched by E1.For e.g.

  1. $('div//e') selects all elements matched by <code> that are descendants of an element matched by <div>

  2. $('//p//a') selects all elements matched by <a> that are descendants of an element matched by <p>

The XPath descendant works the same as teh corresponding CSS descendant selector $('E1 E2) except that the XPath version can specify that it is to start at the document root, which could be useful when working with XML document.

Child (E1/E2)

All elements matched by E2 that are children of an element matched by E1.For e.g.

  1. $('div/p') selects all elements matched by <p> that are children of an element matched by <div>.

  2. $('/root/e') sleects all elements matched by <e> that are children of an element matched by <root>, as long as <root> is actually at the document root.

The XPath child seletor $('E1/E2') is an alternative to the CSS child selector $('E1 > E2').  If the selector expression begins with a single slash (/), as in example 2, the selector immediately following the slash must be at the document root.

Parent (E/..)

All elements that are parents of an element matched by E.For e.g.

  1. $('.menuitem/..') selects the parent  element of all elements that have a class of menuitem.

  2. $('.menuitem/../p') selects all elements matched by <p> that are children of the element that has a class of menuitem.

Contains ([E])

All elements that contain an element matched by E.For e.g.

  1. $('div[p]') selects all elements matched by <div> that contain an element matched by <p>.

This selector is like the reverse of the descendant selector (either E1 // E2 or E1 E2), in that it selects all elements that have a descendant element matched by E1 instead of all elements matched by E2 that are descendants of some other element.

Attribute Selectors

Attribute selectors begin with @ symbol.

Has Attribute ([@foo])

All elements that have foo attribute.For e.g.

  1. $('a[@rel]') selects all elements matched by <a> that have a rel attribute.

  2. $('div[@class]') selects all elements matched by <div> that have a class attribute.

Attribute Value Equals ([@foo=bar])

All elements that have the foo attribute with a value exactly equal to bar.For e.g.

  1. $('a[@rel=nofollow]') selects all elements matched by <a> that have an attribute 'rel' with a value of 'nofollow'.

  2. $('input[@name=first-name]') selects all elements matched by <input> that have a name value exactly equals to first-name.

Attribute Value Does Not Equal ([@foo != bar])

All elements that do not have a foo attribute with a value exactly equal to bar.For e.g.

  1. $('a[@rel != nofollow]') selects all elements matched by <a> that do not have an attribute 'rel' with a value of 'nofollow'.

  2. $('input[@name != first-name]') selects all elements matched by <input> that do not have a name attribute with a value exactly equal to first-name.

NOTE: These selectors see attribute value as a single string.  So, attributes with values separated by space will not be matched. 

To exclude the following match <a rel="nofollow self" href=...>link</a> use the following selector
$('a:not[@rel *= nofollow])').

Form Selector

The following is the form selector list

  1. :input               -> selects all form elements (input, select, textarea, button).

  2. :text                -> selects all text fields (type = "text")

  3. :password         -> selects all password fields (type = "password")

  4. :radio               -> selects all radio fields (type = "radio")

  5. :checkbox         -> selects all checkbox fields (type = "checkbox")

  6. :submit             -> selects all submit buttons (type = "submit")

  7. :image              -> selects all form images (type = "image")

  8. :reset               -> selects all reset buttons (type = "reset")

  9. :button             -> selects all other buttons (type = "button")

  10. :file                  -> selects all <input type = "file">

Custom Selector

Even element (:even) Odd eleemnt (:odd)

:even All elements with an even index
:odd   All elements with an odd indexFor e.g.

  1. $('li:even') selects all elements matched by <li> that have an even index value.

  2. $('tr:odd') selects all elements matched by <tr> that have an odd index value.

As the :even and :odd pseudo-classes match element based on their index, they use JS's native zero-based numbering.  So, even selects the first, third (and so on) elements while :odd selects teh second, fourth (and so on) elements.

Nth element (:eq(n), :nth(n))

The element with index value equal to n.For e.g.

  1. $('li:eq(2)') selects the third <li> element

  2. $('p:nth(1)') selects teh second <p> element.

Greater than  (:gt(n))

The elements with index greater than N.For e.g.

  1. $('li:gt(1)') selects all elements matched by <li> after the second one.

Less than (:lt(n))

The element with index value less to n.For e.g.

  1. $('li:lt(3)') selects all elements matched by <li>  before the 4th one, in other words the first three <li> elements.

First (:first)

The first instance of an element.For e.g.

  1. $('li:first') selects the first <li> element.

  2. $('tr:first') selects the first <tr> element.

Last (:last)

The last instance of an element.For e.g.

  1. $('li:last') selects the last <li> element.

  2. $('tr:last') selects the last <tr> element.

Parent (:parent)

All elements that are parent of another element including text node.For e.g.

  1. $(':parent') selects all elements that are the parent of another element.

  2. $('td:parent') selects all elements matched by <td> that are the parent of another element.

Contains (:contains(text))

All elements that contain the specified text.For e.g.

  1. $('div:contains(sample div)') selects all elements matched by <div> that contain the text 'sample div'.

  2. $('li:contains(wrong link)') selects all elements matched by <li> that contain the text 'wrong link'.

The matching text can appear in the selector element or in any of that element's descendants.

Visible (:visible)

All elements that are visible.For e.g.

  1. $('div:visible') select all elements matched by <div> that are visible.

The :visible selector includes elements that have a display of block or inline or any other value other than none and a visibility of visible.

Hidden (:hidden)

All elements that are hidden.For e.g.

  1. $('div:hidden') selects all elements matched by <div> that are hidden.

DOM

jQuery has a powerful jquery traversal and manipulation methods.

$() factory revisited

We have used the $() functionto access elements in a document.  Let's roll up our sleeves and try doing some trick with the $().    In fact simply inserting a snippet of HTMl code inside the parentheses, we can create an entirely new DOM structure.  Isn't this amazing.

Inserting new elements

The following are the jQuery methods for inserting/appending elements into the DOM.

.before(content)

Inserts content specified by the parameter before each element in the set of matched elements.  The return vlaue is the jQuery object for chaining purposes.  Consider the following HTML fragment.

<div class = "div1"> This div already exist </div>

Execute the following jquery script.

$('div.div1').before('<div class="insert">This div is dynamically inserted</div>')

The resulting HTML will be

     <div class = "insert"> This div is dynamically inserted </div>
     <div class = "div1"> This div already exist </div>

.insertBefore(content)

Inserts every element in the set of matched elements before the set of elements specified in the parameter.  Consider the following HTML fragment.

<div class = "div1"> This div already exist </div>

Execute the following jquery script.

$('<div class="insert">This div is dynamically inserted</div>').insertBefore('div.div1')

The resulting HTML will be

<div class = "insert"> This div is dynamically inserted </div>
<
div class = "div1"> This div already exist </div>

There is only structural difference in the way both the above function works.

.after(content)

Inserts content specified by the parameter after each element in the set of matched element.  Consider the following HTML fragment.

<div class = "div1"> This div already exist </div>

Execute the following jquery script.

$('div.div1').after('<div class="insert">This div is dynamically inserted</div>')

The resulting HTML will be

<div class = "div1"> This div already exist </div>
<div class = "insert"> This div is dynamically inserted </div>

.insertAfter(content)

Inserts every element in the set of matched elements after the set of elements specified in the parameter.  Consider the following HTML fragment.

<div class = "div1"> This div already exist </div>

Execute the following jquery script.

$('<div class="insert">This div is dynamically inserted</div>').insertAfter('div.div1');

The resulting HTML will be

<div class = "div1"> This div already exist </div>
<
div class = "insert"> This div is dynamically inserted </div>

Playing with Events

Coming up soon

Effects and Animation

Coming up soon

Spicing website with Ajax

Let's start with a small usecase in action. Let's say you have a use case to add "Comment" to a blog post. The code snippet is writting for the ASP.NET MVC framework, but it should be seamless to modify it to suit it to work with classic asp.net, php, ror or anything you deem fit.
The comment view is very simple. The following is the minimal markup without any styles for adding a comment.

      <h2>Add Comment</h2>
      <label for ="body">Body</label>
      <br />
      <%= Html.TextArea("body")%>
      <div id = "loading-panel"></div>
      <hr />
      <input id="comment_submit" type="button" value = "Publish" />

The minimal code for the controller is shown below.  When the "Publish" button is clicked we want to make a request to the PostController's action method named "NewComment" in an asynchronous fashion.  The code shown is only for demonstration purpose and as such has no meaning apart from the context of this discussion.

         public class PostController : BaseController
         {
             /// Add new comment
             /// <param name="postId">The post id.</param>
             /// <param name="body">The body.</param>
             public ActionResult NewComment(Guid postId, string body)
             {
              var post = Repository.GetPostById(postId);
              var comment = new Comment
             {
               Body = body, Post = post };

              Repository.AddComment(comment);
              return Content(body);

               }
           }

Let's set up the jQuery to enable posting back in an asynchronous way and also show a progress bar on the way.

<script type="text/javascript"> function flashit()
{
flash('#comment-list li:last'); }
function flash(selector) { $(selector).fadeOut('slow').fadeIn('show');
}
</script>
<
script type = "text/javascript"> $(function()
{
$("#comment_submit").click(function() {
// Set up a string to POST parameters. You can create the JSON string as well.
var dataString = "postId=" + "<%=Model.Post.Id %>" + "&body=" + $('#body').val();
(01) $.ajax({ (02) type: "POST", (03) url: "/Post/NewComment", (04) data: dataString,
(05) beforeSend: function(XMLHttpRequest) { (06) $('#loading-panel').empty().html
('<img src="http://www.c-sharpcorner/Content/Images/ajax-loader.gif" />'); (07) },
success: function(msg) { (08) $('#comment-list').append('<li>' + msg + '</li>');
(09) flashit(); (10) }, error: function(msg) { (11) $('#comment-list').append(msg); },
complete: function(XMLHttpRequest, textStatus) { (12) $('#loading-panel').empty(); (13)
}
});
});
});

</script>

In the above code the jQuery factory function $() sets up the "comment_submit" click event handler.  Whenever the "submit" button is clicked the click function defined above is executed.    The following points highlights what's happening in the above function.

  1. Line 01 sets up the data to be posted to the controller.

  2. Line 02 invokes the ajax method with the following parameters.

  3. Line 03 sets the request type to "POST".

  4. Line 04 sets up the URL.  In this case the URL is Post Controller's action method should be invoked.

  5. Line 05 assigns the data as part of the request.

  6. Line 06 sets up the beforeSend() handler.  This method is executed just before the ajax method is invoked.

  7. Line 07 sets up the loading-panel to display a loading image.  The image can be downloaded from http://www.ajaxload.info/.

  8. Line 08 sets up the success() handler.  This method is executed if the AJAX request is sucessfully executed.

  9. Line 09 appends the new message to the comment-list div if the request executed successfully.

  10. Line 10 invokes the flashit() method which flashes/animates the inserted method.

  11. Line 11 sets up the error() handler.  This method is executed if there are any errors while executing the AJAX request.

  12. Line 12 sets up the complete() handler.  This method is executed after the AJAX request is completed.

  13. Line 13 empties the loading-panel to clear up the image.

AJAX Options

Coming up soon.

Generate Automatic TOC

Let's quickly create an automated TOC for our page. Say we have a page with the following structure and we need to create a TOC based on the <h3> heading. We want to insert this TOC in the "header" div. All the TOC contents should link back to the content of the page.

HTML Snippet

     <div id="header">
     <h1> Automatic Bookmark Headings Example</h1>
     <h2> Using jQuery to Extract Existing Page Information</h2>
     </div> <div id="Div1">
     <h1> Automatic Bookmark TOC Example</h1>
     <h2> Using jQuery to Extract Existing Page Information</h2>
     </div>
     <div id="Div2">
     <h3>Introduction</h3>
     <p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
     </p>
     <a href="#header" title="return to the top of the page">Back to top</a>
     </div> <div id="content">
     <h3>Content</h3>
     <p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
     </p>
     <a href="#header" title="return to the top of the page">Back to top</a>
     </div>

The TOC Generator Script

<script type="text/javascript"> $("document").ready(function() { createTOC('h3', 'header'); });
 // tag : the header tag for which the toc is to be built
 // container : id of the div that we want to append the resulting TOC. function createTOC(tag, container)
 {
 var anchorCount = 0;
 // count to create unique id
 // create an unordered list
 var oList = $("<ul id='bookmarksList'>");

    /* 1. For each header tag create a named anchor and insert the into header tag. It will serve as the jump location for the TOC.
    2. Add the link to the unordered list that will point to the named anchor.
    */
/* Get all h3 inside div where id is not equal to header.
    // For each h3 tag //
    1. Create the named anchor. This should be a unique name.
    // 2. Set the html for h3 tag to a named anchor.
    // 3. Add the existing html for the h3 in front of the named anchor.
    // 4. Create the TOC links
    // 5. Add the TOC to the container. */

    $("div:not([id=header]) " + tag).each(function()
    { $(this).html("<a name='bookmark" + anchorCount + "'></a>" + $(this).html());
    oList.append($("<li><a href='#bookmark" + anchorCount++ + "'>" + $(this).text() + "</a></li>"));
    }); $("#" + container).append(oList); }
    </script>


7.jpg

Here the screenshot of this snippet in action.

I think the code is well commented to guage the logic.

Limit text box entry

Lets quickly have a look at how you can limit the entry to textbox and display the character input left to be keyed in.

<script type="text/javascript">    
$(function() {        
var limit = 250;        
$('#dvLimit').text('250 characters left');        
$('textarea[id$=txtDemoLimit]').keyup(function() {            
var len = $(this).val().length;            
if (len > limit) {                
this.value = this.value.substring(0, limit);            
}            
$("#dvLimit").text(limit - len + " characters left");        
});    
});
</script>  

The $() function does the following things on startup.

  1. Set a variable to a limit of 250 characters.

  2. Assign a default value to the "div" element with id "dvLimit"

  3. Find the control that contains the id "txtDemoLimit" and hook up the keyup event.

  4. In the keyup event get the length of the current text.

  5. If len is greater than the limit set, set the text value as a substring within the specified limit.

  6. Update the div with the no. of characters left to be keyed in.
     

The HTML is shown below.

<div id="dvLimit"></div>
<div>
<asp:TextBox ID="txtDemoLimit" TextMode="MultiLine" Columns = "40" Rows = "10" runat="server">
</asp:TextBox>
</div>

The following is the application in action.

8.jpg
 
Modify this as per your requiement and enjoy jQuerying !!! 

Plug with the Plug-In API

Coming up soon

References

History

  • December 06, 2009 - Limit text input entry.

  • September 15, 2009 - Generate Automatic TOC.

  • August 24, 2009 - Added a simple AJAX use case.

  • August 23, 2009 - Created the first version of the article.

Up Next
    Ebook Download
    View all
    Learn
    View all