Slides from my presentation to the Auckland Web Meetup on 15 September 2011. The interactive demos haven’t translated well to PDF. (Downloading disabled to comply with typeface EULA, but I can email you a copy if you drop me a line.)
19. OBJECTS
For example
$("div").hover(function() {
$(this).addClass("on");
}, function() {…});
20. CORE
Code is generally run when DOM is ready
window.onload = function(){…}
$(document).ready(function(){…});
Can be called repeatedly, and shortened to
$(function(){…});
21. CORE
jQuery deals in ‘collections’ of
one or more objects, so
$("ul li")
returns a collection of all
matching elements
22. CORE
Some JavaScript properties
work with collections
$("ul li").length
As well as array indices to isolate
individual DOM nodes
$("ul li")[0]
23. TIP
When assigning jQuery collections
to variables, prefix with $
var $myList = $("#mylist");
Useful reminder as to a variable’s type.
24. CORE
jQuery uses JavaScript syntax for
conditional statements, loops, etc.
if (this > that) {
$("nav").hide();
} else {…}
25. METHODS
Now for the cool stuff.
Call jQuery methods to manipulate
objects, data and collections
$("ul li").slideDown()
$("ul li").addClass()
54. METHODS
As well as methods for…
Array handling
Forms manipulation
File parsing
Feature detection
and more…
55. CHAINING
Most methods return the same jQuery
collection, and can be chained in sequence
$("div:hidden")
.text("Error")
.css("color","red")
.fadeIn();
56. CHAINING
If a method returns a new collection, return
to the previous collection using end()
$("div").find("a")
.addClass("mute")
.end()
.find("b").hide();
57. CALLBACKS
Some methods allow more code to be
executed once they complete (a ‘callback’)
$("div").animate(
{top: 50},
function() {…}
);
58. DEMO
Given the following markup
<p>…</p>
how might we show the user a
success message above the text?
59. DEMO
One solution
var message = "Page saved";
$("<div>", {class: "msg"})
.text(message)
.insertBefore("p")
.hide().fadeIn();
63. PLUGINS
Plugins allow you to extend the jQuery
model to include new methods.
Galleries, lightboxes
Form validation, input masks
Layout control
Drag & drop, sliders, calendars, etc.
64. PLUGINS
Creating your own plugin is easy
$.fn.addIcon = function() {
return this.prepend(
$("<span>", {class: "icon"})
);
}