0

i am trying to setup a dropdown menu, that can be closed by clicking outside (the opened div) and by clicking the button/img (that opens the div).

Image with onclick funtion:

<img onclick="hide()" id="menu" src="....">

Dropdown list that should be opened and closed, class declares dropdown as display:none:

<ul id="dropdown" class="dropdown-breadcrumb">
   <li>...</li>
</ul>

This is my solution so far:

function hide() {
    var x = document.getElementById("dropdown");

    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}

When i am trying to add a function that closes the dropdown when the user clicks outside the dropdown:

window.addEventListener('mouseup',function(event){
        var dropd = document.getElementById('dropdown');

        if(event.target != dropd && event.target.parentNode != dropd){
            dropd.style.display = 'none';
        }
});

Then i end up with a opened dropdown because the onclick-function starts.

Can someone help me to combine those functions? Thank you!

Jaydeep
  • 1,686
  • 1
  • 16
  • 29
JohnDoe
  • 91
  • 1
  • 12

2 Answers2

2

You can also try this one.

  $(window).click(function() { //Hide the menus if visible });
VNirav
  • 64
  • 6
2

You could bring all of your logic to the click listener and handle the elements' visibility in the function:

window.addEventListener('mousedown', function(event) {
  var dropd = document.getElementById('dropdown');
  var img = document.getElementById('menu');

  if (event.target === img && dropd.style.display === "none") {
    dropd.style.display = "block";
  } else if (event.target != dropd && event.target.parentNode != dropd) {
    dropd.style.display = 'none';
  }
});
<img id="menu" alt="img" />
<ul id="dropdown" class="dropdown-breadcrumb" style="width: 40px;">
  <li>First</li>
  <li>Second</li>
</ul>
shrys
  • 5,860
  • 2
  • 21
  • 36
  • 1
    @JohnDoe because `event.target` is am anchor tag, you can change the condition to `if ((event.target === img || event.target.tagName == "A") && dropd.style.display === "none")` to make it work for anchor tags – shrys Aug 19 '19 at 12:45
  • Sorry for beeing stupid, but still does'nt work .. `window.addEventListener('mousedown', function(event) { var dropd = document.getElementById('dropdown'); var img = document.getElementById('menu'); if ((event.target === img || event.target.tagName === "A") && dropd.style.display === "none") { dropd.style.display = 'block'; } else if (event.target != dropd && event.target.parentNode != dropd) { dropd.style.display = 'none'; } });` – JohnDoe Aug 19 '19 at 13:24
  • 1
    it is failing because `dropd.style.display` is `block`, use `if ((event.target === img) && dropd.style.display === "none" || (event.target.tagName === "A" && dropd.style.display === "block")) {`, my bad – shrys Aug 19 '19 at 13:38
  • 1
    You're my hero ! Thank you ! :) – JohnDoe Aug 20 '19 at 05:43