jgb jgb - 24 days ago 8
Javascript Question

How to only open one dropdown at a time

I have a few dropdowns on my site and I can't figure out how to get them to only open one at a time. I've tried to hide them all by default first but it still seems to open all of them at once... am I missing something? Thank you!

Here's the HTML:

<div class="click-nav">
<ul>
<li>
<a href="#">Dropdown</a>
<ul class="sub">
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
<li><a href="#">Four</a></li>
</ul>
</li>
</ul>
</div>


Here's the js:

$(function () {
$('.click-nav > ul').toggleClass('no-js js');
$('.click-nav .js ul').hide();
$('.click-nav .js').click(function(e) {
$('.click-nav .js ul').slideToggle(200);
e.preventDefault();
$('.clicker').toggleClass('active');
e.stopPropagation();
});
$(document).click(function() {
if ($('.click-nav .js ul').is(':visible')) {
$('.click-nav .js ul', this).slideUp();
$('.clicker').removeClass('active');
}
});
});

Answer

Try this. Since you already have $(function() which is the shortcut for document.ready , you don't need another document.ready.

$(function () {
  $('.click-nav > ul').toggleClass('no-js js');
  $('.click-nav .js ul').hide();

  $('.click-nav .js').click(function(e) 
                            {
    $(this).find('ul').slideToggle(400); 
    $('.click-nav .js ul').not($(this).find('ul')).hide();
    e.preventDefault();
    e.stopPropagation();
  });      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="click-nav">
  <ul>
    <li>
      <a href="#">Dropdown</a>
      <ul class="sub">
        <li><a href="#">One</a></li>
        <li><a href="#">Two</a></li>
        <li><a href="#">Three</a></li>
        <li><a href="#">Four</a></li>
      </ul>
    </li>
  </ul>
  <ul>
    <li>
      <a href="#">Dropdown</a>
      <ul class="sub">
        <li><a href="#">One</a></li>
        <li><a href="#">Two</a></li>
        <li><a href="#">Three</a></li>
        <li><a href="#">Four</a></li>
      </ul>
    </li>
  </ul>
</div>

JSFiddle