Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing Bootstrap Popover When User Clicks Outside Popover

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;
        }
    });
});
like image 265
arcdegree Avatar asked Oct 30 '13 22:10

arcdegree


2 Answers

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');
}
like image 51
amit_g Avatar answered Sep 20 '22 20:09

amit_g


Use this code:

$(document).mouseup(function (e) {
    if ($('.popover').has(e.target).length === 0) {
        $('.popover').toggleClass('in').remove();
        return;
    }
});
like image 40
kraxor Avatar answered Sep 21 '22 20:09

kraxor