The most common methods
So, now that you are somewhat familiar with jQuery’s power and syntax,
you should feel more comfortable working with it. Let me introduce you to a few
things that can help you along your way.
Two of the most used methods that jQuery has to offer. They find
elements inside other elements, and filter the collection, respectively.
<div id="foo" class="parent">
<div class="bar"></div>
<div class="bar"></div>
</div>
<div id="baz" class="parent">
<p class="bar"></p>
</div>
Let’s say I wanted to find all .bar elements
within all .parent elements…
// this will give you a collection with all three .bar elements
$(".parent").find(".bar");
// this will give you a collection with one .bar element
$("#baz").find(".bar");
Really useful, isn’t it? To accompany .find() we have .filter(), which doesn’t dig
into the elements you already have and look for others, it filters the elements
you already have in your collection.
// get all three .bar elements again, but filter out everything
// that isn't a `p` element, so we end up with just one element
$(".parent").find(".bar").filter("p");
$("#foo").on("click", function(evt) {
// do something when user clicks on
the #foo element
});
There’s also built-in support for event delegation, which is basically
that you bind an event on an element you know won’t change, instead of on
elements that might. Let’s go back to our markup again, the #foo element has
two .bar elements in it. Instead of
binding two events and break future .barelements to work
without having to bind a third, fourth, and fifth event; we use delegation. The
only thing different from the normal syntax in the code example above, is that
we add a parameter in the middle between the event type and the event handler,
and we originate the event from the parent, #foo, instead of
binding it directly to the .bar elements.
$("#foo").on("click", ".bar", function(evt) {
// do something when user clicks on
.bar elements,
// existing and future ones alike
});
While straight-up interaction with your webpage is nice, you often have
a need to pull in data asynchronously so that your user doesn’t constantly have
to refresh your page. This is done using $.ajax(), or some of its
helpers:
·
$.getJSON() - Same as above, but
automatically returns a JavaScript object with your data (instead of a string)
·
$.fn.load() - Loads data from an URL into
your jQuery collection
There are a few others, more obscure, that I’ll let you look up if
you want to know. First off, before
we go into detail on the different helpers; they all use $.ajax behind the
scenes, with predefined values. Everything you can do with the helpers, is
possible (and are done) with $.ajax().
To simply retrieve data from your server, you need a few properties to
send into $.ajax():
$.ajax({
url: "/some/path/mydata.html",
success: function(data) {
// do something with `data` that you
retrieved
// from the server
}
});
Introduced in jQuery 1.5, you can also do:
$.ajax({
url: "/some/path/mydata.html"
}).done(function(data) {
// do something with `data` that you
retrieved
// from the server
});
How this works is a bit out of scope for this article, but for now, just
imagine that it works exactly as the first example. I personally prefer the
second example, because it doesn’t clutter the AJAX, you can easily see what
you’re requesting, and how you do it, and what you do when the data has been
retrieved.
That said, let’s us look at how the helpers work. Remember, they all
use $.ajax() in the background.
$.get()
When you simply want to retrieve data, $.get() is your
friend. The simplest usage looks like this:
$.get("/some/path/mydata.html", function(data) {
// do something with `data` that you
retrieved
// from the server
});
It does support more parameters, but I think you can see that for
yourself should you ever need to use it on a more advanced level.
$.post()
This one is super useful if you ever need to submit a form, for example.
It does a lot of work for you so you don’t have to repeat yourself every time
you want to push data back to the server. Let’s say you have this form on your webpage:
<form method="post" action="/some/path/form.php" id="userform">
<label for="username">Username:</label>
<input id="username" name="username" />
<label for="password">Password:</label>
<input id="password" name="password" type="password" />
<input type="submit" />
</form>
When the form is submitted, we want to use AJAX to send that data over
to the server, instead of actually reloading the page and send the user
to form.php. First off, we’re going to bind
the submitevent on the form, and cancel that so
the browser doesn’t send the user to the action URL. Then
we’re going to serialize the form using $.fn.serialize() into a data format that is recognizable by
the server, and lastly, we send that data over.
// cache our form
var userform = $("#userform");
// bind the `submit` event
userform.on("submit", function(evt) {
// serialize the form
var data = userform.serialize();
// POST the data to the server using
the form's action URL
$.post(userform.attr("action"), data, function() {
// Data sent, let's clear the form
elements
userform.find("input, select, textarea").val("");
});
// Make sure the browser doesn't send
the user over
// to the action URL
evt.preventDefault();
});
It’s quite a bit more advanced than the other examples, but when you
understand this, you’ll have a much better image of how you can use jQuery to
do awesome things rather simple (especially compared to vanilla/normal
JavaScript).
I think that’s all for now, I hope you found this post somewhat useful
and please let me know if you have any questions, I’m @peolanha on twitter and peol on FreeNode
(IRC). I’d also like to thankAddy Osmani who reviewed
this article both linguistically and technically.