Search code examples
jquerymegamenu

jQuery: menus appear/disappear on click


I've been looking all over the web and I can't find a solution. I am very new to jQuery as well.

My case:

I have a nav bar, each link in it activates/triggers a megamenu (each link has its own megamenu).

What I need:

I need a way to have each link activate its own megamenu, the megamenu should close when:

  1. The user clicks on another item in the nav bar.

  2. The user clicks on the same item in the nav bar.

  3. The user clicks on a 'close button' (X) graphic inside the megamenu (not shown in the HTML for simplicity sake).

HTML:

<div id="top-nav">
 <ul>
  <li><span>Products &amp; Services</span>
    <ul>
      <li><div class="megamenu">Content here...</div></li>
    </ul>
  </li>
  <li><span>Support &amp; Training</span>
    <ul>
     <li> <div class="megamenu">Content here...</div></li>
    </ul>
  </li>
  <li><span>Communities</span>
    <ul>
     <li> <div class="megamenu">Content here...</div></li>
    </ul>
  </li>
  <li><span>Store</span>
    <ul>
      <li><div class="megamenu">Content here...</div></li>
    </ul>
  </li>
 </ul>
</div>

I've seen the script of 'Sexy Drop Down Menu' but the problem is that it closes the menu triggered by the click on hover, and as I said, I'm new to jQuery and I can't figure out a way to adapt it to what I need.

http://www.sohtanaka.com/web-design/examples/drop-down-menu/

Any help would be greatly appreciated.

Thanks.


Solution

  • You would attach a click handler to another item/same item/close button which would read something like this:

    $(function(){
        $('#top-nav span').click(function(){
            divTrigger = $('#top-nav span').index(this);
            thisMegaMenu = $('.megamenu:eq('+divTrigger+')');
            $('.megamenu').slideUp(200);
            if(thisMegaMenu.is(":not(':visible')")){
            thisMegaMenu.slideDown(200);
            }
    });
        $('.megamenu').append("<a href=# id=closeButton>x</a>");
        $('#closeButton').live('click',function(){
            thisMegaMenu.slideUp(200);
        });
    });
    

    Try it out here