Yash Mistry Yash Mistry - 11 days ago 5
HTML Question

while using slideToggle, how to make all other divs slide back up?

I am building my portfolio site using bootstrap. I need to add project details under the images on my portfolio. It does toggle up and down when i click on the image but if I click on another image, the first div stays visible. How do i make all other visible "project-detail" divs slide back up when the user clicks on another image with slideToggle?



$('div.project-detail').hide();

$('img.doug').click(function() {
$('#dougDet').slideToggle();
});

$('img.ambe').click(function() {
$('#ambeDet').slideToggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="workBlock" class="portfolio-block fixed-bg dark-bg">
<div class="row">
<img src="assets/portfolio/doug-fir-logo-for-instagran.jpg" alt="Doug Fir Digital Logo" class="portfolio-half doug">
<img src="assets/portfolio/AmbeCreations-logo.jpg" alt="Ambe creations logo" class="portfolio-half ambe">
</div>
<div class="project-detail" id="dougDet">
<p>doug</p>
<p>doug</p>
<p>doug</p>
<p>doug</p>
<p>doug</p>
</div>
<div class="project-detail" id="ambeDet">
<p>ambe</p>
<p>ambe</p>
<p>ambe</p>
<p>ambe</p>
<p>ambe</p>
</div>
</div>




Answer

You can achieve what you need by calling slideUp() on the other .project-detail elements before toggling the targeted one.

Also note that you can DRY up your code by using a single event handler on all the .portfolio-half elements and using a data-* attribute to differentiate between them, something like this:

$('img.portfolio-half').click(function() {
  var $target = $($(this).data('target')).slideToggle();
  $('.project-detail').not($target).slideUp();
});
div.project-detail { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="workBlock" class="portfolio-block fixed-bg dark-bg">
  <div class="row">
    <img src="assets/portfolio/doug-fir-logo-for-instagran.jpg" alt="Doug Fir Digital Logo" class="portfolio-half doug" data-target="#dougDet">
    <img src="assets/portfolio/AmbeCreations-logo.jpg" alt="Ambe creations logo" class="portfolio-half ambe" data-target="#ambeDet">
  </div>
  <div class="project-detail" id="dougDet">
    <p>doug</p>
    <p>doug</p>
    <p>doug</p>
    <p>doug</p>
    <p>doug</p>
  </div>
  <div class="project-detail" id="ambeDet">
    <p>ambe</p>
    <p>ambe</p>
    <p>ambe</p>
    <p>ambe</p>
    <p>ambe</p>
  </div>
</div>

Also note that I moved the hiding of the .project-detail elements to CSS to avoid the FOUC on load of the JS.