jQuery Library

JavaScript code to make it easu to write JavaScript that will execute across browsers.

Core set of features on which to build.

Many extensions and plug-ins available.

  • Core - core o flibrary allows identification of code to execute only after document loaded, create DOM elements, iterate elements, etc.
  • Selecting - easily select DOM elements, either individually or those matching pattern.
  • Filtering and traversing - create filters to match DOM elements and then traverse through resulting collection performing operations. Important functions include first, last, odd, visible, match, selected, contains, enabled, find, prev, parent, siblings.
  • Manipulation - can manipulate selcted objects, e.g. evaluating HTML contents, setting text of selected item. Functions include append, insert, replaceWith, wrap, remove.
  • CSS - functions include finding and setting styles, positioning items, setting size, etc.
  • Events - attach client code to user events. Decouples event code from markup. Handles mos t user actions - e.g. hover, toggle, click, keydown, focus, etc.
  • Animation and effects - functions to add animation effetcs to page, e.g. show, hide, fadeIn, fdadeOut, slideDown, etc.
  • AJAX - supports AJAX calls from browser to server.
  • Utilities - utility functions for browser compatibility, arrays, strings, etc.

Adding jQuery Library to webpage

ASP.NET 4 includes library in project by default.

Can easily add to existing site.

jQuery contained in single file - jquery-<version>.min.js+

To use on page reference library:

<script src="Scripts/jquery-1.4.1.js" type="text/javascript" />

Can also reference using ScriptManager control.

Library available via several content delivery networks (CDN) for rapid download, e.g. http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js

jQuery Script

Basic script does three things; ensure document loaded by browser, select elements from DOM, manipulate elements,e.g.:

<%@ Page ... >

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeaderContent">

<script src="Scripts/jquery-1.4.1.js" type="text/javascript" />

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<script type="text/javascript" >

<$(document).ready(function () {

$("h2").fadeIn("slow");

});

</script>

<h2 style="display: none">Page Title</h2>

</asp:Content>

The $ is equivalent to calling core jQuery() function. Used to select items in page and respond to life cycle events.

The $(document).ready() selects entire document and then indicates what to do when ready event fires.

An anonymous function is then passed in to execute when event fires.

