tags:

views:

25

answers:

2

I have a set of links and their corresponding divs showing information when clicked.

What I want to do is using jQuery, when a link is clicked, the div of only that particular link should be shown, and the rest should hide. Right now, it displays all the div containers regardless of which link is clicked unless I click on the same link again [then it toggles its div].

This is jQuery code I have right now:

              $("#babout")
               .click(function() {
                  $("div#about").slideToggle(600);
                }),

            $("#bcontact")
               .click(function() {
                  $("div#contact").slideToggle(600);
                }),



            $("#bsearch")
               .click(function() {
                  $("div#search").slideToggle(600);
                }),

. . . The HTML:

 <!-- Begin Search -->
        <div id="search" style="display:none;">
                <input type="text" class="bsearch" name="search" value="Type and press Enter" />
        </div>
         <!-- End Search -->

     <!-- Begin About -->
            <div id="about" style="display:none;">
                    This is about
            </div>
             <!-- End About -->

             <!-- Begin Contact -->
            <div id="contact" style="display:none;">
                    This is contact
            </div>
             <!-- End Contact -->

              <!-- Begin Naviagtion -->
             <div id="navigation">

                 <ul>
                    <li><a class="main" href="">Another?</a></li>
                    <li><a id="babout">About</a></li>
                    <li><a id="bcontact">Contact</a></li>
                    <li><a id="bsearch">Search</a></li>
                    <li><a href="">RSS Feed</a></li>
                 </ul>   

             </div>
             <!-- End Naviagtion -->
+3  A: 

Give each of the toggle-able <div> elements a class like this:

<div id="search" class="toggleDiv" style="display:none;">

Then you can write one handler instead of one for each link, like this:

$("#navigation li a[id]").click(function() {
  $("#" + this.id.substr(1)).slideToggle(600)
      .siblings('.toggleDiv').slideUp(600);
});​

You can give it a try here, as an aside, this is pretty close (but not exactly) functionality to an accordion, you may want to give it a look.

Nick Craver
Thanks, I tried your code at jsfiddle and it works but when I implement it in my code, nothing happens when I click the link. No div is displayed. It doesn't toggle the div at all. Am I missing something?
fuz3d
Nevermind, it's working now. Thank you so much!
fuz3d
+1  A: 

Then just do something like this:

$("#babout").click(function() {
    $("div#contact:visible").slideUp();
    $("div#search:visible").slideUp();

    $("div#about").slideToggle(600);
});
redtoad