Question

I'm using the popover object from Twitter's Bootstrap library in manual mode and I was wondering how I should go about closing the tooltip when the user clicks away from it.

Here is my HTML:

<a id="stats-bar" rel="popover" data-placement="top" data-trigger="manual" data-title="Title here" data-content="Hello everyone.">Test</a>

and my JavaScript:

$('#stats-bar').click(function(e) {
        $(this).popover('show');
});

How can I hide the popover when the user clicks anywhere but the popover itself? I thought of using a fixed transparent div behind the popover and set its click event but I'm not sure that's the best way.

Was it helpful?

Solution 2

I opted to use a fixed transparent div behind the popover and set its click event as this seems like the most robust and simple solution.

OTHER TIPS

I ended up wiring up to the document click event and hide any tooltips at that point

      $(document).click(function (e)
      {
          // check the parents to see if we are inside of a tool tip.  If the click came
          // from outside the tooltip, then hide our tooltip
          if ($(e.target).parents('.tooltip').length == 0) $('[data-original-title]').tooltip('hide');
      });

If you are using a manual trigger option and wiring up to the click event to show the tooltip you will need to call e.stopPropagation() to prevent the document click event from firing when showing the tooltip.

What about an generic click event listener that triggers where ever you click within the body? Check out this post, it looks similar to what you're trying to achieve.

https://stackoverflow.com/a/2125122/1013422

You would use this to close the actual popover

$('#stats-bar').popover('hide')

I would only define the function when the popup event is run and then remove it once you've closed the popup, that way you're not constantly listening for click events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top