I want to hide any visible span elements if any is visible, and toggle it again if a element is clicked
begin snippet: js hide: false
language: lang-js
function itemshow(n,e){
var idx = "num_"+n;
$(".item_title").each(function(){
var idn = $(this).next().attr("id");
if (idn == idx){
$("#"+idn).toggle();
}else{
$("#"+idn).hide();
}
});
}
language: lang-css
.item_desc{
display: none;
}
language: lang-html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div class="div_body">
<div class="item_title" onclick="itemshow(1,this)">
1) Question
</div>
<div class="item_desc" id="num_1">
Answer
</div>
<div class="item_title" onclick="itemshow(2,this)">
2) Question
</div>
<div class="item_desc" id="num_2">
Answer
</div>
<div class="item_title" onclick="itemshow(3,this)">
3) Question
</div>
<div class="item_desc" id="num_3">
Answer
</div>
</div>
end snippet
You can hide all the spans by using a span selector, then using the $(this) keyword to find the span next to the clicked link:
$(".item a").click(function() {
// Hide all item spans
$(".item span").hide();
// Show the element next to this
$(this).next().show();
});
$('.item span').hide();
$('.item a').click(function(e){
e.preventDefault();
// hide all span
var $this = $(this).parent().find('span');
$(".item span").not($this).hide();
// here is what I want to do
$this.toggle();
});
Check demo
Update with explanation:
The problem is when you hide all spans, you also hide the current span => all spans have the same state (hidden), and your next line display it again. You have to exclude the current element when hiding and use toggle method to toggle its state (simpler than using if to check)
Another problem is try to avoid implicit global by using var
to declare $this
:
var $this = $(this).parent().find('span');
It can be much simpler than that: Updated Fiddle
var all_spans = $('.item span').hide();
$('.item a').click(function(e){
var thisSpan = $(this).parent().find('span'),
isShowing = thisSpan.is(":visible");
// Hide all spans
all_spans.hide();
// If our span *wasn't* showing, show it
if (!isShowing) {
thisSpan.show();
}
e.preventDefault();
});
The main problem with your code was that you were checking whether the a
element was visible, rather than checking whether the span
was.
Your code also fell prey to The Horror of Implicit Globals on this line:
$this = $(this).parent().find('span');
...which creates a global variable $this
because you didn't declare it anywhere.