Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY - toggle divs based on ID

I have a large number of DIVs on a page. Each being a container for an Unordered List. Above each DIV is a header text which consists of an element with an anchor.

e.g.

<h2><a id="header1" href="#" > Header 1 </a></h3>
<div id="container1">
 <ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
</div>

<h2><a id="header2" href="#" > Header 2 </a></h3>
<div <div id="container2">>
 <ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
</div>

I need to have all these DIVs hidden until the header (anchor) is clicked. If the user clicks header it should toggle show/hide DIV

How can I accomplish this in JQUERY in a way that I can have one onClick function for all the DIVS, possibly using an id to differentiate between divs?

<h2><a href="#" onclick="toggleDiv(container1)"> Header 1 </a></h3>

function toggleDiv(id) {

}

but in JQUERY ?

SOLVED!!!!

<script>
 $(function(){
  $('.toggle-link').on('click', function() {
   var linkId = $(this).attr('data-div-id');
$('#' + linkId).toggle();
 });
});
</script>

<h2><a href="#" class="toggle-link" data-div-id="div1"> Header 1 </a></h2>
<div id="div1">
 <ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
</div>

<h2><a href="#" class="toggle-link" data-div-id="div2"> Header 2 </a></h2>
<div id="div2">
 <ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
</div>
like image 585
JakeSays Avatar asked Jun 01 '26 22:06

JakeSays


1 Answers

You can use .toggle() in jQuery

toggle() method toggles between hide() and show() for the selected elements.

function toggleDiv(id) {
  $('#'+id).toggle();   
}

where id is the parameter you pass

like image 199
melvin Avatar answered Jun 03 '26 11:06

melvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!