Juan.Queiroz Juan.Queiroz - 3 months ago 9
CSS Question

Vertical Dropdown menu with jQuery

I'm trying to create a drop down menu using ul and li.
My actual problem is, when I click on letter "A", it opens menu "A" and menu "B" at the same time, the same problem happens when I click on letter B.

This is my code:

HTML

<ul class="nav">
<li>
<a class="clickto">A </a>
</li>
<li class="show" style="display: none;">
<a href="#">AAA </a>
</li>
<li class="show" style="display: none;">
<a href="#">AAA </a>
</li>
</ul>
<ul class="nav">
<li>
<a class="clickto">B </a>
</li>
<li class="show" style="display: none;">
<a href="#">BBB </a>
</li>
<li class="show" style="display: none;">
<a href="#">BBBB </a>
</li>
</ul>


jQuery

$(".clickto").click(function(){
if ($(this).hasClass("clicked")){
$(".show").slideUp(500);
$(this).removeClass("clicked")
}else{
$(".show").slideDown(500);
$(this).addClass("clicked");
}
});


Here's the fiddle

Answer

Your issue is that $('.show') will match all elements with the show class on the page - which means both menus.

You can fix this by having a more specific selector, which finds the closest nav class then finds the show class within that.

$(".clickto").click(function() {
  var $show = $(this).closest('.nav').find('.show');
  if ($(this).hasClass("clicked")) {
    $show.slideUp(500);
    $(this).removeClass("clicked")
  } else{
    $show.slideDown(500);
    $(this).addClass("clicked");
  }
});

JSFiddle: https://jsfiddle.net/9cauyora/