Kez Kez - 3 months ago 22
jQuery Question

Simple collapse / expand using jquery within a php foreach loop

having a bit of trouble with a simple collapse/expand as the elements I'm try to do this with are within a foreach loop, and any element I create it's created for each list item, therefore, giving it a container is proving difficult.

PHP:


echo '<div class="cat_holder">';
function listFolderFiles($dir){
$ffs = scandir($dir);


foreach($ffs as $ff){

if($ff != '.' && $ff != '..'){

if(is_dir($dir.'/'.$ff)){

echo '<div data-toggle="collapse" class="cat_header_holder collapse in">';
echo '<h1 class="lead">' .$ff. '</h1>';
echo '</div>';

listFolderFiles($dir.'/'.$ff);

}else{


?><div class="cv_group"><?php

echo '<a target="_blank" class="cv_item" href="'.$dir.'/'.$ff.'">'.$ff.'<span class="pull-right add_shortlist"><i class="fa fa-check" aria-hidden="true"></i></span></a>';


?></div><?php

}
}
}
}

listFolderFiles('pdf');
echo '</div>';
?>


JS:

$('.cat_header_holder').click(function(){
$('.cv_group').slideToggle('slow');
});


Generated HTML:

<div data-toggle="collapse" class="cat_header_holder collapse in"><h1 class="lead">Title</h1>
</div>
<div class="cv_group">
<a target="_blank" class="cv_item" href="#doc">click here</a>
</div>

<div class="cv_group">
<a target="_blank" class="cv_item" href="#doc">click here</a>
</div>


cv_group is supposed to be hidden and onclick cat_header_holder, show cv_group.

The issue is that when clicking on cat_header_holder all cv_group's are displayed and not the one for that category.

Any help is much appreciated.

Answer

Assuming that your final HTML will be somewhat like below you can check this code:

$(document).ready(function() {

  $('.cat_header_holder').click(function() {
    $(this).nextUntil('.cat_header_holder').slideToggle('slow');
  });

});
.cv_group {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div data-toggle="collapse" class="cat_header_holder collapse in">
  <h1 class="lead">Some Text 1</h1>
</div>
<div class="cv_group">
  Some Contents 1 - 1
</div>
<div class="cv_group">
  Some Contents 1 - 2
</div>
<div data-toggle="collapse" class="cat_header_holder collapse in">
  <h1 class="lead">Some Text 2</h1>
</div>
<div class="cv_group">
  Some Contents 2 - 1
</div>
<div class="cv_group">
  Some Contents 2 - 2
</div>
<div class="cv_group">
  Some Contents 2 - 3
</div>
<div data-toggle="collapse" class="cat_header_holder collapse in">
  <h1 class="lead">Some Text 3</h1>
</div>
<div class="cv_group">
  Some Contents 3
</div>

Here via $.nextUntil() we are targeting the next DOM elements i.e. associated div which need to be toggled.

Comments