medium
medium

Reputation: 4236

Jquery Close menu div on a click event

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();
       }
}

Upvotes: 1

Views: 1228

Answers (2)

tvanfosson
tvanfosson

Reputation: 532455

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');
         });
      }
 });

Upvotes: 0

Victor
Victor

Reputation: 9269

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;
})

Upvotes: 2

Related Questions