Close function when clicking outside the element

1

I have a script problem below, the function myFunction and myFunction1 normally open the dropdown when clicking the button, but in the part of clicking outside and close, only the second event is working.

<script>
    function myFunction() {
        document.getElementById("myDropdown").classList.toggle("show");
    }

    function myFunction1() {
        document.getElementById("myDropdown1").classList.toggle("show");
    }

    // Fechar ao clicar fora - ESSE NÃO FUNCIONA SE ADICIONAR O DE BAIXO
    window.onclick = function(event) {
      if (!event.target.matches('.dropbtn')) {

        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
          }
        }
      }
    }

    // Fechar ao clicar fora - ESSE FUNCIONA, MAS O DE CIMA NÃO
    window.onclick = function(event) {
      if (!event.target.matches('.btn-header')) {

        var dropdowns = document.getElementsByClassName("dropdown-content2");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
          }
        }
      }
    }
    </script>
    
asked by anonymous 30.06.2017 / 19:46

1 answer

1

Just turning the comment in response. The problem with your code is to assign the window.onclick event twice, so the second assignment overrides the first. It is similar when you x = 1 and soon after x = 2 . The x value will be 2 and the value 1 will be lost. To get around the problem, just do the checks inside the same function:

window.onclick = function(event) {

  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }

  if (!event.target.matches('.btn-header')) {
    var dropdowns = document.getElementsByClassName("dropdown-content2");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }

}

In this way the two checks will be executed in the click event.

    
30.06.2017 / 20:31