Reputation: 752
I have given each of my div containers a unique id and some javascript. So I can click to Show/Hide each recipe on the page i'm looking at, but I would like to close any already open div via JavaScript when a new one is opened. I've included some extracted code rather than pasting the entire document as it's huge, below is also the live url:
*update - the <?=$counter_recipes;?>
is just producing a unique number. the $i++ method and all further up the page.
Live url - http://bit.ly/1hQuzRI
<h3 class="box2-title"><?php echo $row_rsCatalogue['pageTitle']; ?></h3>
<a style="color:#000" class="show_hide<?=$counter_recipes;?>">Show/hide</a>
<script type="text/javascript">
$(document).ready(function(){
$("#box_to_show<?=$counter_recipes;?>").hide();
$(".show_hide<?=$counter_recipes;?>").show();
$('.show_hide<?=$counter_recipes;?>').on('click',function(){
$("#box_to_show<?=$counter_recipes;?>").slideToggle();
});
});
</script>
<div class="box2-content" id="box_to_show<?=$counter_recipes;?>">
<p><?php echo $row_rsCatalogue['pageSubTitle']; ?></p>
<?php
if ($row_rsCatalogue['pageId']){
$rsPriceMatrix = $db->select('pageOption',array('pageId'=>$db->mes($row_rsCatalogue['pageId'])),array('sort'=>'ASC','name'=>'ASC'));
$ingredients = '';
while ($row_rsPriceMatrix = $rsPriceMatrix->get_row_assoc()){
$ingredients .= $row_rsPriceMatrix['name'].', ';
}
$ingredients = rtrim($ingredients,', ');
echo '<p>'.$ingredients.'</p>';
}
?>
I can paste more if needed.
Upvotes: 0
Views: 294
Reputation: 104775
Based on your code:
$('.show_hide<?=$counter_recipes;?>').on('click',function(){
//Hide open divs!
$("[id^=box_to_show]:visible").slideUp();
//slide down
$("#box_to_show<?=$counter_recipes;?>").slideToggle();
});
A much much easier way is to give a common class to your divs that open and close, then just call $(".someClass:visible").slideUp();
at the beginning of the function.
Upvotes: 3