jQuery in Action
Showing and hiding elements
127
Have you ever looked at a website built in Flash and become envious because of all
the pretty effects that Flash developers have at their disposal? Heck, you might have
even become tempted to learn Flash purely for those slick effects.
the pretty effects that Flash developers have at their disposal? Heck, you might have
even become tempted to learn Flash purely for those slick effects.
Not long ago, smooth effects and animations weren't realistic options using
JavaScript. Between cross-browser issues and slow browser implementations, try-
ing to fade or zoom elements, or even move them around the screen, was extraor-
dinarily difficult. Thankfully, that state of affairs has passed, and jQuery provides
a trivially simple interface for doing all sorts of neat effects.
ing to fade or zoom elements, or even move them around the screen, was extraor-
dinarily difficult. Thankfully, that state of affairs has passed, and jQuery provides
a trivially simple interface for doing all sorts of neat effects.
But before we dive into adding whiz-bang effects to our pages, we need to con-
template the question: should we? Like a Hollywood blockbuster that's all special
effects and no plot, a page that overuses effects can elicit the opposite reaction
than we intended. Be mindful that effects should be used to enhance the usability
of a page, not hinder it.
effects and no plot, a page that overuses effects can elicit the opposite reaction
than we intended. Be mindful that effects should be used to enhance the usability
of a page, not hinder it.
With that caution in mind, let's see what jQuery has to offer.
5.1 Showing and hiding elements
we want to keep it simple and pop elements into existence or make them vanish!
The commands for showing and hiding elements are pretty much what we'd
expect:
show()
to show the elements in a wrapped set and
hide()
to hide them.
We're going to delay presenting their formal syntax for reasons that will
become clear in a bit; for now, let's concentrate on using these commands with
no parameters.
become clear in a bit; for now, let's concentrate on using these commands with
no parameters.
As simple as these methods may seem, we should keep a few things in mind.
First, jQuery hides elements by changing the
display
value of the
style
property
to
none
. If an element in the wrapped set is already hidden, it will remain hidden
but still be returned for chaining. For example, suppose we have the following
HTML
fragment:
<div style="display:none;">This will start hidden</div>
<div>This will start shown</div>
If we apply
$("div").hide().addClass("fun")
, we'll end up with the following:
<div style="display:none;" class="fun">This will start hidden</div>
<div style="display:none;" class="fun">This will start shown</div>