Hide Menu when clicking on the outside

0

I have a slightly simple side menu that has a Toggle event that shows and hides said menu by clicking on its respective button.

I would like you to help me to make sure that when you click on any part of the page outside the menu, it is automatically hidden.

JavaScript

$(document).ready(function () {
            $('#BtMenuDez').on('click', function () {
                $('#MenuDez').toggle('slide'/*'slow'*/);
            });
        });

HTML

<ul id="menu" style="width: 85px;height: 70px;">
                    <li style="border-radius: 3px;">
                        <a href="#" id="BtMenuDez" style=""><i class="fa fa-bars fa-2x"></i></a>
                        <div id="MenuDez" style="display:none">
                            <ul> 
                                <li><a id="Menu1" href="#Inicio">Inicio</a></li><br />
                                <li><a id="Menu2" href="#Propositos">Propositos</a></li><br />
                                <li><a id="Menu3" href="#5S">5S</a></li><br />
                                <li><a id="Menu7" href="#Mudas">Mudas</a></li><br />
                                <li><a id="Menu8" href="#Poka-Yoke">Poka-Yoke</a></li><br />
                                <li><a id="Menu4" href="#Kanban">Kanban</a></li><br />
                                <li><a id="Menu5" href="#Hansei">Hansei</a></li><br />
                                <li><a id="Menu6" href="#Hacks">Hack's</a></li><br />
                                <li><a id="Menu9" href="#Glosario">Glosario</a></li>
                                <li><a id="Menu10" href="#Contactenos">Contáctenos</a></li>
                            </ul>
                        </div>
                    </li>                
                </ul>
    
asked by Mateo Castaño Tobon 18.06.2018 в 18:53
source

2 answers

0

Add the following code to complete your JavaScript part:

$(document).ready(function () {
  $(document).on('mouseup', function(e){
    const container = $("#BtnMenuDez");
    if(!container.is(e.target) && container.has(e.target).length === 0) {
      $('#MenuDez').hide('slide');
    }
  });

  $('#BtMenuDez').on('click', function () {
    $('#MenuDez').show('slide');
  });
});

What is being done is that when the button has been released after clicking, check if the menu is already displayed, and in that case, hide it.

    
answered by 18.06.2018 в 19:12
0

You can try this way:

$(document).mouseup(function(e) 
{
    var container = $('#MenuDez');

    // Si el elemento cliqueado no pertenece al contenedor padre
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

Greetings!

    
answered by 18.06.2018 в 19:15