Jimmy
Jimmy

Reputation: 12487

Jquery only allow one menu item to be expanded

So I have this code from a previous question: http://jsfiddle.net/928Dj/4/

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function(e) {
      $(this).next('ul').toggle();
});

I was wondering if anyone could tell me how I allow it to still be toggled open and closed, but also make it so if one menu is open and I click to open another menu, it closes the first one, meaning only one menu can be open at any time.

Upvotes: 0

Views: 97

Answers (3)

Amit Prajapati
Amit Prajapati

Reputation: 1190

This is the best way. You can also try this:

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function(e) {
      $(this).next('ul').toggle();
      $(this).parent().siblings().find('.opt').hide();
});

Fiddle

Upvotes: 0

T J
T J

Reputation: 43156

You can hide all the visible submenus before showing the current one as follows

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function(e) {
  var ul = $(this).next('ul');
  $('ul li ul:visible').not(ul).hide();
  ul.toggle();
});

Demo

Upvotes: 1

Balachandran
Balachandran

Reputation: 9637

Try to hide the opened ul elements first and then toggle the current element,

 $("ul.opt").addClass("hidden");
  $('#filter > li > a').on("click", function (e) {
    var cache = $(this).next('ul');
    $('#filter ul:visible').not(cache).hide();
    cache.toggle();
  });

DEMO

Upvotes: 1

Related Questions