iczyrski
iczyrski

Reputation: 51

Turning off clickable menu

I have a code which creates me a clickable dropdown, and close it when I click outside of the dropdown activator. It works well, but I have more then one dropdown activator on the page. When I click one activator after another, the previous dropdown don't hide.

function dropDownFunction(iD) {
  document.getElementById(iD).getElementsByClassName("dropdown-content")[0].classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropdown')) {
    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');
      }
    }
  }
}

Is there a way to hide the dropdown when I click another dropdown?

Upvotes: 0

Views: 57

Answers (2)

pho7on
pho7on

Reputation: 444

I would recommend using events. So when you click on anywhere besides dropdown it closes it. That way you can shorten your code. You just set event.stopPropagation() on the dropdown, so its clickable without closing itself, if thats an idea. Also we would need to see the code in order to help more. Does your second dropdown activator work at all?

Upvotes: 1

rth
rth

Reputation: 36

As you are managing the dropdown with class, you can just remove your show class before the toggling.

if you want more info please create a codepen/jsfiddle with the issue.

Upvotes: 1

Related Questions