MegaTron MegaTron - 4 months ago 11
jQuery Question

How to prevent multiple slidetoggles on the same item

I currently have list with a sub UL. When clicking on a list item, I want the UL to slide toggle. This I have achieved. The issue I'm currently having is, if i click on the same item that I have opened to close it, it performs a double toggle. It's worth mentioning, that I would like only one sub ul to be open at a time.

HTML

<div class="top">
<ul>
<li><a href="#"> Item </a></li>
<li class="drop"><a href="#"> Item Drop </a>
<ul class="sub">
<li><a href="#"> Sub Item </a></li>
<li><a href="#"> Sub Item </a></li>
<li><a href="#"> Sub Item </a></li>
</ul>
</li>
<li><a href="#"> Item </a></li>
<li><a href="#"> Item </a></li>
<li class="drop"><a href="#"> Item Drop</a>
<ul class="sub">>
<li><a href="#"> Sub Item </a></li>
<li><a href="#"> Sub Item </a></li>
<li><a href="#"> Sub Item </a></li>
</ul>
</li>
</ul>
</div>


CSS

ul {
li {
ul {
display:none;
}
}
}


JS

$('.drop').click(function(){
$('.sub').slideUp();
$(this).children('.sub').slideToggle();
});


http://codepen.io/anon/pen/RRZPvZ

Answer

Try the following

$('.drop').click(function(e){
  if($(e.target).closest('ul').is(':not(.sub)')) {//if the clicked element is has a ul that is not .sub we slide them up
  $('.sub').slideUp();}
  $(this).children('.sub').slideToggle();
});

or:

$('.drop').click(function(e){
  $('.sub').not( $(this).children('.sub')).slideUp();//hide all except the one we want to display
  $(this).children('.sub').slideToggle();
});
Comments