简体   繁体   中英

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;
        }
    });
});

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');
}

Use this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM