3

I have a list of links. When one of the links is clicked, I would like to change the visibility of the div associated with it. My html looks like the following:

<div id="tab">
<ul>
<li id="tab1" class="active"><a href="#">Link 1</a></li>
<li id="tab2"><a href="#">Link 2</a></li>
<li id="tab3"><a href="#">Link 3</a></li>
<li id="tab4"><a href="#">Link 4</a></li>
</ul>
</div>

<div id="content1"><div class="nestedDiv">Content Here</div></div>
<div id="content2"><div class="nestedDiv">Content Here</div></div>
<div id="content3"><div class="nestedDiv">Content Here</div></div>
<div id="content4"><div class="nestedDiv">Content Here</div></div>

I tried using examples I found here: How do you swap DIVs on mouseover? (jquery?) but it fails because of the nested divs.

Any ideas of how I can get this working in a way that all the content within a given div, including other divs, is shown on click? I'd also like to keep the first div in an active state when the page is first opened... change the active look of the li that is selected... but I haven't attempted to tackle that yet.

Any input is appreciated. Thanks!

Thanks!

Community
  • 1
  • 1
Peachy
  • 643
  • 4
  • 20
  • 31
  • 1
    You should show the code that you used to try and hide/show the content, since it's not clear what calls or selectors you are using. – casperOne Feb 18 '10 at 17:54

1 Answers1

7

Add a class="content" on each content div

<style type="text/css">
.content
{
    display: none;
}
</style>

<script type="text/javascript">

$(document).ready(function() {

   $("#tab a").click(function() {

      //reset
      $(".content").hide();
      $("#tab .active").removeClass("active");

      //act
      $(this).addClass("active")
      var id = $(this).closest("li").attr("id").replace("tab","");
      $("#content" + id).show();
   });

});
</script>
Francisco Aquino
  • 9,097
  • 1
  • 31
  • 37
  • This works great, thank you so much! Any hint as to how I can keep the first content div open when the page first loads? – Peachy Feb 18 '10 at 18:18
  • oops, forgot that one. Add this under the $(document).ready part: var activeId = $(".active").attr("id").replace("tab",""); $("#content" + activeId).show(); – Francisco Aquino Feb 18 '10 at 18:34