Show and hide with jQuery

Written by Joe on Thursday, February 4, 2010

Simple, yet very powerful, jQuery show() and hide() functions give you the ability to show and hide content on the fly.  These functions are useful when you have long content that may cause vertical scrolling, "tabbed" sections, and more.  Put together with the click() function, which you can read about in my article "jQuery for beginners", in this article I will demonstrate how to use the show() and hide() functions along with the click() function.

For this article imagine you have a product on your website.  You want to display the products description and photos on the same page, but don't want your page to scroll vertically.  A tabbed <div> can do just what you need.

In the image to the right, you have one section containing the description of your product, and the other containing your product images. When you click the pictures tab, rather than reloading the page, you want to hide the description section and display the pictures section.

Here is what the html markup should look like.  Your markup may be different depending on how your site is layed out.

<div id="product_details">
  <div class="tabs">
      <ul>
          <li class="description">Description</li>
          <li class="picures">Pictures</li>
      </ul>
  </div>

  <div class="text_area">
      <div id="description" class="active">
          <!--  My Description -->
      </div>
      <div id="pictures">
          <!--  My Pictures -->
      </div>
  </div>
</div>

Your CSS should look something like this:

#product_details
{
     width:400px;
     border:1px solid #CCC;
}

#product_details .tabs li
{
     float:left;
     padding:5px 10px;
     cursor:pointer;
}

#product_details .text_area div
{
     display:none;
}

#product_details .text_area div.active
{
     display:block;
}

Now the jQuery magic to make everything work:

$("#product_details .tabs li").click(function(){
     var tab = $(this).attr("class");
     $("#text_area div").removeClass("active");
     $("#text_area div").hide();
     $("#text_area div#" + tab).fadeIn();
});

And thats all!  With a little design and styling you can use this code for many different scenarios.

Like what you’ve read?

Link back to us.
http://www.revolutionunlimited.com/news-and-articles/javascript-jquery/2010-02-04/show-and-hide-with-jquery/

OR Join Our Mailing List

* indicates required fields

Pulling your hair out over your website?

Contact us today to get a professional website at a great price.

Contact Us Today

Post A Comment