1

I can get the navigation menu to appear when I click on the button, but I can't make it disappear.

Here's the code:

const navButton = document.getElementById("nav-btn");
const menu = document.getElementById("nav-menu");
const all = document.getElementsByTagName("body");

const menuActive = () => {
    if (menu.style.display = "none") {
        menu.style.display = "block";
    }
}

const menuDeactive = () => {
    if (menu.style.display = "block") {
        menu.style.display = "none";
    }
}

navButton.addEventListener("click", menuActive);

all.addEventListener("click", menuDeactive);
Bledsoe
  • 19
  • 3
  • 1
    Multiple issues: `all.addEventListener` doesn’t make sense. See [What do querySelectorAll and getElementsBy\* methods return?](/q/10693845/4642212). `if (menu.style.display = "none")` doesn’t make sense. See [What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)](/q/11871616/4642212). – Sebastian Simon Sep 21 '21 at 20:36
  • Checking CSS properties directly is [best avoided](/q/55071684/4642212). Instead, a CSS class should be used, e.g. `.hidden { display: none; }`; then [`.classList.contains("hidden")`](//developer.mozilla.org/docs/Web/API/Element/classList) to check for its existence, `.classList.toggle("hidden")`, etc. Consider using the [`hidden` attribute](//developer.mozilla.org/docs/Web/HTML/Global_attributes/hidden) instead. – Sebastian Simon Sep 21 '21 at 20:37
  • You will have to stop propagation of the event too. Else, when you will click on nav-menu, it will propagate till body and trigger the event there too. – Clem Sep 21 '21 at 20:37
  • And finally: see [How do I detect a click outside an element?](/q/152975/4642212). – Sebastian Simon Sep 21 '21 at 20:38

1 Answers1

0

Use == to compare.

Also, document.getElementsByTagName("body") is redundant. There can only be one body tag.

const navButton = document.getElementById("nav-btn");
const menu = document.getElementById("nav-menu");
const all = document.getElementsByTagName("body");

const menuActive = () => {
    if (menu.style.display == "none") {
        menu.style.display = "block";
    }
}

const menuDeactive = () => {
    if (menu.style.display == "block") {
        menu.style.display = "none";
    }
}

navButton.addEventListener("click", menuActive);

document.body.addEventListener("click", menuDeactive);
Spectric
  • 30,714
  • 6
  • 20
  • 43