Capture Document click to close menu that is open

Asked

Viewed 172 times

2

I’m implementing a function in my menu where it will close the content of dropdown that is open IF the click is anywhere else 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
      }
   });
 });

Only always true when I click anywhere else, even the button responsible for opening the dropdown in question, so it is never displayed to be closed.

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

  • I must have misunderstood, I’ve already withdrawn the answer

2 answers

2


You can check if the target is your button and ignore the next 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 whether it contains a certain value in an array, if it finds it returns the index, if it does not find it is returned -1. Since string is array of chars in javascript, the if checks if among the classes of the element on the screen that was clicked there is any with classe_buttons, therefore the verification is if > -1 that is found.

  • elements do not have id.

  • Somehow you’re going to have to identify that button, if you can put a id Besides being the most correct form is the easiest. But you can use another selector such as class for example.

  • I have more than 1 menu that can be opened, so the reason for the loop and the non-use of ID

  • worked! you can explain a little more the first if ?

1

You can do this validation by 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, it’s like:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.