简体   繁体   中英

Javascript Multiple menu. If i click on one ul i want the other to close. (toogle). It keeps being open, how to fix?

Hopefully you can help me out with my problem. Been annoying be for quite some time now.

Trying to make my menu work.

When i click on a block i want it to open, and close the other tab "if" another one is open.

Best regards jfb

HERE IS JSFIDDLE http://jsfiddle.net/3ZWZu/ INCLUDES HTML, CSS, JS(jQuery)

$(document).ready(function() {

$('.ac-menu .topLevel').click(function(e) {
    e.preventDefault();

        if($('.ac-menu .topLevel ul').hasClass('open') === true){
        $('.ac-menu .topLevel ul').removeClass('open'); 
        $('.ac-menu .topLevel ul').addClass('closed');  
        $('.ac-menu .topLevel ul').slideUp(300);

    }
        if($(this).next('ul').hasClass('closed') === true){ 
        $(this).next('ul').removeClass('closed');           
        $(this).next('ul').slideDown(300);
        $(this).next('ul').addClass('open');
    }
 });
});

Presuming you use JQuery, try this one:

$(document).ready(function() {    
 $('.ac-menu .topLevel').click(function(e) {
    e.preventDefault();    
    $('.ac-menu ul.open').removeClass('open').addClass('closed').slideUp(300);    
    $(this).next('ul.closed').removeClass('closed').slideDown(300).addClass('open');
  });
});

Basically the idea behind this is that with ul.open or ul.closed selector you will only select the ul s which have that specific class set. If there are none - then JQuery will return an empty set and will not apply those operations to anything - that is the way JQuery works. Furthermore, it allows you to chain your commands, like shown in my example.

I think you need that jsfiddle

i add topLevel class to li instead of a href

$(document).ready(function() {
  $('.ac-menu li.topLevel').click(function(e) {
    e.preventDefault();
    var isClosed = $(this).find('ul').hasClass('closed');
    $('.ac-menu li.topLevel ul').removeClass('open').addClass('closed').slideUp(300);
    if( isClosed){
        $(this).find('ul').addClass('open').removeClass('closed').slideDown(300);
    }
 });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM