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.
-
jQuery is Cross-Browser
-
jQuery supports Ajax
-
Rich Selectors
-
DOM Manipulation
-
Animation
-
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/ .
The jQuery architecture revolves around the following areas.
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() { .... });
Let's briefly have quick look at jQuery in action.
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.
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>
The $("div") selects all div elements. The fadeIn() effect is applied to each div matched.
The div is hidden initially.
On clicking the button the all the div elements fades in slowly.
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>
The $(p.mark) selects all paragraph elements with the class "mark".
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>
The above discussion summed up the very basics of jQuery. The next sections dig deeper into jQuery based on the antomical structure outlined.
The CSS selectors are baed on the CSS 1-3 as outlined by the w3C. For additional information please visit w3.org
All elements selection takes the form of $('T') where 'T' stands for the element tag name.For e.g.
-
$('div') selects all elements with a tag name of div in the document
-
$('input') selects all elements with a tag name of input in the document.
jQuery uses the JavaScript's getElementsByTagName() function for tag-name selectors.
This takes the form $('#id') where ID equal to id.For e.g.
-
$('#firstName') selects the unique element with id = 'firstName'.
-
$('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.
This takes the form $('.myclass') where class equal to myclass.For e.g.
-
$('.blink') selects all elements with class = 'blink'.
-
$('p.blink') selects all paragraphs that have a class of blink.
-
$('.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.
Matches all elements matched by E2 that are descendants of an element matched by E1.For e.g.
-
$('#menu li') selects all elements matched by <li> that are descendants of an element that has an id of menu.
-
$('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".
Matches all elements matched by E2 that are children of an element matched by E1.For e.g.
-
$('li > ul') selects all elements matched by <ul> that are children of an element matched by <li>.
-
$('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.
Matches all elements by E2 that immediately follow and have the same parent as an element matched by E1.For e.g.
-
$('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.
Matches all elements by E2 that follow and have the same parent as an element matched by E1.For e.g.
-
$('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">
Selects all elements matched by selector E1, E2 or E3.For e.g.
-
$('div, p, pre') selects all elements matched by <div> or <p> or <pre>.
-
$('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.
All elements that are the nth child of their parent.For e.g.
-
$('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.
All elements that are the first child of their parent.For e.g.
-
$(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).
All elements that are the last child of their parent.For e.g.
-
$(li:last-child') selects all elements matched by <li> that are the last child of their parent.
All elements that are the only child of their parent.For e.g.
-
$(':only-child') selects all elements that are the only child of their parent.
-
$('p:only-child') sleects all elements matched by <p> that are the only child of their parent.
All elements that do not match selector 's'.For e.g.
-
$('li:not (.myclass)') selects all elements matched by <li> that do not have class="myclass".
-
$('li:not(:last-child)') selects all elements matched by <li> that are not the last child of their parent element.
All elements that have no children (including text nodes).For e.g.
-
$('p:empty') selects all elements matched by <p> that have no children.
-
$('empty') selects all elements that have no children.
All elementsFor e.g.
-
$('*') selects all elements in the document.
-
$(p > '*') selects all elements that are children of a paragraph element.
XPath selectors are modelled after the file system's directory-tree navigation.
All elements matched by E1 that are descendants of an element matched by E1.For e.g.
-
$('div//e') selects all elements matched by <code> that are descendants of an element matched by <div>
-
$('//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.
All elements matched by E2 that are children of an element matched by E1.For e.g.
-
$('div/p') selects all elements matched by <p> that are children of an element matched by <div>.
-
$('/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.
All elements that are parents of an element matched by E.For e.g.
-
$('.menuitem/..') selects the parent element of all elements that have a class of menuitem.
-
$('.menuitem/../p') selects all elements matched by <p> that are children of the element that has a class of menuitem.
All elements that contain an element matched by E.For e.g.
-
$('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 begin with @ symbol.
All elements that have foo attribute.For e.g.
-
$('a[@rel]') selects all elements matched by <a> that have a rel attribute.
-
$('div[@class]') selects all elements matched by <div> that have a class attribute.
All elements that have the foo attribute with a value exactly equal to bar.For e.g.
-
$('a[@rel=nofollow]') selects all elements matched by <a> that have an attribute 'rel' with a value of 'nofollow'.
-
$('input[@name=first-name]') selects all elements matched by <input> that have a name value exactly equals to first-name.
All elements that do not have a foo attribute with a value exactly equal to bar.For e.g.
-
$('a[@rel != nofollow]') selects all elements matched by <a> that do not have an attribute 'rel' with a value of 'nofollow'.
-
$('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])').
The following is the form selector list
-
:input -> selects all form elements (input, select, textarea, button).
-
:text -> selects all text fields (type = "text")
-
:password -> selects all password fields (type = "password")
-
:radio -> selects all radio fields (type = "radio")
-
:checkbox -> selects all checkbox fields (type = "checkbox")
-
:submit -> selects all submit buttons (type = "submit")
-
:image -> selects all form images (type = "image")
-
:reset -> selects all reset buttons (type = "reset")
-
:button -> selects all other buttons (type = "button")
-
:file -> selects all <input type = "file">
:even All elements with an even index
:odd All elements with an odd indexFor 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.
The element with index value equal to n.For e.g.
-
$('li:eq(2)') selects the third <li> element
-
$('p:nth(1)') selects teh second <p> element.
The elements with index greater than N.For e.g.
-
$('li:gt(1)') selects all elements matched by <li> after the second one.
The element with index value less to n.For e.g.
-
$('li:lt(3)') selects all elements matched by <li> before the 4th one, in other words the first three <li> elements.
The first instance of an element.For e.g.
-
$('li:first') selects the first <li> element.
-
$('tr:first') selects the first <tr> element.
The last instance of an element.For e.g.
-
$('li:last') selects the last <li> element.
-
$('tr:last') selects the last <tr> element.
All elements that are parent of another element including text node.For e.g.
-
$(':parent') selects all elements that are the parent of another element.
-
$('td:parent') selects all elements matched by <td> that are the parent of another element.
All elements that contain the specified text.For e.g.
-
$('div:contains(sample div)') selects all elements matched by <div> that contain the text 'sample div'.
-
$('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.
All elements that are visible.For e.g.
-
$('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.
All elements that are hidden.For e.g.
-
$('div:hidden') selects all elements matched by <div> that are hidden.
jQuery has a powerful jquery traversal and manipulation methods.
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.
The following are the jQuery methods for inserting/appending elements into the DOM.
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>
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.
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>
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>
Coming up soon
Coming up soon
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.
-
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.
-
Line 07 sets up the loading-panel to display a loading image. The image can be downloaded from http://www.ajaxload.info/.
-
Line 08 sets up the success() handler. This method is executed if the AJAX request is sucessfully executed.
-
Line 09 appends the new message to the comment-list div if the request executed successfully.
-
Line 10 invokes the flashit() method which flashes/animates the inserted method.
-
Line 11 sets up the error() handler. This method is executed if there are any errors while executing the AJAX request.
-
Line 12 sets up the complete() handler. This method is executed after the AJAX request is completed.
-
Line 13 empties the loading-panel to clear up the image.
AJAX Options
Coming up soon.
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>
Here the screenshot of this snippet in action.
I think the code is well commented to guage the logic.
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.
-
Set a variable to a limit of 250 characters.
-
Assign a default value to the "div" element with id "dvLimit"
-
Find the control that contains the id "txtDemoLimit" and hook up the keyup event.
-
In the keyup event get the length of the current text.
-
If len is greater than the limit set, set the text value as a substring within the specified limit.
-
Update the div with the no. of characters left to be keyed in.
<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.
Modify this as per your requiement and enjoy jQuerying !!!
Coming up soon
-
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.