5
votes

I have some content that's dynamically loaded on a webpage that contains popovers. For this reason I have to bind them to the body so they load and appear correctly.

I'd like to find a way to hide the popovers when a user clicks outside the popover or on another popover trigger.

I found that if I "hide" the popover, the popover does indeed hide but the elements remain in the DOM. This means that active links in the popover remain "clickable".

If I instead destroy the popover, it hides, but is unable to re-activate if clicked on. The only reliable way to hide the popover is to use "toggle". This increases the complexity of determining which popovers to hide.

Please see this JSFiddle with all this code.

HTML

<a href="#" data-toggle="popover" data-original-title="" data-content="<a href='http://www.yahoo.com'>http://www.yahoo.com</a>" class="some-popover-link">Yahoo</a>
<br><br> <br> <br> <br>  <a href="#" data-toggle="popover" data-original-title="" data-content="<a href='http://www.google.com'>http://www.google.com</a>" class="some-popover-link">Google</a>
<br><br> <br> <br> <br>  <a href="#" data-toggle="popover" data-original-title="" data-content="<a href='http://www.microsoft.com'>http://www.microsoft.com</a>" class="some-popover-link">Microsoft</a>

JavaScript

$('.some-popover-link').popover({
    container: 'body',
    html: true,
    placement: 'bottom'
});

$(document).click(function (e) {
    $('.some-popover-link').each(function () {
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide'); // this hides popover, but content remains
            return;
        }
    });
});
2
Seems to work correctly in your fiddle.. Or does your fiddle demonstrate the problem and i'm just not seeing it? - Trevor
The fiddle illustrates that the popovers are hiding as expected, but div.popover is not getting removed from the DIV. If you hover where the link in the popup was, it will still click-through to a website. I'll try in other browsers to. - arcdegree
Ahh I finally see what is happening. It looks like @kraxor has a solution. Have you tried it? - Trevor
Yes, it didn't quite solve the problem though. @amit_g has an internal but workable solution. - arcdegree

2 Answers

8
votes

This relies on internal implementation so be careful but it should work. JSFiddle Link

if ($(this).data('bs.popover').tip().hasClass('in')) {
    $(this).popover('toggle');
}
6
votes

Use this code:

$(document).mouseup(function (e) {
    if ($('.popover').has(e.target).length === 0) {
        $('.popover').toggleClass('in').remove();
        return;
    }
});