Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
How can I make an element disappear when clicking away from it using javascript

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);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!