What is jQuery?
jQuery is a client-side JavaScript library that abstracts away browsers’
different implementations into an easy-to-use API. What jQuery does best is to
interact with the DOM (add, modify, remove elements on your page), do AJAX
requests, create effects (animations) and so forth. It does not provide
an application framework, it’s merely a tool amongst others that should be used
what it’s meant to be used for. However, there’s a plethora of plugins due to a
thriving community, and there’s pretty much a plugin for anything you can think
of.
Recently, it also set a new usage record with being used on 54
per cent of Alexa’s top 17,000 most visited websites, while Flash was
“only” at 47 per cent.
Before we continue, I’d like to quote @johanbrook who, when I
asked what I should mention to people that might not have used jQuery before,
said: Don’t go to bed with it. That said, jQuery is still the best
library for DOM manipulation, AJAX and effects and in this article you’ll find
out why.
How do I use jQuery?
First off, you should learn some basics. jQuery, like many other
libraries, uses the global $ variable as a shortcut. Basically, window.jQuery ===
window.$ (and therefore, $("div") and jQuery("div") are
identical. You can use whichever you prefer, but $ is shorter
and neater, it also provides better readability since it’s easier to spot
than jQuery, which is a more conventional name
for a variable (being plain text). There are two parts to jQuery. There are
methods which run on collections and rely on $.fn (a shortcut
for $.prototype). There are then utility methods
which run directly on $—for example $.data() and $.ajax(), which don’t require a collection to
work.
Using selectors and instance methods
jQuery sports a CSS3 selector engine called Sizzle, which means that
more or less all selectors you use in your stylesheet can be applied to the DOM
to query for elements matching them. Consider the following markup:
<div id="foo">
<div class="bar"></div>
<div class="bar"></div>
</div>
<div id="baz"></div>
In CSS, to select the div element with
id foo, you’d use #foo {}. That’s exactly
what you do with jQuery as well. We use the $ shortcut we
talked about earlier, and use it as a function, which will query the DOM and
return a new jQuery instance, allowing us to operate on said collection: $("#foo").
So, let’s try to modify #foo, and give it a
background.
$("#foo").css("background-color", "red");
Here, we simply used the $.fn.css() method to set the background
to red. But what about if I wanted to do more? Maybe I
would like to set the font-weight to bold? This is where
object literals come in handy, most of jQuery’s methods allow you to send in an
object containing several values instead of repeating method calls:
$("#foo").css("background-color", "red");
$("#foo").css("font-weight", "bold");
// becomes:
$("#foo").css({
"background-color": "red",
"font-weight": "bold"
});
Now, wasn’t that easy? As I said, you can use this on several methods
like $.fn.attr(), $.fn.prop()and so on.
Another thing to note here is that while I in my example used
repeated $("#foo"), you shouldn’t. It’s considered bad
practice since you will be creating a new jQuery instance each time, and also
query the DOM twice. Good practice states that you should always cache your
collection whenever possible, if you’re using it more than once. So instead of
this:
$(".bar").css("color", "blue");
// lots of code
$(".bar").appendTo("#baz");
we should cache $(".bar") in a
variable, so we can re-use it later:
var bars = $(".bar");
bars.css("color", "blue");
// lots of code
bars.appendTo("#baz");
Now we’re entering one of jQuery’s most powerful features, chaining.
Let’s imagine for a second that there was no // lots of code separating
the two jQuery method calls.
var bars = $(".bar");
bars.css("color", "blue");
bars.appendTo("#baz");
It works, it’s readable, but we can do better. jQuery’s methods, except
for a select few, returns the jQuery-wrapped collection you operated on. This
means we can chain method calls together, instead of having to repeat the
collection/variable reference. This also means that we can skip the varstatement in this
example.
$(".bar").css("color", "blue").appendTo("#baz");
You can go nuts with chaining, I’ve seen some mad chaining in my days
and can be messy if you don’t format it correctly. Sometimes, it’s even better
to use multiple variable references to ease readability for other developers.
Consider this example:
$("#foo").css("color", "red")
.click(function(){ /* event handler */ })
.mousedown(function(){ /* event handler */ })
.mouseup(function(){ /* event handler */ })
.attr("id", "my-new-id")
.find(".child")
.css("color", "blue")
.mouseup(function(){ /*...*/ });
That’s a lot of new information at once, I know, but if we ignore what
the actual method calls do for now and look at how the indentation follows the
flow of the actual code instead, we can see exactly were we’re modifying our
collection ($.fn.find()), and what we’re doing after we
modified it. It’s just something you should keep in mind when you start
chaining like a mad man—readability should always be a priority, someone will
be maintaining your code and shouldn’t be spending hours trying to figure out
what is happening.
Making sure the document is ready
One thing that I see several times a week in the #jQuery help channel on
FreeNode, is people misunderstanding how the DOM works. The browser basically
has to parse the entire markup you gave it and the DOM hierarchy before you can
interact with it. This can be tricky, especially if you’re using jQuery because
it won’t tell you when you, for example, try to change a background color on an
element and the collection were empty. Querying the DOM before it’s ready will
leave you at risk for problems like these, where you see that you have an
element with id foo in the document, but nothing happens when you
run your code and you yell at jQuery because it’s not working.
$(document).ready(function() {
// everything in here will be run
when the DOM is
// ready to be interacted with
$(".bar").css("color", "blue").appendTo("#baz");
});
You should really remember this, it’s an easy mistake
and we all do it every now and then.

0 on: "What is jQuery? How do I use jQuery?"