We help IT Professionals succeed at work.

jquery dropdown box - multiple

joethermal
joethermal asked
on
Hi, I have a page where i want jquery to toggle multiple dropdown boxes eg;

Button1 - toggles contentbox1
Button2 - toggles contentbox2
Button3 - toggles contentbox3

HTML...
<a href="#"  id="button1">One</a>
<a href="#"  id="button2">Two</a>
<a href="#"  id="button3">Three</a>

<div id="contentbox1" style="display: none;">content box one</div>
<div id="contentbox2" style="display: none;">content box two</div>
<div id="contentbox3" style="display: none;">content box three</div>

Open in new window


JQUERY...
$(document).ready(function(){
        $('#button1').toggle(function(){
            $('#contentbox1').slideDown();
        }, function(){
            $('#contentbox1').slideUp();
        });
	});

Open in new window


How would I use this same function to slide up and down different boxes with different buttons instead of duplicating the code for each button/contentbox.
...and when a box is down and I click a button to drop another box  ...how do I make the box that is already down slide up first?

Thanks
Comment
Watch Question

Software Engineer
CERTIFIED EXPERT
Commented:
try this:
var activeBox = null;
$(document).ready(function(){
  $('a[id^=button]').toggle(function(){
    if (activeBox) {
      $('#button' + activeBox).click(); /* call second toggle function to hide the active box */
    }
    activeBox = this.id.substr(6);
    $('#contentbox' + activeBox).slideDown();
  }, function(){
    $('#contentbox' + this.id.substr(6)).slideUp();
    activeBox = null;
  });
});

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
Alternative. Add class to <a> to pick up generic click. Then make the <div>'s id based on the id of the button - wht a static suffix - the rest is trivial.

<a href="#"  id="button1" class="button-box">One</a>
<a href="#"  id="button2" class="button-box">Two</a>
<a href="#"  id="button3" class="button-box">Three</a>

<div id="button1_box" style="display: none;">content box one</div>
<div id="button2_box" style="display: none;">content box two</div>
<div id="button3_box" style="display: none;">content box three</div>

Open in new window

$(document).ready(function(){
  $('a.button-box').toggle(function(){
            $('#' + $(this).attr('id') + '_box').slideDown();
        }, function(){
            $('#' + $(this).attr('id') + '_box').slideUp();
        });
	});

Open in new window

Author

Commented:
Thanks - just what i wanted

Explore More ContentExplore courses, solutions, and other research materials related to this topic.