Smithy Smithy - 1 month ago 8
Javascript Question

How to toggle class when clicked outside the element Jquery

So the first block of code opens and closes the .main-navigation while putting the shadow overlay over the page at the same time. But what I would like to accomplish is to click anywhere outside the navigation to do the same action(close the menu and remove the overlay) only if the menu is opened and overlay is over the page - so if those two classs are applied.

Fiddle: https://jsfiddle.net/bfgb951w/

<header id="ovlay">
<span class="nav-toggle eq">&equiv;</span>
<nav class="main-navigation">
<span class="nav-toggle">&times;</span>
<ul class="menu">
<li><a href="#about" class="slide-section">About</a></li>
<li><a href="#works" class="slide-section">Works and stuff</a></li>
<li><a href="#contact" class="slide-section">Contact</a></li>
</ul>
</nav>
</header>

$(document).ready(function(){
$('.nav-toggle').on('click', function(){
$('.main-navigation').toggleClass('open');
$('#ovlay').toggleClass('overlay');
});
});

$(document).click(function(){
if($('.nav-toggle').hasClass('open')) {
$('.main-navigation').toggleClass('open');
$('#ovlay').toggleClass('overlay');
}
});

Answer

You never set the open class to the .nav-toggle element so while the $(document).click() fires, the if-statement within it always yields false. Change it to:

$(document).ready(function(){
    $('.nav-toggle').on('click', function(){
        $('.main-navigation').toggleClass('open');
        $('#ovlay').toggleClass('overlay');
        return false;
    });
});

$(document).click(function(event){
    if($('.main-navigation').hasClass('open') && $(event.target).closest(".main-navigation").length == 0) {
        $('.main-navigation').toggleClass('open');
        $('#ovlay').toggleClass('overlay');
    }
});

Check this fiddle: https://jsfiddle.net/1n78d9jq/

Note the added check in the document.click that prevents closing when the click is on the main menu itself.

Comments