Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Bootstrap popovers (or any item in general) when a user clicks away from it?

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.

like image 887
Jake Petroules Avatar asked Feb 15 '12 22:02

Jake Petroules


People also ask

How do I destroy bootstrap popover?

Use the popver(“detroy”) to destroy the popover.

How do you toggle popover?

To create a popover, add the data-toggle="popover" attribute to an element. Note: Popovers must be initialized with jQuery: select the specified element and call the popover() method.

How do I customize bootstrap popover?

To create a popover, you need to add the data-bs-toggle="popover" attribute to an element. Whereas, popover's title and its content that would display upon trigger or activation can be specified using the title and data-bs-content attribute respectively. Here is the standard markup for adding a popover to a button.


2 Answers

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.

like image 191
Kevin Avatar answered Oct 07 '22 20:10

Kevin


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.

like image 37
Jake Petroules Avatar answered Oct 07 '22 20:10

Jake Petroules