开发者

Jquery Close menu div on a click event

开发者 https://www.devze.com 2022-12-25 13:18 出处:网络
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

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号