Question

I have a menu where some elements slide up and slide toggle. So if, fruit is open and I click on vegetables, this opens and fruit closes. That's all working fine. 'Snacks' doesn't have a submenu but I want it to behave the same as the other two. So if I click on snacks and any of the other submenus are open, it'll close them with the same slide effect.

At the moment I have it on hide (slow), but that hides the elements horizontally, not with a slide up/down.

Can anyone help?

http://jsfiddle.net/Alga/H3Y4Q/2/

$('.fruit_submenu').hide(); $('.veg_submenu').hide();

$('li#fruit').click(function () { $(".fruit_submenu").slideToggle(); $('.veg_submenu').slideUp(); });

$('li#veg').click(function () {

  $(".veg_submenu").slideToggle();
  $('.fruit_submenu').slideUp();

});

$('li#snacks').click(function () {

  $('.fruit_submenu').hide('slow');

});

Was it helpful?

Solution 2

The way you're toggling isn't ideal, and you could avoid having to specify which elements to open/close if you loop through all the 'li' elements on each click. That would also make it easy to expand upon in the future.

That said... a quick answer to your question is below:

  $('.fruit_submenu').hide();
  $('.veg_submenu').hide();

  $('li#fruit').click(function () {
      $(".fruit_submenu").slideToggle();
      $('.veg_submenu').slideUp();
  });


  $('li#veg').click(function () {
      $(".veg_submenu").slideToggle();
      $('.fruit_submenu').slideUp();
  });

  $('li#snacks').click(function () {
      //force the other elements to slide up no matter their state.
      $('.fruit_submenu').slideUp();
      $('.veg_submenu').slideUp();
  });

OTHER TIPS

Fixing the markup first, as it's invalid

<ul class="menu">
    <li id="fruit">Fruit
        <ul class="fruit_submenu">
            <li>Apples</li>
            <li>Bananas</li>
            <li>Pears</li>
        </ul>
    </li>
    <li id="snacks"><a href="#">Snacks</a>
    </li>
    <li id="veg">Vegetables
        <ul class="veg_submenu">
            <li>Beans</li>
            <li>Spinach</li>
        </ul>
    </li>
</ul>

you can just do

$('.menu [class$="_submenu"]').hide();
$('.menu li').on('click', function () {
    $(this).siblings('li').find('ul').slideUp();
    $('[class$="_submenu"]', this).slideToggle();
});

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top