Introduction to jQuery
What is jQuery?
- An open source JavaScript library that simplifies the interaction between HTML and JavaScript.
- Created by John Resig in 2005, released in January of 2006.
- Built in an attempt to simplify the existing DOM APIs and abstract away cross-browser issues.
Why jQuery?
- Fully documented.
- Great community.
- Tons of plugins.
- Small size (23kb)
- Everything works in IE 6+, Firefox 2+, Safari 3+, Chrome, and Opera 9+
Who uses jQuery?
- Microsoft, Google, Mozilla, IBM, Amazon, HP, Intel.
- Ruby on Rails, Wordpress, Django, Drupal, CakePHP, ASP.NET MVC.
- Everyone can agree that jQuery is awesome.
jQuery is pretty popular.
- 26.95% of all sites use jQuery (see Builtwith.com).
- Google Trends
Easy to learn and master
- Uses CSS to layer functionality.
- Easy to separate behavior.
- Quick, terse, syntax.
The Focus of jQuery
$("div").addClass("special");
- Find some elements.
- Do something with them.
- Note: All jQuery methods, in the examples, are linked to the documentation.
The jQuery Object
$("div").addClass("special");
$
is the jQuery Object (also named jQuery
)
"div"
finds some elements using CSS selectors
$("div")
returns a jQuery set (containing 0 to many DOM nodes).
addClass(...)
modifies all the divs
Graceful Scripting
$(".idontexist").addClass("special");
- jQuery will gracefully fail when it can't find anything to run against.
- Works just like CSS - write your queries to match what you want, doesn't break when nothing is found.
Ready Event
$(document).ready(function(){
// Your jQuery code goes in here
});
- In order to traverse and manipulate the page we must wait until it's ready to be used.
- jQuery has a ready event that fires the instant the DOM is ready to be worked with.
- Stick all your jQuery code in a ready block, load it unobtrusively.
Find Some Elements
- CSS Selector 1-3 support.
- Better CSS Selector support than most browsers.
- Plus a bunch of custom selectors that make life easier.
- (Such as :first, :last, :has(), :visible, :hidden)
Selectors in jQuery
<div id="body">
<h2>Some Header</h2>
<div class="contents">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
</div>
Traversing
$("button").parent().css("border", "3px solid red");
- Sometimes CSS selectors alone aren't enough.
- jQuery provides a full suite of methods for walking the DOM tree.
- .parent(), .next(), .prev(), .children(), .siblings() and many more.
Chaining
- You can have multiple actions against a single set of elements.
- Every jQuery method returns the jQuery set, for further actions (unless a value is returned).
$("div").hide();
$("div").hide().css("color","blue");
$("div").hide().css("color","blue").remove();
Chained Traversal
$("button")
.parent().css("border", "3px solid red")
.siblings().css("border", "3px solid green");
- Sometimes CSS selectors alone aren't enough.
- jQuery provides a full suite of methods for walking the DOM tree.
- .parent(), .next(), .prev(), .children(), .siblings() and many more.
Do something with them
- Now that we've found the elements we're looking for, let's change them!
- Attributes (addClass, attr)
- CSS (css)
- Manipulation (append, prepend, remove, clone)
- Events (click, hover, toggle)
- Effects (hide, show, slideDown, fadeOut)
- Ajax (load, get, post)
Manipulation - .after()
$("a[target=_blank]")
.after("<img src='open.png'/>");
Manipulation - .append()
$("a[target=_blank]")
.append(" (Opens in New Window)");
Manipulation - .css()
$("li a").css({
color: "red",
fontWeight: "bold"
});
HTML Selector
$("<li><a></a></li>")
.find("a")
.attr("href", "http://ejohn.org/")
.html("John Resig")
.end()
.appendTo("ul");
Event - .submit()
$("form").submit(function(){
if ( $("#name").val() === "" ) {
$("span.help").show();
return false;
}
});
Event - .click()
$("a.menu").click(function(){
$(this).next().toggle();
return false;
});
Event - .hover()
$("li").hover(function(){
$(this).animate({marginLeft: 38, marginRight: 0});
}, function(){
$(this).animate({marginLeft: 18, marginRight: 18});
});
- Hover uses the
mouseenter
and mouseleave
events.
- These events detect when a user enters or leaves an element.
- Works better than
mouseover
and mouseout
.
Event Delegation
- Event delegation is an efficient way to watch for an event on a large number of elements.
- Works by binding to a point farther up the DOM tree and watching for bubbling events.
- jQuery has two ways to do event delgation:
.live()
(as a direct replacement for .bind()) and .delegate()
.
- Works on all current, and future, elements.
Live Events
$("a.menu").live("hover", function(){
$(this).next().toggle(200);
return false;
});
Effect - .slideToggle()
$("a.menu").click(function(){
$(this).next().slideToggle("slow");
return false;
});
Effect - .animate()
$("div.block").animate({
fontSize: "2em",
width: "+=20%",
backgroundColor: "green"
});
hello!
Effect - .hide()/.show()
$("div.block").hide("slow", function(){
$(this).show("slow");
});
hello!
Ajax - Load XML
$.ajax({
url: "file.xml",
success: function( xml ) {
$(xml).find("tab").each(function(){
$("ul").append(
"<li>" + $(this).text() + "</li>");
});
}
});
Ajax - Get JSON
$.getJSON("file.js", function( obj ) {
for ( var prop in obj ) {
$("ul").append(
"<li>" + prop + ": " + obj[prop] + "</li>");
}
});
Ajax - .load()
$("div.load").load("file.html");
hello!
Ajax - .load()
$("div.load").load("file.html h2");
hello!
jQuery Plugins
- jQuery provides a simple, intuitive, format for writing drop-in plugins.
- All hosted in the jQuery plugin repository: http://plugins.jquery.com/
- Thousands of plugins have been written, covering all aspects of web apps.
- Some good ones: jQuery UI, Validation, Ajax Form, jqGrid, jQuery Tools.
Developing a Plugin
jQuery.fn.slideRemove = function() {
return this.slideUp("slow", function(){
$(this).remove();
});
};
$("li.remove").slideRemove();
- A simple plugin that hides an element and then removes it.
- (I'm going to be removed when run.)
What Makes a Plugin?
- Most jQuery plugins are just adding in a new method to the jQuery set.
- The methods need to return the jQuery set (likely 'this').
- Can also add in new selectors.
jQuery.expr[":"].unordered = function(elem) {
return elem.parentNode.nodeName.toLowerCase() === "ul";
};
jQuery UI
- A complete set of themed, cross-browser, user interface components.
- Drag, Drop, Sort, Select, Resize Accordion, Datepicker, Dialog, Slider, Tabs
- New in 1.8: Button, Autocomplete
- More info: http://jqueryui.com/
jQuery CDN
<script src='http://code.jquery.com/jquery.js'></script>
- jQuery, Google, and Microsoft all host jQuery on their CDNs.
- Automatically minified, gzipped, and geopositioned for performance.
Minified and Gzipped
- The best way to transfer JavaScript.
- Minification removes comments, whitespace, and makes other optimizations (Google Closure, YUIMin, and Packer).
- Gzipping that output compresses the filesize even further.
- jQuery goes from 150KB+ down to ~20KB.
jQuery Books
- Learning jQuery 1.3 (and jQuery 1.4 Reference Guide)
- jQuery in Action (2nd edition)
- jQuery Cookbook (O'Reilly)