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

127
Views
How to disallow click function when current class is inactive with JavaScript?

When in mobile view, the hamburger menu appears and the user clicks the icon it opens, when you click the close icon. its closes.

I'm attempting to allow users to click outside of the menu to close the menu. Unfortunately the JS code provided above, Allows users to click Anywhere on the site, to Open & close the menu. I Don't want this, I just want the menu to be closed when a user clicks outside of it.

How can I achieve this? Any help is appreciated.

document.querySelector('#bg-close').addEventListener('click', function() {
    document.querySelector('.nav').classList.toggle('nav-container')
})

The issue I'm attempting to solve is on my website

Summary:

Hamburger menu is being activated with a click anywhere on the site.

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

0

You can implement something like below:

It uses an if statement to see if the .nav-open class is active, in case is not there, nothing will happen. In opposite case it will be removed.

$('#bg-close').on('click', function() {
    let nav =  $('#navElement-id');
    if(nav.attr('class') == 'nav-container nav-open'){
       nav.attr('class','nav-container');
    }
});
*{padding:0;margin:0}
#bg-close{height:100vh;width:100vw;background-color:blue}
.nav-container{color:blue; padding:10px;position:absolute;top:10px; left:0;}
.nav-open{color:black!important;background-color:grey;width:300px;height:200px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="bg-close">
</div>
<div id="navElement-id" class="nav-container nav-open">Click on the blue</div>

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!