0

my problem is the following - i need a jquery hide/show such as toggle() to hide and show a div. If i click outside of that div i need it to hide() , and if i click inside it , i want it to stay .I will have forms inside it , and i would like if click/type in them - the children of the div , the div to stay shown.

I have tried this -

$(document).ready(function(){
    $("#dropdown-btn").click(function(){
        $(this).find("#dropdown").toggle();
    });
});
$(document).on("click", function(event){
    var $trigger = $(".dropdown-btn");
    if($trigger !== event.target && !$trigger.has(event.target).length){
        $(".dropdown").hide();
    }            
});

JSfiddle

2 Answers 2

2

I believe this is what you're looking for.

  1. First, your $(".dropdown") selector should be $("#dropdown").
  2. Second, $(this).find("#dropdown") will never work, as the element is a sibling not a child. Use the raw $("#dropdown") instead.
  3. You then also need to check on the click event that you're not clicking on the button itself. I've done this by assigning $("#dropdown-btn")[0] to trigger, and then checking that it's not the target with trigger !== event.target. Note that the [0] is required for this to work, as you're looking to target the raw HTML element, rather than the jQuery object.

$(document).ready(function() {
  $("#dropdown-btn").click(function() {
    $("#dropdown").toggle();
  });
  $(document).on("click", function(event) {
    var trigger = $("#dropdown-btn")[0];
    var dropdown = $("#dropdown");
    if (dropdown !== event.target && !dropdown.has(event.target).length && trigger !== event.target) {
      $("#dropdown").hide();
    }
  });
});
#dropdown {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="dropdown-btn">Click</button>
<div id="dropdown">
  <p>Hello</p>
</div>

Hope this helps! :)

Sign up to request clarification or add additional context in comments.

1 Comment

one problem spotted , if i click the paragraph inside , it works , but if i click the div itself , it hides,
0

try event.stopPropagation()

 $(document).ready(function(){


$("#dropdown-btn").on('click', function(event){
 event.stopPropagation();
 $("#dropdown").toggle();


});



$(document).on("click", function(event){
event.stopPropagation();
$("#dropdown").hide();      


});


});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.