How to hide an item by clicking outside it?

2

I want to do something like this:

Suppose that I click on a button to show a menu, and I want to click on the elements that are inside that menu, but when clicking on a different element of that menu (or the elements that it brings inside) this disappear.

    
asked by José Gregorio Materán 19.06.2017 в 05:20
source

1 answer

1

This will help you ( concept ):

 $(document).on("click",function(e) {

        var container = $("#tu_elemento");

            if (!container.is(e.target) && container.has(e.target).length === 0) { 
            //Se ha pulsado en cualquier lado fuera de los elementos contenidos en la variable container

            }
   });

Here goes a example works l:

    $(document).on("click",function(e) {
                    
         var container = $("#container");
                            
            if (!container.is(e.target) && container.has(e.target).length === 0) { 
               alert("¡Pulsaste fuera!");               
            }
     });
    #container {
        background: #fff;
        padding: 20px;
        box-shadow: 0px 0px 5px rgba(0,0,0,0.3);
        color: #555;
        border-radius: 5px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



    <div id="container">Pulsa en cualquier lado fuera de este elemento</div>
    
answered by 19.06.2017 в 07:37