Capture document click to close menu that is open

2

I'm implementing a function in my menu where it will close the contents of the dropdown that is open IF the click is anywhere except in the menu itself.

$(document).click(function(event) {
   var $menuOpened = $('.dropdown-content');
   $.each($menuOpened, function(index, value) {
      if ($(value).hasClass('show') && event.target != $(value)) {
         // Fecha o menu
      }
   });
 });

But I always true when I click elsewhere, even the button responsible for opening the dropdown in question, therefore, it is never displayed in order to be closed.

  

I have more than 1 dropdown that can be opened in the same menu.

    
asked by anonymous 25.01.2017 / 20:12

2 answers

2

You can check if the target is your button and ignore the following action:

$(document).click(function(event) {

   if ($(event.target).attr('class').indexOf('classe_botoes') > -1) return; // verifica se o alvo esta sendo o botão

   var $menuOpened = $('.dropdown-content');
   $.each($menuOpened, function(index, value) {
      if ($(value).hasClass('show') && event.target != $(value)) {
         // Fecha o menu
      }
   });
 });

indexOf is a javascript function that checks if it contains a certain value in an array, if it finds it it returns the index, if it does not find it is returned -1 . Since string is an array of chars in javascript, if checks if any of the classes on the screen element that was clicked exist with class_boos , so the check is if it is > -1 it's found.

    
25.01.2017 / 20:16
1

You can do this validation through target of the event.

$(document).click(function(event) {
   if (event.target.id == 'btnAbrirMenu' || event.target.id == 'div_do_menu')
      alert("clicou no menu ou no botão de abrir o menu");
   else
      alert("clicou fora do menu");
 });

At the end of the day, something like:

$(document).click(function(event) {
   if (event.target.id == 'btnAbrirMenu' || event.target.id == 'div_do_menu')
      return;
   else { 
      //fechar menu;
   }
 });
    
25.01.2017 / 20:19