Documentation

Tutorials:Basic Show and Hide

From jQuery JavaScript Library

Jump to: navigation, search

An introduction to hiding, showing, and toggling the display of elements.

Original: http://www.learningjquery.com/2006/09/basic-show-and-hide
Author: Karl Swedberg

Similar Tutorials: EffectsTraversing

In this tutorial, I'll be showing you a simple effect that you can do using jQuery: showing or hiding something, or a group of things, on the page. The two functions that let us do this are, not surprisingly, show() and hide(). jQuery also comes with another function called toggle(), which will make matching elements visible if they are hidden or hidden if they are visible.

So, let's get down to business. We're going to start with our $(document).ready() function.

 $(document).ready(function() {
   // we'll put our code here
 });

Next, we'll choose what we want to show or hide. Hmm, let's see. How about the site's title? Excellent! Now, whenever we refer to an element in jQuery, we start with the dollar sign, $, and we put any CSS or XPATH selector in parentheses right after it: $('css-selector')

Since the site's title is wrapped in an <h1> tag, we'll refer to it this way: $('h1'). We could just as easily refer to all DIVs with a class of "treacle" — $('div.treacle') — or any paragraph that is a chlid of a DIV with an ID of "bonespur" — $('#bonespur > p').

Now for the magic. To make the site's title disappear, we just connect $('h1') and hide() with a dot (.) and stick it all inside the $(document).ready() like so:

 $(document).ready(function() {
   $('h1').hide();
 });

The code above will make the site's title hide when the DOM / page loads, which isn't ideal for our purposes here, so I'm going to attach the the hide() event to the first button below instead. The second and third buttons will handle show() and toggle() respectively.

Just for kicks, we'll show and hide this sentence, which is wrapped in a div with class="showide", too.

The complete code to run this example looks like this:

 $(document).ready(function() {
   $('#hideh1').click(function(){
     $('div.showhide,h1').hide();
   });
   $('#showh1').click(function(){
     $('div.showhide,h1').show();
   });
   $('#toggleh1').click(function(){
     $('div.showhide,h1').toggle();
   });
 });

This works by watching for a click to occur on each of the buttons (which we've named 'hideh1', 'showh1' and 'toggleh1' respectively. When these buttons are clicked our associated jQuery code is executed (and hiding, showing, or toggling the header and div in the process).