lys916
lys916

Reputation: 317

jquery hide toggle when click anywhere on document

i'm able to hide dropdown toggle when clicking anywhere on document by using even.stopPropagation() but how do i make it so even when i click on links on the document nothing happens except hiding the toggle dropdown. so basically i don't want anything to happen until i hide the dropdown toggle first.

https://jsfiddle.net/dbgwktxz/

notice when click on menu, the list toggles. when click outside of the div link the list hides. when i click inside the div link the list hides and takes me to google.com. how do i make it so when click inside div link, it hides the list without taking me to google.com. once the list is hidden i can go ahead and click the link if i want to. Thank you for your help.

//HTML
<div id="menu">Menu</div>
<div id="dropdown">
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
</div>
<a href="www.google.com"><div id="link">Google</div></a>

//CSS
#dropdown{
 display: none;
}
#link {
 height: 100px;
 border:1px solid blue;
}

//JQUERY
$("#menu").click(function(event){
  event.stopPropagation();
  $("#dropdown").toggle()
});

$(document).click(function(){
  $("#dropdown").hide();
});

Upvotes: 2

Views: 1295

Answers (2)

Jai
Jai

Reputation: 74748

how do i make it so when click inside div link, it hides the list without taking me to google.com.once the list is hidden i can go ahead and click the link if i want to.

change your selector to:

$("#menu, #link")

and make use of event.preventDefault();.


Like below:

//JQUERY
$("#menu, #link").click(function(event){
  event.stopPropagation();
  if(event.target.parentNode.tagName.toLowerCase() === "a" && 
      $("#dropdown").is(':visible')){ 
      event.preventDefault();
  }
  $("#dropdown").toggle()
});

Your updated fiddle link.

Upvotes: 0

Joy Biswas
Joy Biswas

Reputation: 6527

You need to identify that the click on the document is from your ul's children or not. If the clicked target is not a children or self the ul dont close it.

Use .closest() https://api.jquery.com/closest/ Snippet added

//JQUERY
$("#menu").click(function(event){
  event.stopPropagation();
  $("#dropdown").toggle()
});

$(document).click(function(e){
  if($(e.target).closest("#dropdown").length===0){
  	$("#dropdown").hide();
  };
});
#dropdown{
    border:1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">Menu</div>
<div id="dropdown">
    <ul>
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
    </ul>
</div>

Upvotes: 2

Related Questions