Close a Twitter Bootstrap Popover when Clicking Outside

A vexing topic for me and a bunch of other people on stackoverflow, the problem being that Twitter Bootstrap Popovers don’t close when you click outside to anywhere else on the document.

This might not be your desired outcome, simply: when clicking outside a popover, wouldn’t you want it to close?

The code below makes this possible:

$('[data-toggle="popover"]').popover();

$('body').on('click', function (e) {
    $('[data-toggle="popover"]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
        }
    });
});

A note about the use of $(':not(#anything)') as my body selector. This is due to iOS not binding click events to ‘html’ or ‘body’.

To put it short, this is a bulletproof way to detect clicks anywhere on the document (providing you don’t have a div with an id of ‘anything’).

Live Example Here

This entry was posted in Bootstrap, Code. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.