简体   繁体   中英

when click other than a specified div then hide the dropdown

I created a custom dropdown, everything works good except of I want the dropdown to be hidden (slideUp) if not the dropdown div and all of its children is clicked. To be more sharp, I intends to hide the dropdown if not the dropdown is click (body click or anywhere on the document except for the dropdown and its children). Below is my snippets but yet, my attempts is sadly not working. Any help, suggestions, recommendations, ideas, clues is greatly appreciated. Thank you!

 $(document).ready(function(){ $(".with_dpx").click(function(e){ $(".dpx", this).slideDown(); e.preventDefault(); }); $(document).on("click", function(event){ if(event.target.is(".dpx")){ alert("asdas"); } }); }); 
 .thehide{display: none;} .dpx{ padding: 0px; margin: 0px; list-style: none; position: absolute; z-index: 9999; padding: 10px; background: #fff; margin-top: 20px; box-shadow: 0 0.5px 0 0 #ffffff inset, 0 1px 2px 0 #B3B3B3; } .dpx li{list-style: none;} .dpx li{ padding: 5px 8px!important; font-size: 15px; color: #555 !important; display: block !important; clear: both; float: none; text-transform: uppercase; border: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="menu"> <a href="#" class="with_dpx"> Menu 1 <ul class="thehide extend clear display_table dpx" id="test"> <li>hr approver</li> <li>manager approver</li> <li>attendance approver</li> </ul> </a> <a href=="#"> Menu 2 </a> </div> 

You can try this:-

 $(document).on("click", function(event){
     if($(event.target).is(".dpx")||$(event.target).closest(".dpx").length){
        //or this will also work
        //$(event.target).parents(".dpx").length           
        alert("asdas");
     }
 });

you can try this

$(document).mouseup(function (e)
{
var container = $("YOUR CONTAINER SELECTOR");

if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
{
    container.hide();
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM