jQuery

Last Updated: 8/16/2011

Links And Resources

·         http://speckyboy.com/2008/04/02/65-excellent-jquery-resources-tutorialscheat-sheetsebooksdemosplugins/

·         http://api.jquery.com

 

Basics

At its core, jQuery is a way to select elements and perform actions upon them. The basic prototype is: $(selector).action(). For example:

$("#myId").hide()      // Hide the element with the id "myId"
$("p").hide()          // Hide all paragraph elements
$(".myClass").hide()   // Hide all the element with class="myClass"
$("p#myId").hide()     // Hide all paragraph elements with the id="myId"
$("p.myClass").hide()  // Hide all paragraph elements with class="myClass"

Note how similar the syntax is to CSS selectors: #myId p {…} vs. $('#myId p')

Include is a single file:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js" ></script>
Note that IE9 needs the closing </script> tag (A ‘…/>’ on the opening tag is not sufficient).
(Google also hosts version of this file, and there is nothing to stop you self-hosting.)

Selectors

jQuery uses XPath like syntax to determine the selected items.

Sample

Meaning

$("*")

All elements

$("[myAttribute])

All elements with a ‘myAttribute’ attribute

$("[myAttribute='x']")

All elements whose ‘myAttribute’ attribute value matches x.

$("[myAttribute!='x']")

All elements whose ‘myAttribute’ attribute value does not match x.

$("[myAttribute$='x']")

All elements whose ‘myAttribute’ attribute value ends with x (e.g. $([src]$="png")

$(this)

Current element. Note the lack of quotes.

$("…:first")

Limits the selection to the first occurrence. This is always a single result (e.g. “ul li:first” will return only the first list item in the first list, not the first list item in each list)

$("…:last")

$("…:even")

$("…:odd")

As you’d expect

$("…:eq(nth)")

$("…:gt(nth)")

$("…:lt(nth)")

The nth match, the nth & subsequent matches, etc.

$("div#myDiv ul li:first")

The first li inside a ul that’s inside the div with an ID of myDiv

$(":contains(text)”)

All elements containing the specified text

$(":empty")

All elements with no child elements

$(":hidden")
$(":visible")

$(":disabled")
$(":enabled")

All elements that are hidden / visible /enabled / disabled

:text, :button, etc

All elements of the specified input type.

:selected
:checked

All elements that are selected / checked.

 

Actions

Sample

Example

.css("style-element", "new-value")

$("p").css("color", "red")
Changes all paragraphs (foreground) color to red

.blur()

.change()

.click()

.dblclick()

.focus()

.load()

.mousedown()

etc

With no arguments, triggers the code associated with that event. With a function parameter assigns code to the event. For example:
 $(“:button”).click(function() {$(this).hide()})

 

Effects

Sample

Example / Meaning

.someCommand("slow|fast|normal"|ms [, callback]])

All the commands in this section take these two optional parameters.

If a string, speed must be one of slow, fast or normal. If a  number, it’s the duration in milliseconds.

Callback is called on completion of the animation.

.hide(…)
.show(…)

 

.toggle(…)

$("p").hide(1000, function(){$(this).show(1000);})

 

Toggle calls .hide or .show depending on whether the element’s current state is shown or hidden.

.slideDown(…)

.slideUp(…)

.slideToggle(…)

As they sound.

.fadeIn(…)

.fadeOut(…)

.fadeToggle(…)

As they sound.

 

Sample

Example / Meaning

.animate({params} [, duration [, easing [, callback]]])

Applies the specified CSS properties over time in a gradual manner, providing what amounts to an animation effect. Some of these properties can be relative (e.g. {left:"+=200"})

 

Duration & callback are as above.

 

?? No idea what easing is ??

 

Parameter is an ad-hock object containing the CSS properties to be animated (e.g.{marginLeft:"10em", fontSize:10em})

 

A call to .animate appears to be a queued (and non-blocking)

$('#myId').is(':animated')

Is the selected object undergoing animation?

 

DOM

Sample

Example / Meaning

.before(content) / .after(content)

Adds content as a pre / post-sibling

.append(content)

Adds context to the end of (but still within) the element

.appendTo("selector")

$("<i>Hello!</i>").appendTo("p");

.clone([includeEvents])

Returns a cloned copy of the selected elements. E.g. $("p").Clone().appendTo("body")

By default, includeEvents is false.

.empty()

Deletes all children and immediate content

.remove / .removeAttr / .removeClass

As they sound

.replaceAll / .replaceWith

 

.text

Sets or returns the text content of the selected elements.

.addClass / .removeClass /

.toggleClass

 

.css()

·  css(name) returns the value,

·  css(name,value) sets it.

·  css(name, function([index, existingValue]))
Calls a UDF for each match and sets the value to the return value of the UDF.

·  css({p:v, p2:v2 [,…]})
Sets multiple css properties at once

.height(), .offset(), .position(), .scrollTop(), .width(), etc

As they sound

.html()

.html(innerHtml)

Returns the inner HTML.
Sets the inner HTML

 

AJAX

jQuery includes comprehensive AJAX wrappers. Calls to jQuery's AJAX functions are all asynchronous (duh) and return an XHR object that can be polled / assigned a complete call funciton, but it's more common to specify the completion function in the call itself.

Sample

Example / Meaning

var xhr= $.get(url)

Makes an AJAX call.

var xhr= $.get(url, uploadData)

Makes an AJAX call passing uploadData to the server.

$.get(url, function(downloadData) {...})

Makes an AJAX call and calls the specified function with the returned data from the server when done.

$.get("navigation.xml"function (data) { alert(data.xml); });

$.ajax(object)

Same as $.get except the parameters come from a {url:url, data:data, success:successFn(data), dataType:dataType, ...} object parameter.

$(selector).load(url [,data [,callback]])

Makes an AJAX call and deposits the results in the selected element(s)

ajaxComplete, ajaxError, ajaxSend, ajaxStart, ajaxStop, etc

As they sound

$.getJSON(), $.getScript()

As they sound

 

Error Handling

An error handler can be assigned to the request only through the returned XHR object:

  var xhr = $.get("nosuchendpoint.xml"function (data) { alert(data.xml); });

  xhr.error(function (err) { alert("Error: " + JSON.stringify(err)); });

Since the call is $.get call is asynchronous, the error handler may be assigned after the error has occurred. In tis scenario, jQuery automatically calls the error handler when it is assigned.

Headers

TODO

Same Origin Policy & JSONP

Most browsers restrict the XHTTPRequest object to the same domain, subdomain and protocol. This can be worked around (at your own risk) via JSONP. In JSONP the client injects a new <script> tag into the DOM with the src attribute set to the target URL (e.g. http://differentdomain?jsonp=myMethod). Since <script> doesn't enforce same origin policy restrictions, the call goes through fine.

Instead of regular JSON the server returns the data wrapped in valid Javascript (this is where the P (padding) in JSONP comes from). For example, instead of {result: "hello world"} we could return ourClientHandler({result: "hello world"}). The result is that a (predefined) method on the client ends up being called without origin policy restrictions being invoked.

jQuery's $.getJSON and $.ajax methods will automatically issue a JSONP request if the url includes the string "callback=?".

Walked Example

$.getJSON("http://fred/getPerson?name=Joe&callback=?", function (data) {alert(JSON.stringify(data));});

1.       jQuery sees &callback=? in the URL and generates a random name to replace the '?' placeholder.

2.       jQuery attaches a temporary function (the equivalent of 'ourClientHandler') with this name to the window object.

3.       jQuery injects the <script> element with the crafted src attribute, trigging the call to the server.

4.       Server knows from the presence of callback=name on the URL that this is a JSONP call rather than a normal AJAX call.

5.       Server wraps the JSON result it would normally return in a Javascript call to the name method and returns that instead. For example, if http://fred/getPerson?name=Joe normally returns '{age: 20, weight:120}', then
http://fred/getPerson?name=Joe&callback=jsonHandler3213 would return 'jsonHandler3213({age: 20, weight: 120})'

6.       Browser completes download of the 'script', which executes immediately

7.       jQuery's temporary function is called and the data routed accordingly (i.e. to the success function specified in the $.getJSON call). The temporary function is removed.

When the call completes, the temporary function is deleted. This makes using JSONP (from the client side) almost identical to using vanilla AJAX JSON calls:

$.getJSON("http://someOtherDomain/blah?callback=?", function (data) {alert(JSON.stringify(data));});

jQuery is smart enough that if the call is to the same domain, it will issue a normal JSON/XHTTPRequest.

 

Misc

Sample

Example / Meaning

$(selector).toArray()

$(selector).size()

As they sound

$(selector).each(function([index[, element]]) {this…})

Calls the function for each element returned by the selector. The index and element reference are optional parameters. ‘this’ can also be used inside the function to refer to the element reference.

$(selector).get(n)

Gets the nth match

this.index()

$(selector).index(element)

Returns the index of this item in the selection.

Returns the index of this element in the selection.

.data("key", "value")

.data("key")

.removedata("key")

Saves an item of data against the element.

Reads an item of data from against the element.

Removes an item of data from the element.
[I don’t know how these are stored, but it doesn’t appear to be writing to the DOM model (i.e. this isn’t HTML5 data-* attributes)]

var newArray = $.map(array, function(arrayElement, arrayIndex))

For each element in the array, calls the provided function with that element's value and index. The non-null results returned from the function are returned as a new array. Example:

var a1 = [1, 2, 3, 4, 5, 6];

var a2 = $.map(a1, function(element, index) {

  if (element % 2 == 0) return null;

  return element;

});

 

Result: a2 = [1, 3, 5]

 

Tricks & Tips

·         $(document).ready(function() { xyz });
Runs the xyz query only after the document is fully loaded.

·         If some other library has hooked $, you can get assign the value of $ to another variable via jQuery.noConflict() [var myjq = jQuery.noConflict();]. Some thoughts on handling other libraries dependencies on different versions of jQuery: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

·         To hide text prior to a .fadeIn, set it to display:none