Hide popup when clicking outside

//show popup when clicking the trigger
$('#trigger').on('click touch', function(){
  $('#tooltip').show();
});			

//hide it when clicking anywhere else except the popup and the trigger
$(document).on('click touch', function(event) {
  if (!$(event.target).parents().addBack().is('#trigger')) {
    $('#tooltip').hide();
  }
});

// Stop propagation to prevent hiding "#tooltip" when clicking on it
$('#tooltip').on('click touch', function(event) {
  event.stopPropagation();
});

Demo

Comments

  1. written by: Mohammad Anzar on August 25, 2017 at 1:00 pm - Reply

    Thank you so much. It worked for me

  2. written by: shailesh on September 5, 2017 at 11:31 am - Reply

    it’s working fine.

  3. written by: Dastan on June 9, 2018 at 6:42 am - Reply

    $(document).on(‘click touch’, function (e) {
    if ($(event.target).hasClass(‘modal_wrapper’)) {
    $(‘.modal’).fadeOut();
    }
    });

    • written by: Mihai on June 30, 2018 at 7:29 pm - Reply

      First, the “function (e) ” should be “function (event) “;
      Second, this will hide your .modal, when .modal_wrapper is clicked, and I presume that .modal_wrapper is full screen width and height and that .modal is centred inside.
      This will work in this particular case.

      How about if instead of the modal, which has a wrapper that covers the entire screen so anything else in the page is basically un-clickable, you want to hide some sort of dropdown or tooltip?

      Thanks for the comment.

  4. written by: invoice123 on August 13, 2018 at 2:13 pm - Reply

    ytytr

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × = 30

This site uses Akismet to reduce spam. Learn how your comment data is processed.