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

261
Views
Clicking outside of element with JavaScript e.target not working

I'm building a mega menu that has a close button on each menu that works great. However I need to write some JavaScript that says, 'if you click outside a mega menu when it's open, close it'.

I've written a script below. It does detect when a user clicks inside of the mega menu, but it doesn't when they click outside of it. In this case, removing the display-on class which makes an element have display: block;.

const dropDownMenu = document.getElementsByClassName("drop-down");

for (let i = 0; i < dropDownMenu.length; i++) {
  dropDownMenu[i].addEventListener("click", (e) => {
    // If clicking in any area that has drop-down class, do nothing.
    if (dropDownMenu[i].contains(e.target)) {
      console.log("clicked in mega menu area");
      // If clicking in any area outside drop-down class, remove display-on class which closes the menu.
    } else {
      console.log("clicked outside mega menu area");
      document.querySelector(".display-on").classList.remove("display-on");
    }
  });
}

Working demo if needed can be seen here.

Thanks.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

From the above comment ...

"Of cause the OP needs to register the handling of "out of drop-down" events also outside of any drop-down classified element. document.body might be the right element for listening."

... something like this ...

function handleDropDownMenuBehavior(evt) {
  if (evt.target.closest('.drop-down') === null) {

    document.querySelector(".display-on").classList.remove("display-on");

    console.log("clicked outside mega menu area");
  } else {
    console.log("clicked in or at mega menu area");
  }
}
document.body.addEventListener('click', handleDropDownMenuBehavior);
about 4 years ago · Juan Pablo Isaza Report

0

You could add a global event listener to the document which checks if what was clicked on isn't the mega menu. let me know if you need any extra help :)

document.onclick = (e) => {
    if (e.target.contains(document.getElementsByClassName("drop-down")[0])) {
        console.log('close mega menu');
        document.getElementsByClassName("drop-down")[0].classList.remove("display-on");
    }
}
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!