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.

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.

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

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.

$('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.

:even All elements with an even index
:odd All elements with an odd index

For e.g.

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

$('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.

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.

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.

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.

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.

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

Line 02 invokes the ajax method with the following parameters.

Line 03 sets the request type to "POST".

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

Line 05 assigns the data as part of the request.

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

AJAX Options

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.

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 listvar 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>

As you may be aware by this time that there is more than one way to work with jQuery and the thing we have to try is to use the best method i.e. the most performant method. The following are some of the ways in which you can get maximum performance out of jQuery. Note I am not taking into consideration the browser, operating system, hardware and other things which may have some consequence on performance

Latest Version

Get the latest version of jQuery. Since jQuery is in active development there will be plenty of fixes that will come up with each release.

Context

Passing a context to the jQuery function can improve the query performance as this will reduce the number of DOM elements that are traversed. In order to do this you need to pass the jQuery function a second parameter which referes to a single DOM element. This element is then used as the starting point for the DOM querying and as a result there will be some performance benefits which the app may get.

In many situation you can use the this as the second parameter. Please do note that in order for a performance gain, you need to pass an actual DOM reference as the 2nd parameter. Passing anything other than a DOM reference still requires a search of the entire document actually may hinder performance.

Selector Performance

This is one of the important design decision you need to take. The performance may be directly impacted by the selectors you use. The selector peformance is dependent upon the following points

Complexity of the selector expression

Type of selector

Size and Complexity of the DOM that is being evaluated

Following are some of the important points you can consider while using jQuery

Prefer ID selector whenever possible.

The simple the selector the better the performance

If you have to use class name, always try to use it with other selector as well.
For. e.g. Use $('div.menu') rather than $('.menu') or something similar based on your requirement.

Since Simple DOM are traversed faster the context becomes much more important.

Cache elements if they are used frequent

Never duplicate the DOM queries for the same element/elements. Cache the result set and use it. This is more important when you are dealing with loops. Store the wrapped set in a local variable outside the loop so that you avoid querying during each iteration.>

Keep DOM changes to minimum

As the previous tip this concept is important when dealing with loops. Avoid updating elements in the loop. Rather, create a string representation of the element in the loop and update the DOM outside the loop.

In this update, let's build a simple slide show app. We will keep the API simple to follow and may skip certain best practices for ease of understanding. But I will update the article with my observation of the recommended practices and may change the example to refer that.

We haven't yet coded the mySlideShow object. But let's see what we are expecting from this object. We intend to invoke the slide show, by passing in a title, the elementID were the slides will be displayed, and a timer value. If the timer vaue is 0 the slides can be navigated by clicking on the "next" and "prev" button. The timer value is in milliseconds. If you give a timer value of 1000, then after 1000 seconds the slides will automatically changed.

NOTE: This is not a full fledged libray, but has enough information to cover the fundamentals. You can adapt this as per your requirement, style it the way you want it, add images etc.

NOTE: Also, please note this code is only in couple of iterations and as such I am aware of some ways to optimize this. The article may be updated in future but the idea now is get the MVP (Minimum Viable Product) feature ready :).

Note the functions are chained here. We can specify the slides and the points in the slides by using the slide() method which takes an object literal with a title and an array of points.

Now let's see how the library/module is coded. First we wrap the entire library code in an IIFE (Immediately invoked function or also called as self invoking anonymous function). Note we are explicitly passing the global objects like window and jQuery to the function call (This is a best practice to avoid module/naming conflicts)

We will create a jquery plugin named "quickTree" that can be invoked on any existing
element. For this example I have made it work with a unordered list, but you can modify
the code to suite to your requirement, add images,labels etc.

The code for the jquery plugin is give below and also a working plnkr url is shared