input
input

Reputation: 7519

Toggle div containers of links using jQuery

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 -->

Upvotes: 0

Views: 1107

Answers (2)

redtoad
redtoad

Reputation: 1

Then just do something like this:

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

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

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630637

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.

Upvotes: 3

Related Questions