6. // Collections!
var $collection = jQuery("a[rel=userprofile]");
// $collection is a jQuery collection.
// It can have 0 or more elements.
$collection.addClass("foo");
// API functions apply to all elements in the
// collection.
var p = document.getElementById("myUserProfile");
var $collection2 = jQuery(p);
// $collection2 is a jQuery collection.
// It has 1 element.
7. var $hi = jQuery("<p>Hello, world.</p>");
// $hi is also a jQuery collection,
// containing 1 element.
console.log($collection.length);
// The number of elements in $collection.
console.log($collection[0]);
// The first DOM element in $collection.
8. //methods on the same collection
$collection.attr("hreflang", "fr");
// Sets the "hreflang" attribute on *all*
// elements in $collection.
$collection.attr("href");
// Gets the "href" attribute of the
// *first* element in $collection.
9. //script execution and DOM Ready
console.log(
jQuery("input[type=checkbox]").length
); // => 0
// The page has only loaded enough
// elements to get to this <script>.
jQuery(function() {
// This function is called when the page
// has fully loaded.
console.log(
jQuery("input[type=checkbox]").length
); // => 6
});
10. //events
function handleEvent(event) {
console.log(this);
// The element clicked,
// not a jQuery collection
event.preventDefault();
// Prevent the default action of this
// event.
}
$collection.bind("click", handleEvent);
// handleEvent is called when any element
// in $collection is clicked.
$collection.unbind("click", handleEvent);
11. //when I say stop I mean…
$collection.bind("keydown",
function(event) {
event.stopPropagation();
event.stopImmediatePropagation();
return false;
// Avoid these.
// This breaks the key rule that
// event handlers should be agnostic
// of other event handlers.
});
13. //bind to arbitrary objects
MyApp.ISSUES = {};
jQuery(MyApp.ISSUES).bind("add_issue",
function(newIssue) {
// Handle adding new issues
});
// jQuery(MyApp.ISSUES) is a jQuery
// collection containing the JavaScript
// object MyApp.ISSUES.
var newIssue = new Issue(newIssueId);
jQuery(MyApp.ISSUES).trigger("add_issue",
[newIssue]);
// The second argument to trigger() is an
// array of arguments to supply listeners.
15. //store data against DOM nodes
// Set data:
jQuery.data(obj, "key", "value");
// Get data:
jQuery.data(obj, "key"); // => "value"
//
//
//
//
obj can be any DOM element or
JavaScript object.
The key can be any string.
The value can be any type.