1

I tried to make a content, that gets viewed if you click a button an hides if you click that button again but also hides if you click anywhere else on the side except the content itself.
Like on www.w3schools.com if you click on tutorials.
my attempt was this:

$(":not(#content)").click does not work. But even if, it would also get triggered all the times the content is not visible anyways. No good code.

$(document).ready(function() {
  $("button").click(function() {
    $("#content").toggle();

  });
  $(":not(#content)").click(function() {
    $("#content").hide();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">This is the Content</div>

<button>switch</button>

<div> This is somewhere else </div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nils
  • 275
  • 3
  • 12

2 Answers2

2

You can add a click event listener to the document that hides the content if the clicked element was not the button or contained inside the content.

$(document).ready(function() {
  $("button").click(function() {
    $("#content").toggle();
  });
  $(document).click(function(e) {
    if(!$(e.target).closest('button, #content').length){
      $('#content').hide();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" style="display: none;">This is the Content</div>
<button>switch</button>
<div> This is somewhere else </div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

The content is not showing anymore because both events are fired when you click on "switch". If you need to prevent another external click event, use event.stopPropagation() and event.cancelBubble = true.

Comment these both lines and you will see the difference.

$(document).ready(function(){
  $("button").click(function(event){
    console.log("click button");
     event.stopPropagation();
     event.cancelBubble=true; 
    $("#content").toggle();
    
  });
  $("body").click(function(){
    console.log("click outside");
    $("#content").hide();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">This is the Content</div>

<button>switch</button>

<div> This is somewhere else </div>
F.Igor
  • 4,119
  • 1
  • 18
  • 26
  • $event.stopPropagation(); if the "$" is in front it also works for buttons that are created during the runtime. $(document).ready(function(){ $(document).on('click', '.sorting', function(){ //$(".sorting").on('click', function(){ //$("button").click(function(){ alert("clicked the button"); $(this).after(''); $event.stopPropagation(); }); //$(document).on('click', document, function(){ $(document).click(function() { alert("document was clicked"); }); }); – Nils Oct 13 '20 at 20:41