I have several divs on a page. Each div has a heading which I can click to toggle visibility of the corresponding div. The divs are set to display:none by default.
I have used #ids in the click functions of each of the divs , however since I have several divs on the same page. I would want to use a single .class so that I have a single class thus a single function that controls the visibility.
I am guessing i would then need to use .parent and .sibling classes to do this.
Below is an excerpt from my code:
HTML:
<div>
<legend>
<a id="show_table" class="show_table" href="#">
<span id="plus_minus"></span>Div
</a>
</legend>
<div class="toshow" id="toshow">Div to be shown</div>
</div>
JS:
$('#show_table').click(function(){
$("#toshow").slideToggle();
})
I would think to make this more efficient, so that I don’t have to do this for every div using the #ids I would want to know how to use a single .class , probably parent and siblings of it to make this.
As an addition, I would like to have a minus/plus sign toggle functionality on the plus_minus span. I had the same working using the individual ids . How would I be able to achieve this using a single .class. I attempted this using below:
$('.div_show').click( function(){
$(this).parent().next().slideToggle();
if($(this).parent().next().is(':visible'){
$(this).closest('span').find('plus_minus').text('+');
}
else {
$(this).closest('span').find('plus_minus').text('-');
}
});
However it seems not to work.
Suggestions on how to achieve this +/- toggle functionality appreciated.
Why not try this
UPDATED CODE
Because you are using SlideToggle the changes to the DOM is not readily updated.. So you have to handle the visibility issues in the callback function of it..
Try this code
UPDATED FIDDLE