views:

68

answers:

2

I have a div which opens when I click a menu button, I am trying to close it if the user clicks anywhere after it is open. The issue I am having is that with my code the show div and the close div when a user clicks I guess are firing at the same time for some reason. The code for the click event is below. How can I make it so they do not fire at the same time and when I open the div that does not fire the click function. Thanks!

//if user clicks and menu is open then hide menu div
$(document).click(function() { 
       if($("menu").hasClass("menu_closed") == false ) { 
           //will hide the menu div
           closeMenu();
       }
}
+1  A: 

I think what you want actually is to stop propagation in the other click handler, something like:

$("your_menu_selector").bind("click", function(e){

   //your code to open the menu

   e.stopPropagation();
   return false;
})
Victor
this worked! thanks so much
mysql_quest
A: 

You might want to consider adding the event handler to close the menu in the handler that opens the menu. Have it execute only once using the one method. In the handler that opens the menu, simply check to see if it is open already and do a no-op if it is.

 $('.openButton').click( function() {
      var $menu = $('#menu').
      if ($menu.hasClass('menu_closed')) {
         $menu.removeClass('menu_closed').addClass('menu_open');
         $(document).one( function() {
             $menu.removeClass('menu_open').addClass('menu_closed');
         });
      }
 });
tvanfosson
but wont this only work when specifically clicking on the open button. I want the menu to close if I click anywhere sort of like a windows style menu.
mysql_quest
No. When the open button is clicked, it adds a handler to the document that will execute one time and will close the menu when you click anywhere on the page.
tvanfosson