Jarrod H
Jarrod H

Reputation: 45

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.

Upvotes: 1

Views: 140

Answers (1)

Gass
Gass

Reputation: 9344

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>

Upvotes: 2

Related Questions