Click on page area and close MENU

1

I'm trying to make this script close the MENU when I click on any area of main .

The MENU opens the left side of the mobile page. But as you can see the MENU is out of main . So I could not do that code with closest checking if any PAI element has class menu-in .

    // Abre o Menu Mobile
    $('.open-menu-mobile').on('tap click', function(){
        $('main, nav.menu').addClass('menu-in');
    });

    nav.menu{
        position: absolute;
        width: 240px;
        background-color: #37474f;
        height: 100%;
        z-index: 1;
        opacity: 0;
        left: -240px;
        transition: all 0.3s ease;
        &.menu-in{
            transform: translateX(100%);
            opacity: 1;
        }
    }

    {{-- MENU --}}
    <nav class="menu">
        <div class="search">
            Procurar
        </div>
        <ul>
            <li><a href="#">Quem Somos</a></li>
            <li><a href="#">Produtos</a></li>
            <li class="logo"><a href="#"></a></li>
            <li><a href="#">Contato</a></li>
            <li><a href="#">Onde Estamos</a></li>
        </ul>
    </nav>

    {{-- MAIN --}}
    <main>
        {{--- Cabeçalho do Site Mobile --}}
        <header id="header">
            {!! Html::image('img/open-menu-mobile.png', 'Abrir Menu Mobile', ['class'=>'open-menu-mobile']) !!}
            <a href="{!! URL::to('/') !!}">
            </a>
        </header>

        @yield('content')
    </main>

Personally, I messed up this code and it's now working almost the way I need it.

    // Abre o Menu Mobile
    $('.open-menu-mobile').on('tap click', function(e){
        $('main, nav.menu').stop(true, true).addClass('menu-in');
        e.stopPropagation();
    });

    // Clicar em alguma área do site e fechar MENU
    $(document).on('tap click', function(e){
        if(!$(this).hasClass('.open-menu-mobile'))
            $("main, nav.menu").removeClass('menu-in');
    });

What happens now is as follows:

Inside my MENU , I have LINKS and a Search field. When I click on these places, the MENU closes as well. I found that using stopPropagation() would solve this.

    
asked by anonymous 28.07.2015 / 22:16

1 answer

1

I did it.

    // Clicar em alguma área do site e fechar MENU
    $('body').on('tap click', function(e){
        if(e.target !== $('nav.menu')[0] && $(e.target).closest('nav.menu').attr('class') != 'menu menu-in')
            $("main, nav.menu").removeClass('menu-in');
    });

I used closest to check if the parent element class is different from the parent I'm clicking on. If yes, close the MENU .

So when I click on a child of the parent element, it does not close the MENU , since the parent element's class is = to what I determined in the condition.

    
29.07.2015 / 20:46