jQuery in Action
60
CHAPTER 3
Bringing pages to life with jQuery
One situation where the
toggleClass()
command is most useful is when we want
to switch visual renditions between elements quickly and easily. Remember the
zebra-stripe example of figure 1.1? What if we had some valid reason to swap
the colored background from the odd rows to the even rows (and perhaps back
again) when certain events occurred? The
zebra-stripe example of figure 1.1? What if we had some valid reason to swap
the colored background from the odd rows to the even rows (and perhaps back
again) when certain events occurred? The
toggleClass()
command would make
it almost trivial to add a class name to every other row, while removing it from
the remainder.
the remainder.
Let's give it a whirl. In the file chapter3/zebra.stripes.html, you'll find a copy
of the same page from chapter 1 with some minor changes. We added the follow-
ing function to the
ing function to the
<script>
element in the page header:
function swap() {
$('tr').toggleClass('striped');
}
This function uses the
toggleClass()
command to toggle the class named
stripe
for all
<tr>
elements. We also added calls to this function as the
onmouseover
and
onmouseout
attributes of the table:
<table onmouseover="swap();" onmouseout="swap();">
The result is that every time the mouse cursor enters or leaves the table, all
<tr>
elements with the class
striped
will have the class removed, and all
<tr>
elements
without the class will have it added. This (rather annoying) activity is shown in the
two parts of figure 3.2.
two parts of figure 3.2.
Manipulating the stylistic rendition of elements via
CSS
class names is a pow-
erful tool, but sometimes we want to get down to the nitty-gritty styles themselves
as declared directly on the elements. Let's see what jQuery offers us for that.
as declared directly on the elements. Let's see what jQuery offers us for that.
Command syntax: toggleClass
toggleClass(name)
Adds the specified class name if it doesn't exist on an element, or removes the name from
elements that already possess the class name. Note that each element is tested individu-
ally, so some elements may have the class name added, and others may have it removed.
elements that already possess the class name. Note that each element is tested individu-
ally, so some elements may have the class name added, and others may have it removed.
Parameters
name
(String) A string containing the class name to toggle.
Returns
The wrapped set.
The wrapped set.