Reden Reden - 21 days ago 6
jQuery Question

How do I hide the same content after opening with jQuery?

I want to hide a current element after it's been clicked. Right now if you click it, it will reopen, I don't want to nest the items, as I need these to be their own independent links. Here's my code:

This is my fiddle: http://jsfiddle.net/neo9a0xc/

<style>.targetDiv {display: none}</style>

<a class="showSingle" target="1">Div 1</a>
<a class="showSingle" target="2">Div 2</a>
<a class="showSingle" target="3">Div 3</a>
<a class="showSingle" target="4">Div 4</a>


<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
<div id="div4" class="targetDiv">Lorum Ipsum4</div>

<script>
jQuery(function(){
jQuery('.showSingle').click(function(){
jQuery('.targetDiv').slideUp();
jQuery('.targetDiv').hide();
jQuery('#div'+$(this).attr('target')).slideToggle();
});
});
</script>

Answer

You don't need both the slideUp and hide since when slideUp finishes it sets the display to none anyway. What you need to do is get the index of the element you click on, and then hide the targetDiv divs that aren't of the same index.

jQuery(function() {
  jQuery('.showSingle').click(function() {
    $(this).addClass('selected').siblings().removeClass('selected');
    var idx = $(this).index('.showSingle')
    jQuery('.targetDiv:not(:eq(' + idx + '))').hide();
    jQuery('#div' + $(this).attr('target')).slideToggle();
  });
});
.targetDiv {
  display: none
}
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<a class="showSingle" target="1">Div 1</a>
<a class="showSingle" target="2">Div 2</a>
<a class="showSingle" target="3">Div 3</a>
<a class="showSingle" target="4">Div 4</a>


<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
<div id="div4" class="targetDiv">Lorum Ipsum4</div>