jQuery

  • jquery.js
  • Originally written by John Resig
<script type="text/javascript" src="jquery.js"></script>
<!-- Load jQuery using the Google Ajax Libraries API -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.3.2");</script>
  • Uses Sizzle (CSS selector engine, which originated in jQuery)

jQuery functions

  • $ is an alias for the jQuery namespace
// The following are equivalent
$.trim(str);
jQuery.trim(str);
  • $. is used for utility functions
$.someFunction()

$()

$(selector [, context])
  • Acts on a CSS selector
  • Returns the set of matching elements, as a jQuery object
  • Each element in the set is an HTML DOM object
$("p.foo").addClass("bar");                     // For every p with class "foo", add class "bar"
$("div.test").add("p.quote").addClass("blue")   // For every div.test or p.quote, add class "blue"

$.each()

$.each( obj, function(key, value){...} );   // Comparable to: for (var key in obj) { var value = obj[key]; ...}
$.each([4,5,6], function(i){ document.write(this); });   // Output: 456, i is 0-based and optional

$().each()

$("p.foo").each(function(i){ var dom = this; var jo = $(this); ... })   // i is 0-based and optional

$.extend()

$.extend(destObj, srcObj);         // Add the properties and methods in srcObj to destObj
$.extend(true, destObj, srcObj);   // Deep copy
$.extend(srcObj);                  // Add the properties and methods in srcObj to the jQuery object

Adding jQuery functions

  • jQuery.fn is an alias for jQuery.prototype

$.foo()

jQuery.foo = function() { ... };

$().foo()

// Act on the first matching element
jQuery.fn.foo = function() {
    var dom = this[0]; var jo = jQuery(this[0]); ...
};
// Act on all matching elements
jQuery.fn.foo = function() {
    return this.each(function(){
        var dom = this; var jo = jQuery(this); ...
    });
};

Ajax

$.ajax()

  • Request the output for the specified URL
$.ajax({
    url: 'index.php',
    type: 'POST',                   // 'POST', 'GET'
    data: 'apple=red&lime=green',
    dataType: 'text',               // 'text', 'xml', 'json'  (Default: 'text')
    timeout: 1000,
    success: function(data){ ... },
    error: function(){ ... }
});
Accessing the data
data              // text
$(data)           // XML
data.myProperty   // JSON

load()

  • Update the specified DOM element using the output from the specified URL
$('#myId').load('data.txt');

Misc

Running code when the page has loaded

$(document).ready(function() {
    myfunc();
});

Misc functions

  • addClass("one two")
  • hasClass("one")
  • removeClass("one two")
  • toggleClass("one")
  • toggleClass("one", bool)

 

Resources URL: 
notes/javascript/resources
Sources URL: 
notes/javascript/sources

See Also