The $("h2").fadeIn("slow" selects all instances of h2 tag and then for all found items call jQuery fadeIn function.

Selecting and Traversing DOM

Base selector function is jQuery() or its short cut $().

2 ways to pass string arguments to function:

  • Select by element - find all elements with specified tag, e.g. S("h2")
  • Select by ID - selects single element by its ID. Use # to indicate searching by id, e.g. $("#someId")
  • Select by CSS - find all elements with CSS class name. Use . To indicate CSS search, e.g. $(".userInputStyle")

Advanced Selectors

Can combine three selection types to get specific with searches.

To select all <span> tags with CSS style of "sectionHeading" write $("span.sectionHeading").

Can use keywords (e.g. :first, :odd. :not) within selection string to further refine it, e.g. to find first span write $("span:first")

Can search DOM for elements with specific attributes, specified using {}, e.g. $("a[href*=MyDomain]") finds all anchor tages that have MyDomain s part of href attribute.

Available search criteria:

Search Description Example
* Searches for search term in all string $("a[href*=MyDomain]")
^ Searches for search term at start of string $("a[href^=Folder/]")
$ Searches for search term at end of string $("a[href$=.com]")
! Searches for elements whose attributes do not match search string  $("a[href!=http://www.MyDomain.com]")

 

Selector examples:

Example Description
$("h2:first") First <h2> element
$("#div1:nth-child(4)")   Fourth child inside element with ID of div1
$(":enabled") All enabled elements on paged
$("'#div1 #div2") All elements with ID of div2 nested inside another element with ID of div1

 

Traversing Selection

jQuery returns set of elements matching criteria - even if only one element.

Use functions to work with these returned elements, for example to traverse all returned elements use each function:

$(document).ready(function() { $("h2").each(function (index) { this.innerHTML = "Section " + index; }); });

Can chain functions together, e.g. $("h2").fadeIn().each(function (index) { ...

Traversing examples:

Example Description
$("span").get[0] or $("span")[0] Returns single item from result set
$("h2").size() Number of elements in result set
$("h2").add("span").css("color", "green"); add() allows things to be added to elements, in this case a span with CSS color set to green
$("h2").eq(1).css("color", "green"); eq() selects element from result set, this example selects second h2 and turns it green.
$("#div1").find("h2") Subsearch to find h2 elements under element with id of div1
$("h2").filter(function(index) { return $("b", this).length ==1;})..css("color", "green");   Filter similar to find, but has overload allowing function to be used to evaluate each item in result set. In this example each result that has a <b/> tag within it is turned green.
$("h2").slice(2) Reduces set size based on start and optional end position, in this example set reduced to third element through to end.

Manipulating selection

Once selection narrowed to elements on which to focus then need to manipulate them.

Example Description
$("h2").append(": < a href='default.aspx'>home</a>");   Inserts html at the end of the element
$("#div1").detach() Removes the found elements from the DOM. Similar to .remove() but the elements are kept in memory and can be added back to DOM.
$("#div1").after($("#div2")); Allows content to be inserted after item, in this example the div element with id of div2 is inserted after that with an id of div1
$("h2").replaceWith("<h1>Title</h1>"); Removes content from DOM and replaces with something else.
$("h2").wrapInner("<span class="pageTitle"/>"); Wraps HTML content of selected elements, in this example <span> tag placed around content between <h2> tags.

Client-side Events

Can bind scripts to client-side events.

Scripts can be in separate .js files or within the page.

Bind to events using .bind() method - don't need to add markup to page.

May have markup of:

<asp:Content ContentPlaceHolderId="MainContent" .... >
<input type="button" id="buttonSearch" runat="server" value="Search" /> </asp:Content>

In a seperate .js file the following code hooks up to the click event to the function validateEmpId():

<script type="text/javascript"> $(document).ready(function () { $("#MainContent_ButtonSearch").click(validateEmpId); }); </script>

Note, the .click() method is a short cut for .bind("click", "validateEmpId");

Other short cuts include:

Event Description
.blur() Raised when element looses focus
.click() / .dblclick() Executes when element clicked / double clicked
.error() Trap element errors, e.g. broken links or missing images
.focus() / .focusin() / .focusout() .focus when element gains focus, .focusin when parent element gains focus, .focusout when element (or parent) looses focus
.hover() Raised when mouse pointer over element
.keydown() / .keyup() / .keypress() Traps keyboard input associated with element
.mousemove() / .mouseover() / .mousedown() / mouselevae()   Relate to mouse pointer incineration with element
.load() / .unload() Triggered when element is loaded / unloaded from page
.resize() Browser changes size
.scroll() Specified element is scrolled
.select() User selects data or child element within parent element
.unbind() Unbind code from an elements event

Page Effects and Animation

Find element via jQuery and then call desired effect, e.g.

$(document).ready(function() { $("h2:first").delay(1000).slideDown(); });

will wait for a second after page loads and then slide text into view.

Effect Description
.delay() Delays call of subsequent method
.fadeIn() / .fadeOut() / .fadeTo() Fade element into view, out of view or to another element
Jquery.fx.off Turns off jQuery effects on page
.show() / .hide() Show or hide selected elements
.slideDown() / .slideUp() / .slideToggle()   Slide element into view. Toggle allows element to be slide into / out of view (and toggle current show / hide state) 200
.toggle() Allow to functions to be bound to alternate click events
.stop() Stop animation or effect currently running for selected elements

AJAX with jQuery - calling a Web Service

The .ajax() method allows a web service to be called and page updated with its results.

Performs asynchronous HTTP request, passes data to request and gets the results.

Can be used for many tasks, e.g. file posting, send / receiving XML, etc. but main use is posting to web services for partial page updates.

Takes name-value pairs as settings - include URL, HTTP method, user credentials, etc.

Sample web service:

[System.Web.Services.ScriptService] public class EmployeeService : System.Web.Service.WebService { [WebMethod] public string GetEmployee(string employeeId) { return "Jane Developer"; } }

The ScriptService attribute indicates service can be called from client-side scripts like jQuery.

Sample client-side code:

$(document).ready(function() { $("#MainContent_ButtonSearch").click(function () { var empId = $("#MainContent_TextBoxEmpId").val(); $.ajax({ type: "POST", dataType: "json", contentType: "application/json", url: "EmployeeService.asmx/GetEmployee", data "{'employeeId': '" + empId + "'}", success: function(data) { alert("Employee name: " + data.d); }, error: function () { alert("Error calling web service"); } } }); });

Note, data setting used to pass information to web service - again as name value pairs within braces.

The success setting is a function called when the AJAX call is successful. In this example the results will be in JSON format and so will be an object.

The error setting represents a function to call when the AJAX call results in an error.

AJAX with jQuery - call back to Webpage

For self contained web pages may not want to expose a set of web services.

ASP.NET allows web methods to be added directly to page - do not need to create separate web services.

Based on prior example can move the web service into the page making the call:

<script runat="server"> [System.Web.Services.WebMethod] public string GetEmployee(string employeeId) { return "Jane Developer"; } </script>

No longer need to mark as a ScriptService - ASP.NET will assume this.

The .ajax call will be the same as before, except the URL will change to point to the aspx page, e.g.

url: "EmployeeLookupWebForm.aspx/GetEmployee",

Addition AJAX Methods

Method Description
$.getJSON()   Shorthand for $.ajax(), but data type automatically set to JSON and request type to GET, e.g. $.getJSON("States.txt", function(data) { alert("First state: " + data.state[1]); });
$.get() Shorthand for $.ajax(), but request type automatically set to GET, e.g. $.get("DataList.txt", null, function(html) { alert(html); }, "text");
$.post() Shorthand for $.ajax(), but request type automatically set to POST, e.g. $.post("EmpDetails.aspx", { "empId": "AB123" }, function(data) { alert(data); }, "html");
$getScript() Shorthand for $.ajax(), but data type automatically set to script, e.g. $.getScript("jquery/UpdateContents.js.aspx", function() { GetContent(); });

Download