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

Posted February 27th, 2009 in Javascript

jQuery is a powerful Javascript library which makes adding useful Javascript stuff to your website easy across browsers. This post looks at how to show and hide an element with jQuery using the show(), hide(), toggle(), fadeIn() and fadeOut() functions.

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>

Basic hide and show

The most simple way to hide an element with jQuery is to call .hide() and then .show() to show it again. This makes the element instantly show or hide.

If we had a couple of buttons to hide and show the above paragraph they could look like this, although of course you'd normally attach events to a button in the docment ready function:

<input type="button" value="Hide" onclick="$('#example').hide()" />
<input type="button" value="Show" onclick="$('#example').show()" />

Here's the above example in action:

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

Controlling the speed

Control how quickly to hide and show the element by passing in 'slow' 'normal' or 'fast' or a decimal to indicate the number of milliseconds to make the animation last.

<input type="button" value="Hide - Slow" onclick="$('#example').hide('slow')" />
<input type="button" value="Hide - Normal" onclick="$('#example').hide('normal')" />
<input type="button" value="Hide - Fast" onclick="$('#example').hide('fast')" />
<input type="button" value="Hide - 2000" onclick="$('#example_2').hide(2000)" />

<input type="button" value="Show - Slow" onclick="$('#example').show('slow')" />
<input type="button" value="Show - Normal" onclick="$('#example').show('normal')" />
<input type="button" value="Show - Fast" onclick="$('#example').show('fast')" />
<input type="button" value="Show - 2000" onclick="$('#example').show(2000)" />

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

Other posts

Part 2 of this two part series looks at how the toggle, fadeIn and fadeOut functions work. There's also a later follow up post which shows how to hide an element initially with CSS and show it later with jQuery.

Comments