简体   繁体   中英

When clicked inside div that is toggled to show, it toggles up

I have an annoying problem, I have a button that toggles a dropdown, my intention is to hide the div when clicked on the button again, which toggle achieves, and to hide the dropdown when clicked outside why my current jquery does. However when clicking inside the div itself, it slides back up.

HTML >

<div class="navPanel">

<!-- NAV -->

<nav>

<ul id="navBar"> 

<div class="dynamicNav">

<div class="menu1Container">
<li class="menu1">Books

<!-- DropDown1-->
<div id="dropdownContainer-1"> 

</div>
</li>
</div>
</div>

</ul>

</nav>

Jquery >

$(function(){
 $(".menu1").click(function(){
   $("#dropdownContainer-1").slideToggle(90);
});

 $(document).click(function(event) {
if (!$(event.target).is(".menu1") && !$(event.target).is(".menu1")) {
     $("#dropdownContainer-1").slideUp(90); //make all inactive
   }
    });

});

The obvious problem is event target, I tried using a similar method ->

$(document).click(function(e) {
 var target = e.target;
 if (!$(target).is('.menu1') && !$(target).parents().is('.menu1')) {
 $('#dropdownContainer-1').slideUp(90);
 }
  });

If you could help me figure this one out, I'd appreciate it!

You may use:

$(event.target).closest(".menu1").length == 0

 $(".menu1").click(function(e){ e.stopPropagation(); // avoid to propagate to document click if ($(event.target).is(".menu1")) { $("#dropdownContainer-1").slideToggle(90); console.log('Menu1 toggled clicking menu1'); } }); $(document).click(function(event) { if ($(event.target).closest(".menu1").length == 0 && $("#dropdownContainer-1").is(':visible')) { // if not inside area of menu1 $("#dropdownContainer-1").slideUp(90); //make all inactive console.log('Menu1 closed clicking outside menu1'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="navPanel"> <!-- NAV --> <nav> <ul id="navBar"> <div class="dynamicNav"> <div class="menu1Container" style="border-style: dotted;width:50%;"> <li class="menu1">Books <!-- DropDown1--> <div id="dropdownContainer-1"> <p>1111</p> <p>1111</p> <p>1111</p> <p>1111</p> <p>1111</p> </div> </li> </div> </div> </ul> </nav> </div> 

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