3

I have my dropdown, it is working on click of its parent anchor tag, but now i want to close it on body click

I have try to do it with event.stopPropagation(); but it didn't work, here is my code -

$(".mydropd > a").click(function() { $(this).siblings(".mycustom_dropd").slideToggle(); }); $('body').click(function(event) { $(".mycustom_dropd").slideUp(); event.preventDefault(); event.stopPropagation(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li class="mydropd"> <a href="#" class="mydropd_a">menu <span class="line1"></span> <span class="line2"></span> <span class="line3"></span> </a> <ul class="mycustom_dropd"> <li> <a href="#"><img src="images/vibgyor.png"> VIBGYOR</a> </li> <li><a href="#">MULTIPLAYER</a></li> <li><a href="#">RAPTOP</a></li> <li><a href="#">HELP</a></li> <li><a href="#">PROFILE</a></li> </ul>

6
  • 1
    Can you make this piece of code a runnable snippet? Commented Feb 5, 2018 at 7:21
  • 1
    I feel that the portion where you are clicking, the body wouldn't be having that height. So just try giving height:100vh and width:100vh to body and then try clicking.. Your code works with that.. or else try attaching it to document instead of body but that might lead to some other issues. Commented Feb 5, 2018 at 7:26
  • when you say it did not work what actually happening? not closing the menu? re-opening the menu? please the result in details also make the your code runnable so we can reproduce your issue. Commented Feb 5, 2018 at 7:26
  • 1
    Please wrap your javascript/jquery code in JQuery ready function. api.jquery.com/ready Commented Feb 5, 2018 at 7:30
  • Check here stackoverflow.com/questions/1403615/… Commented Feb 5, 2018 at 7:35

1 Answer 1

2

Wrap code in jQuery ready function.

<script type="text/javascript"> $(function() { $(".mydropd > a").click(function(){ $(this).siblings(".mycustom_dropd").slideToggle(); event.preventDefault(); event.stopPropagation(); }); $('body').click(function(event){ $(".mycustom_dropd").slideUp(); }); }); </script> <div class="mydropd"> <a href="#" class="mydropd_a">Click Here <span class="line1"></span> <span class="line2"></span> <span class="line3"></span> </a> <ul class="mycustom_dropd"> <li><a href="#"><img src="images/vibgyor.png"> VIBGYOR</a></li> <li><a href="#">MULTIPLAYER</a></li> <li><a href="#">RAPTOP</a></li> <li><a href="#">HELP</a></li> <li><a href="#">PROFILE</a></li> </ul> </div> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.