will return different results.
.
These three, you won’t be shocked to learn, are concerned with calculating the dimensions of an element in pixels. They both return the offset dimensions, which are the genuine dimensions of the element no matter how stretched it is by its inner content.
return dimensions as integers.
There’s actually another little-known difference that concerns IE (quelle surprise!), and it’s why you should avoid the
route. It has to do with the fact that IE, when asked to read “computed” (i.e. not implicitly set) dimensions, unhelpfully returns
. In jQuery core,
read correctly.
But if you’re working on elements with dimensions implicitly set, you don’t need to worry about that. So, if you wanted to read the width of one element and set it on another element, you’d opt for
, because the value returned comes ready appended with ‘px’.
with a view to performing a calculation on it, you’d be interested only in the figure; hence
is better.
. If you try this using the
method, you’ll get an error.
These are all concerned with binding events to elements. The differences lie in what elements they bind to and how much we can influence the event handler (or “callback”). If this sounds confusing, don’t worry. I’ll explain.
is the daddy of jQuery’s event-handling API. Most tutorials deal with events with simple-looking methods, such as
.
These lieutenants, or aliases, give you quick access to bind certain event types to the elements returned by the selector. They all take one argument: a callback function to be executed when the event fires. For example:
inside
#table
is clicked, alert its text content.
bind()
We can do the same thing with
bind
, like so:
1 | $( '#table td ' ).bind( 'click' , function () { |
2 | alert( "The TD you clicked contains '" +$( this ).text()+ "'" ); |
Note that this time, the event type is passed as the first argument to
bind()
, with the callback as the second argument. Why would you use
bind()
over the simpler alias functions?
Very often you wouldn’t. But
bind()
gives you more control over what happens in the event handler. It also allows you to bind more than one event at a time, by space-separating them as the first argument, like so:
1 | $( '#table td' ).bind( 'click contextmenu' , function () { |
2 | alert( "The TD you clicked contains '" +$( this ).text()+ "'" ); |
Now our event fires whether we’ve clicked the
with the left or right button. I also mentioned that
bind()
gives you more control over the event handler. How does that work? It does it by passing three arguments rather than two, with argument two being a data object containing properties readable to the callback, like so:
1 | $( '#table td' ).bind( 'click contextmenu' , {message: 'hello!' }, function (e) { |
As you can see, we’re passing into our callback a set of variables for it to have access to, in our case the variable
message
.
You might wonder why we would do this. Why not just specify any variables we want outside the callback and have our callback read those? The answer has to do with
scope and closures. When asked to read a variable, JavaScript starts in the immediate scope and works outwards (this is a fundamentally different behavior to languages such as PHP). Consider the following:
1 | var message = 'you left clicked a TD' ; |
2 | $( '#table td' ).bind( 'click' , function (e) { |
5 | var message = 'you right clicked a TD' ; |
6 | $( '#table td' ).bind( 'contextmenu' , function (e) { |
No matter whether we click the
with the left or right mouse button, we will be told it was the right one. This is because the variable
message
is read by the
alert()
at the time of the event firing, not at the time the event was bound.
If we give each event its
own “version” of
message
at the time of binding the events, we solve this problem.
1 | $( '#table td' ).bind( 'click' , {message: 'You left clicked a TD' }, function (e) { |
4 | $( '#table td' ).bind( 'contextmenu' , {message: 'You right clicked a TD' }, function (e) { |
Events bound with
bind()
and with the alias methods (
.mouseover()
, etc) are unbound with the
unbind()
method.
live()
This works almost exactly the same as
bind()
but with one crucial difference: events are bound both to current and future elements — that is, any elements that do not currently exist but which may be DOM-scripted after the document is loaded.
Side note: DOM-scripting entails creating and manipulating elements in JavaScript. Ever notice in your Facebook profile that when you “add another employer” a field magically appears? That’s DOM-scripting, and while I won’t get into it here, it looks broadly like this:
1 | var newDiv = document.createElement( 'div' ); |
2 | newDiv.appendChild(document.createTextNode( 'hello, world!' )); |
3 | $(newDiv).css({width: 100, height: 100, background: '#f90' }); |
4 | document.body.appendChild(newDiv); |
delegate()
A shortfall of
live()
is that, unlike the vast majority of jQuery methods,
it cannot be used in chaining. That is, it must be used directly on a selector, like so:
1 | $( '#myDiv a' ).live( 'mouseover' , function () { |
But not…
1 | $( '#myDiv' ).children( 'a' ).live( 'mouseover' , function () { |
… which will fail, as it will if you pass direct DOM elements, such as
$(document.body)
.
delegate()
, which was developed as part of jQuery 1.4.2, goes some way to solving this problem by accepting as its first argument a context within the selector. For example:
1 | $( '#myDiv' ).delegate( 'a' , 'mouseover' , function () { |
Like
live()
,
delegate()
binds events both to current and future elements. Handlers are unbound via the
undelegate()
method.
Real-Life Example
For a real-life example, I want to stick with DOM-scripting, because this is an important part of any RIA (rich Internet application) built in JavaScript.
Let’s imagine a flight-booking application. The user is asked to supply the names of all passengers travelling. Entered passengers appear as new rows in a table,
#passengersTable
, with two columns: “Name” (containing a text field for the passenger) and “Delete” (containing a button to remove the passenger’s row).
To add a new passenger (i.e. row), the user clicks a button,
#addPassenger
:
01 | $( '#addPassenger' ).click( function () { |
02 | var tr = document.createElement( 'tr' ); |
03 | var td1 = document.createElement( 'td' ); |
04 | var input = document.createElement( 'input' ); |
07 | var td2 = document.createElement( 'td' ); |
08 | var button = document.createElement( 'button' ); |
09 | button.type = 'button' ; |
10 | $(button).text( 'delete' ); |
11 | $(td2).append(button); |
14 | $( '#passengersTable tbody' ).append(tr); |
Notice that the event is applied to
#addPassenger
with
click()
, not
live('click')
, because we know
this button will exist from the beginning.
What about the event code for the “Delete” buttons to delete a passenger?
1 | $( '#passengersTable td button' ).live( 'click' , function () { |
2 | if (confirm( "Are you sure you want to delete this passenger?" )) |
3 | $( this ).closest( 'tr' ).remove(); |
Here, we apply the event with
live()
because the element to which it is being bound (i.e. the button) did not exist at runtime; it was DOM-scripted later in the code to add a passenger.
Handlers bound with
live()
are unbound with the
die()
method.
The convenience of
live()
comes at a price: one of its drawbacks is that you cannot pass an object of multiple event handlers to it. Only one handler.
5. .children() vs. .find()
Remember how the differences between
parent()
,
parents()
and
closest()
really boiled down to a question of reach? So it is here.
children()
This returns the immediate children of an element or elements returned by a selector. As with most jQuery DOM-traversal methods, it is optionally filtered with a selector. So, if we wanted to turn all
s orange in a table that contained the word “dog”, we could use this:
1 | $( '#table tr' ).children( 'td:contains(dog)' ).css( 'background' , '#f90' ); |
find()
This works very similar to
children()
, only it looks at both children and more distant descendants. It is also often a safer bet than
children()
.
Say it’s your last day on a project. You need to write some code to hide all
s that have the class
hideMe
. But some developers omit
from their table mark-up, so we need to cover all bases for the future. It would be risky to target the
s like this…
1 | $( '#table tbody tr.hideMe' ).hide(); |
… because that would fail if there’s no
. Instead, we use
find()
:
1 | $( '#table' ).find( 'tr.hideMe' ).hide(); |
This says that wherever you find a
in
#table
with
.hideMe
, of whatever descendancy, hide it.
6. .not() vs. !.is() vs. :not()
As you’d expect from functions named “not” and “is,” these are opposites. But there’s more to it than that, and these two are
not really equivalents.
.not()
not()
returns elements that do not match its selector. For example:
1 | $( 'p' ).not( '.someclass' ).css( 'color' , '#f90' ); |
That turns all paragraphs that do
not have the class
someclass
orange.
.is()
If, on the other hand, you want to target paragraphs that
do have the class
someclass
, you could be forgiven for thinking that this would do it:
1 | $( 'p' ).is( '.someclass' ).css( 'color' , '#f90' ); |
In fact, this would cause an error, because
is()
does not return elements: it returns a boolean. It’s a testing function to see whether any of the chain elements match the selector.
So when is
is
useful? Well, it’s useful for querying elements about their properties. See the real-life example below.
:not()
:not()
is the pseudo-selector equivalent of the method
.not()
It performs the same job; the only difference, as with all pseudo-selectors, is that you can use it in the middle of a selector string, and jQuery’s string parser will pick it up and act on it. The following example is equivalent to our
.not()
example above:
1 | $( 'p:not(.someclass)' ).css( 'color' , '#f90' ); |
Real-Life Example
As we’ve seen,
.is()
is used to test, not filter, elements. Imagine we had the following sign-up form. Required fields have the class
required
.
01 | < form id = 'myform' method = 'post' action = 'somewhere.htm' > |
03 | < input type = 'text' class = 'required' /> |
06 | < input type = 'text' class = 'required' /> |
11 | < label >Desired username * |
12 | < input type = 'text' class = 'required' /> |
14 | < input type = 'submit' value = 'GO' /> |
When submitted, our script should check that no required fields were left blank. If they were, the user should be notified and the submission halted.
1 | $( '#myform' ).submit( function () { |
2 | if ($( this ).find( 'input' ).is( '.required[value=]' )) { |
3 | alert( 'Required fields were left blank! Please correct.' ); |
Here we’re not interested in returning elements to manipulate them, but rather just in querying their existence. Our
is()
part of the chain merely checks for the existence of fields within
#myform
that match its selector. It returns true if it finds any, which means required fields were left blank.
7. .filter() vs. .each()
These two are concerned with iteratively visiting each element returned by a selector and doing something to it.
.each()
each()
loops over the elements, but it can be used in two ways. The first and most common involves passing a callback function as its only argument, which is also used to act on each element in succession. For example:
1 | $( 'p' ).each( function () { |
This visits every
in our document and alerts out its contents.
But
each()
is more than just a method for running on selectors: it can also be used to handle
arrays and array-like objects. If you know PHP, think
foreach()
. It can do this either as a method or as a core function of jQuery. For example…
1 | var myarray = [ 'one' , 'two' ]; |
2 | $.each(myarray, function (key, val) { |
3 | alert( 'The value at key ' +key+ ' is ' +val); |
… is the same as:
1 | var myarray = [ 'one' , 'two' ]; |
2 | $(myarray).each( function (key, val) { |
3 | alert( 'The value at key ' +key+ ' is ' +val); |
That is, for each element in
myarray
, in our callback function its key and value will be available to read via the
key
and
val
variables, respectively. The first of the two examples is the better choice, since it makes little sense to pass an array as a jQuery selector, even if it works.
One of the great things about this is that you can also iterate over objects — but only in the first way (i.e.
$.each
).
jQuery is known as a DOM-manipulation and effects framework, quite different in focus from other frameworks such as MooTools, but
each()
is an example of its occasional foray into extending JavaScript’s native API.
.filter()
filter()
, like
each()
, visits each element in the chain, but this time to remove it from the chain if it doesn’t pass a certain test.
The most common application of
filter()
is to pass it a selector string, just like you would specify at the start of a chain. So, the following are equivalents:
1 | $( 'p.someClass' ).css( 'color' , '#f90' ); |
2 | $( 'p' ).filter( '.someclass' ).css( 'color' , '#f90' ); |
In which case, why would you use the second example? The answer is, sometimes you want to affect element sets that you cannot (or don’t want to) change. For example:
1 | var elements = $( '#someElement div ul li a' ); |
3 | elements.filter( '.someclass' ).css( 'color' , '#f90' ); |
elements
was set long ago, so we cannot — indeed may not wish to — change the elements that return, but we might later want to filter them.
filter()
really comes into its own, though, when you pass it a filter function to which each element in the chain in turn is passed.
Whether the function returns true or false determines whether the element stays in the chain. For example:
1 | $( 'p' ).filter( function () { |
2 | return $( this ).text().indexOf( 'hello' ) != -1; |
Here, for each
found in the document, if it contains the string
hello
, turn it orange. Otherwise, don’t affect it.
We saw above how
is()
, despite its name, was not the equivalent of
not()
, as you might expect. Rather,
use filter()
or has()
as the positive equivalent of not()
.
Note also that unlike
each()
,
filter()
cannot be used on arrays and objects.
Real-Life Example
You might be looking at the example above, where we turned
s starting with
hello
orange, and thinking, “But we could do that more simply.” You’d be right:
1 | $( 'p:contains(hello)' ).css( 'color' , '#f90' ) |
For such a simple condition (i.e. contains
hello
), that’s fine. But
filter()
is all about letting us perform more complex or long-winded evaluations before deciding whether an element can stay in our chain.
Imagine we had a table of CD products with four columns: artist, title, genre and price. Using some controls at the top of the page, the user stipulates that they do not want to see products for which the genre is “Country” or the price is above $10. These are two filter conditions, so we need a filter function:
1 | $( '#productsTable tbody tr' ).filter( function () { |
2 | var genre = $( this ).children( 'td:nth-child(3)' ).text(); |
3 | var price = $( this ).children( 'td:last' ).text().replace(/[^\d\.]+/g, '' ); |
4 | return genre.toLowerCase() == 'country' || parseInt(price) >= 10; |
So, for each
inside the table, we evaluate columns 3 and 4 (genre and price), respectively. We know the table has four columns, so we can target column 4 with the
:last
pseudo-selector. For each product looked at, we assign the genre and price to their own variables, just to keep things tidy.
For the price, we replace any characters that might prevent us from using the value for mathematical calculation. If the column contained the value
$14.99
and we tried to compute that by seeing whether it matched our condition of being below $10, we would be told that it’s not a number, because it contains the $ sign. Hence we strip away everything that is not number or dot.
Lastly, we return true (
meaning the row will be hidden) if either of our conditions are met (i.e. the genre is country or the price is $10 or more).
filter()
8. .merge() vs. .extend()
Let’s finish with a foray into more advanced JavaScript and jQuery. We’ve looked at positioning, DOM manipulation and other common issues, but jQuery also provides some utilities for dealing with the native parts of JavaScript. This is not its main focus, mind you; libraries such as MooTools exist for this purpose.
.merge()
merge()
allows you to merge the contents of two arrays into the first array. This entails
permanent change for the first array. It does not make a new array; values from the second array are appended to the first:
1 | var arr1 = [ 'one' , 'two' ]; |
2 | var arr2 = [ 'three' , 'four' ]; |
After this code runs, the
arr1
will contain four elements, namely
one
,
two
,
three
,
four
.
arr2
is unchanged. (If you’re familiar with PHP, this function is equivalent to
array_merge()
.)
.extend()
extend()
does a similar thing, but for objects:
1 | var obj1 = {one: 'un' , two: 'deux' } |
2 | var obj2 = {three: 'trois' , four: 'quatre' } |
extend()
has a little more power to it. For one thing, you can merge more than two objects — you can pass as many as you like. For another, it can merge recursively. That is, if properties of objects are themselves objects, you can ensure that they are merged, too. To do this, pass
true
as the first argument:
1 | var obj1 = {one: 'un' , two: 'deux' } |
2 | var obj2 = {three: 'trois' , four: 'quatre' , some_others: {five: 'cinq' , six: 'six' , seven: 'sept' }} |
3 | $.extend( true , obj1, obj2); |
Covering everything about the behaviour of JavaScript objects (and how merge interacts with them) is beyond the scope of this article, but you can
read more here.
The difference between
merge()
and
extend()
in jQuery is
not the same as it is in MooTools. One is used to amend an existing object, the other creates a new copy.
There You Have It
We’ve seen some similarities, but more often than not intricate (and occasionally major) differences. jQuery is not a language, but it deserves to be learned as one, and by learning it you will make better decisions about what methods to use in what situation.
It should also be said that this article does not aim to be an exhaustive guide to all jQuery functions available for every situation. For DOM traversal, for example, there’s also nextUntil() and parentsUntil().
While there are strict rules these days for writing semantic and SEO-compliant mark-up, JavaScript is still very much the playground of the developer. No one will demand that you use
click()
instead of
bind()
, but that’s not to say one isn’t a better choice than the other. It’s all about the situation.