Ray
Ray

Reputation: 171

jQuery 'toggle' requiring two clicks

I have this little menu thing I'm working on: http://jsfiddle.net/6a3eZ/25/

The problem lies with the 'MISC' and 'MISC2' menus that slide open. When one is opened, the other needs to close, and the 'toggle' code I've pasted below works fine for the first two clicks, but then the menu items will require not one but two clicks to activate again. Any clues as how to keep it going with a single click?

For some reason, on touch devices the menus can't be closed either.

The code works everywhere with 'hover', but it really needs to be click-activated.

Here's what I have:

function mainmenu(){

    $('.menu ul').css({display: "none"});

    $('.menu li.sub').toggle(function(){
        $(this).siblings('li').find('ul').slideUp(200);
        $(this).find('ul:first').css({visibility: "visible",display: "none"}).slideDown(200);
    },function(){
        $(this).find('ul:first').slideUp(200);
    });

    $('.sub-menu li a').click(function(e) {
        e.stopPropagation();
    }); 

};

$(document).ready(function(){                  
    mainmenu();
});

Upvotes: 0

Views: 494

Answers (2)

ahmet2106
ahmet2106

Reputation: 5007

Try this one. Should work fine: http://jsfiddle.net/Ptz9F/

I would say, use some classes and specify steps the right way :)

Only my jQuery:

$(document).ready(function(){                  
    $('.menu ul.sub-menu').css({display: "none"});
    $('.menu li.sub > a').click(function(e){
        var $this = $(this),
            $parent = $this.parent('li'),
            $sub = $('.sub-menu', $parent);

        if (!$sub.hasClass('slided-down'))
        {
            // this sub is not visible
            $('.sub-menu.slided-down').slideUp(200).removeClass('slided-down');
            $sub.slideDown(200).addClass('slided-down');
        }
        else
        {
            // this sub is visible
            $sub.slideUp(200).removeClass('slided-down');
        }

        e.preventDefault();
        return false;
    });
});

Upvotes: 2

adeneo
adeneo

Reputation: 318232

untested, but try something more like this :

$(document).ready(function(){                  
    $('.menu ul').hide();

    $('.menu li.sub').click(function() {
        $(this).find('ul:first').slideToggle(200)
               .end().siblings('li').find('ul').slideUp(200);
    });
});

Upvotes: 1

Related Questions