jQuery: menus appear/disappear on click

爷,独闯天下 提交于 2019-12-03 20:44:55

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

I was able to get this other solution which works like a charm as well:

$(function(){
//Megamenus
$('#top-nav li').click(function(){//set up a click event for the li
    $(this).siblings('.active').click();//click any other lis which are active to close their menus
    $(this).find('.megamenu').toggle();//toggle the child megamenu
    $(this).toggleClass('active');//toggle a class so we can identify any open megamenus
});

$('.megamenu').click(function(event){//hide the megamenu on load and set up a click event..
    $(this).parents('li').click();//..that just clicks the parent li
    event.stopPropagation();//stop the click bubbling up to the parent li
  });
});

My problem now is which of both solutions is better to use? This is a good problem now though :p

Solution provided at: http://codingforums.com/showpost.php?p=1016305&postcount=2

For each of the higher level <li>s in the Navbar, give them a class like 'navbar'. Then your jQuery could look something like this:

$('li .navbar').click(function() {
  if($(this).find('.megamenu').is(':visible')) { // Already open
    $(this).find('.megamenu').hide();
  } else { // Close others first
    $('.megamenu').each(function() {
      $(this).hide();
    });
    $(this).find('.megamenu').show();
  }
});

You would just need to add the click handler for the Close button. Note, this is untested code so let me know if there's a problem.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!