Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  50] [ 1]  / answers: 1 / hits: 163267  / 13 Years ago, fri, january 20, 2012, 12:00:00

I'm currently using popovers with Twitter Bootstrap, initiated like this:



$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).click(function(e) {
$(this).popover('toggle');
e.preventDefault();
});


As you can see, they're triggered manually, and clicking on .popup-marker (which is a div with a background image) toggles a popover. This works great, but I'd like to also be able to close the popover with a click anywhere else on the page (but not on the popover itself!).



I've tried a few different things, including the following, but with no results to show for it:



$('body').click(function(e) {
$('.popup-marker').popover('hide');
});


How can I close the popover with a click anywhere else on the page, but not with a click onthe popover itself?


More From » jquery

 Answers
16

Presuming that only one popover can be visible at any time, you can use a set of flags to mark when there's a popover visible, and only then hide them.



If you set the event listener on the document body, it will trigger when you click the element marked with 'popup-marker'. So you'll have to call stopPropagation() on the event object. And apply the same trick when clicking on the popover itself.



Below is a working JavaScript code that does this. It uses jQuery >= 1.7



jQuery(function() {
var isVisible = false;

var hideAllPopovers = function() {
$('.popup-marker').each(function() {
$(this).popover('hide');
});
};

$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).on('click', function(e) {
// if any other popovers are visible, hide them
if(isVisible) {
hideAllPopovers();
}

$(this).popover('show');

// handle clicking on the popover itself
$('.popover').off('click').on('click', function(e) {
e.stopPropagation(); // prevent event for bubbling up => will not get caught with document.onclick
});

isVisible = true;
e.stopPropagation();
});


$(document).on('click', function(e) {
hideAllPopovers();
isVisible = false;
});
});


http://jsfiddle.net/AFffL/539/



The only caveat is that you won't be able to open 2 popovers at the same time. But I think that would be confusing for the user, anyway :-)


[#87883] Friday, January 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darrell

Total Points: 109
Total Questions: 113
Total Answers: 113

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;