views:

337

answers:

1

I have the following code that just has controls relating to an item.

<ul class="controls">
    <li><button type="button" class="button1" value="somevalue">&nbsp;</button></li>
    <li><button type="button" class="optionsbutton" value="somevalue">&nbsp;</button></li>
    <li class="options">
        <ul>
            <li>Option 1 link</li>
            <li>Option 2 link</li>
            <li>Option 3 link</li>
       </ul>
    </li>
</ul>

The options menu (the ul in the li.options) is hidden by default in the css (via display:none). I want a click on the options button (button.optionsbutton) to toggle showing and hiding the ul, but I also want a click on any other options button (there are many items with this button) to close any open menus and I need a click anywhere not on a button to close the menu as well. My Jquery code is below:

$('button.optionsbutton').click(
    function(event){
        // hiding any other open menus
        $('ul.controls li.options').hide();

        var OptionMenu = $(this).parent('li').siblings('.options');
        if ( OptionMenu.is(':visible') ) {
            $('ul.bit_controls li.bit_options').hide();
        } else {
            bitOptionMenu.css('display','block'); 
            //because show() sets display to list-item insteads of block
        } 

        event.stopPropagation();
    }
);

// So that clicks anywhere outside will close the menu
$('html').click(
    function(event){
        if(event.target != 'button.options' && $('button.options').is(':visible') ) {
         $('ul.controls li.options').hide();
        }
    }
);

The menus open properly when the buttons are clicked and close when another button is clicked or there's a click outside the menu. BUT, clicking on the same button twice doesn't close the menu! Whats the deal here folks, I know its easy but I've been beating my head against it for hours.

+1  A: 

The line $('ul.controls li.options').hide(); will probably hide your menu.

If this is the case, the test if ( OptionMenu.is(':visible') ) will always return false and show the menu.

Scharrels
Oh, I see, thanks! I should have figured that one out. I moved "$('ul.controls li.options').hide();" (the one under the //hiding all other open menus comment, and moved it right before the "bitOptionMenu.css('display','block');"
Diogenes
Upvoted to counter the (sadly unexplained) down-vote, in respect of your solving the OP's problem.
David Thomas