0

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');
    }
});
Smithy
  • 807
  • 5
  • 17
  • 43

1 Answers1

1

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.

Robba
  • 7,684
  • 12
  • 48
  • 76
  • hm seems to work for open-close, but still the menu closes if I click any of the links on it.. – Smithy Oct 30 '16 at 14:59
  • oh sorry, it seems to work in my browser, this happens only in fiddle. thank you! P.S. could you please explain why is the "return false" important, and why is the (".main-navigation").length == 0? – Smithy Oct 30 '16 at 15:01
  • 1
    If you don't add the return false, the click on the menu also counts as a click on the document. The length check ensures that the close when clicking somewhere on the menu itself it doesn't close. – Robba Oct 30 '16 at 15:37