Aj Troxell
Aj Troxell

Reputation: 265

Close Dropdown When Clicking Adjacent

I am using the following for a dropdown menu. It works great, however, I can't figure out how to get an open dropdown to slideUp if somewhere in the body is clicked, or another dropdown is clicked.

$(document).ready(function () { 
$('.nav li').click(function() {

  var slideToggle = this;
  if ($('ul', this).is(':visible')) {
      $('ul', this).slideUp(function() {
          $(slideToggle).removeClass('active');
      });
  }
  else {
      $('ul', this).slideDown();
      $(slideToggle).addClass('active');
  }
});
});

View it action here: http://jsfiddle.net/Ngh5C/1/

What would be the easiest way to go about what i've asked?

Upvotes: 1

Views: 600

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

Take advantage of event bubbling and bind a click handler to a suitable parent container (e.g. body). Check the target in the handler and if it isn't one of your menus, use a selector to find the open menu and close it.

Here's a simple example as a starting point:

http://jsfiddle.net/Ngh5C/6/

Try this fiddle to keep only one open at a time:

http://jsfiddle.net/Ngh5C/7/

If you really only want to close the neighbors of the item clicked (which is an odd requirement), then this works:

http://jsfiddle.net/Ngh5C/8/

Upvotes: 2

Related Questions