Show and hide an element with jQuery - Part 2 of 2

Posted March 1st, 2009 in Javascript

This post is the second of a two part post which look at how to show and hide an element with jQuery. The previous post looked at the show() and hide() functions and this post looks at the toggle(), fadeIn() and fadeOut() functions. See also my later post which shows how to hide an element initially with CSS and show it later with jQuery.

Example HTML

The following examples all use a paragraph that looks similar to this:

<p id="example">This is an example of text that will be shown and hidden.</p>

Toggling the element

Previously I looked at how to show and hide and element with jQuery using the show() and hide() functions. However, you can also simply toggle the element so it is shown if hidden and hidden if shown, use the toggle() function. It also supports the speed parameter that hide and show use.

<input type="button" value="Toggle" onclick="$('#example').toggle()" />
<input type="button" value="Slow" onclick="$('#example').toggle('slow')" />
<input type="button" value="Normal" onclick="$('#example').toggle('normal')" />
<input type="button" value="Fast" onclick="$('#example').toggle('fast')" />

This is an example of text that will be shown and hidden.

Fading in and out

And finally, you can also fade in and fade out. Again you can pass a speed parameter and I've done this using 'slow' below:

<input type="button" value="Fade Out" onclick="$('#example').fadeOut('slow')" />
<input type="button" value="Fade In" onclick="$('#example').fadeIn('slow')" />

This is an example of text that will be shown and hidden.

Conclusion

This is all fairly basic usage in these two post using these functions; you probably normally wouldn't show and hide elements from clicking buttons but it makes it easy to illustrate the point.

Common uses for showing and hiding stuff is when hovering over a navigation element and showing a sub-menu, or showing the shopping cart contents when clicking a shopping cart icon on an e-commerce page.

Comments