Quick Hack: One Bootstrap Popover at a Time

Bootstrap is my new favorite front-end framework, and I really like the JavaScript popovers for contextual information and help. One thing I don’t like about them is they aren’t aware of each other. If you only want 1 to be visible on your page at a time, here’s a quick hack. It does involve 1 global variable, which should make you feel dirty.

One Bootstrap Popover at a Time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Global variable - cringe
var visiblePopover;

// enable popovers - all of mine in this instance have a class of .hov
$(".hov").popover({ 'container': 'body' });

// only allow 1 popover at a time
// all my popovers hav
$('.hov').on('click', function(e) {
// don't fall through
e.stopPropagation();
var $this = $(this);
// check if the one clicked is now shown
if ($this.data('popover').tip().hasClass('in')) {
// if another was showing, hide it
visiblePopover && visiblePopover.popover('hide');
// then store the current popover
visiblePopover = $this;
} else {
// if it was hidden, then nothing must be showing
visiblePopover = '';
}
});

// hide all popovers if any non-popover part of the body is clicked
$("body").on('click', function () {
$(".hov").popover('hide');
visiblePopover = '';
});

Check it out over here. Click on a bubble at the top, then click on a different bubble or somewhere else on the page.