Search code examples
javascriptjqueryshow-hide

show hide on click anywhere and reset state properly


I have a button which shows and hides some text.

  <button id="test">
    Show Toggle
  </button>

  <div id="invisible">
    stuff to show
  </div>

I use jQuery to handle the click event on "#test". In the fadeIn callback I bind the body click event to know when the user clicks anywhere in which case I hide the text. I need to turn this click "off", if I do not the text will appear and immediately disappear again because the event is still bound.

 $('#test').click(function() {
    $('#invisible').fadeIn(500, function() {
      $('body').on('click', function(e) {
        $('#invisible').fadeOut();
        $(this).off('click');
      });
    });
  });

When I use ".off" I really only want to unbind this very specific click event on 'body' and not ALL the click events on 'body' -> yet it unbinds every! click event on body I have.

$('body').on('click', function(e) {
    $(this).off('click');
});

What would be the best approach to be able to show the text when the button is pressed and then hide it again when another press (anywhere) is executed? (this has to work multiple times)

I have prepared an example to show my problem (after showing and hiding once, the second onclick event on 'body' does not fire anymore): https://jsfiddle.net/x2q70dkm/1/


Solution

  • Try this :

    $(function() {
      $('#test').click(function(e) {
        e.stopPropagation();
        $('#invisible').fadeToggle();
      });
      
      $('body').click(function () {
        $('#invisible').fadeOut();
      });
    });
    #invisible {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="test">
      Show Toggle
    </button>
    
    <div id="invisible">
      stuff to show
    </div>