Nermina Avdić Nermina Avdić - 2 months ago 6
jQuery Question

Show/hide div on a click, toggle when clicked outside of the div

This is what I have so far:
For example, when I click on button1, content1 shows, when I click on button2, content1 closes and content2 appears.
That works so far with this code:

$("#buttons a").click(function(e){
e.preventDefault();
var toShow = $(this).attr('href');
$(".togg").fadeOut();
$(toShow).fadeIn();
});


JSFiddle
What I'm trying to do is keep this function, but add some things: if content1 is already open, toggle it when I click on its button (button1), and also toggle it when clicked outside of the content1 div. In short I want to toggle it when clicked anywhere but the div itself.

Answer

As you want to check whether the click is on the element or outside the element, for that you need to check nodeName or tagName or id

$(document).click(function(e) {
  //Check the element is none of the DIVS which we wants prevent.
  if(e.target.id != "content1" && e.target.id != "content2" && e.target.id != "content3")
    {
      //Hide the content div which is visible now.
      $('div.togg:visible').hide();
    }
});

You just need to create a dynamic selector to achieve kind of dynamic toggling function.

$("#buttons a").click(function(e){
    var selector = $('.'+$(this).attr('id'));
    selector.toggle();
    $('div.togg').not(selector).hide();
});

$("#buttons a").click(function(e){
    var selector = $('.'+$(this).attr('id'));
    selector.toggle();
    $('div.togg').not(selector).hide();
});
$(document).click(function(e) {
  //Check the element is none of the DIVS which we wants prevent.
  if(e.target.id != "content1" && e.target.id != "content2" && e.target.id != "content3")
    {
      //Hide the content div which is visible now.
      $('div.togg:visible').hide();
    }
});
.content1 {display:none;}
.content2 {display:none;}
.content3 {display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
  <a href="#" id="content1">Div 1</a>
  <a href="#" id="content2">Div 2</a>
  <a href="#" id="content3">Div 3</a>
</div>
<div>
  <div class="content1 togg">1111</div>
  <div class="content2 togg">2222</div>
  <div class="content3 togg">3333</div>
</div>